bhaktimehta's bloghttp://www.java.net/blog/bhaktimehta
enBook review: "JavaServer Faces: Introduction By Example" by Josh Juneauhttp://www.java.net/blog/bhaktimehta/archive/2015/01/06/book-review-javaserver-faces-introduction-example-josh-juneau
<!-- 202 | 0 --><img src="/images/people/bhakti_mehta.jpg" border="0", align="left" /><p> I had the pleasure to review <b>JavaServer Faces: Introduction by Example</b> by <a href="http://jj-blogger.blogspot.com/">Josh Juneau</a> which has been published by Apress in December 2014.<br />
<img src="http://www.apress.com/media/catalog/product/cache/9/image/9df78eab33525d08d6e5fb8d27136e95/A/9/A9781484208397-3d_1.png"> </img><br />
The highlight of the book was the simplicity with which Josh has covered some of the most complicated topics related to JavaServer Faces (JSF).<br />
I like how smoothly and seamlessly he can transition from the simple recipes to the more involved and detailed discussions in each chapter. I also<br />
appreciated the way he covers every topic as a recipe and has an example source code and a detailed explanation for each recipe's code.</p>
<p>
Here are the details of each chapter in the book</p>
<p><h2>Chapter 1: Introduction to Servlets</h2>
<p>Chapter 1 covers detailed introduction to Servlets with examples from setting up the Java Enterprise environment, installing GlassFish,<br />
developing the first servlet, to packaging and deploying the servlet. It also discusses about topics related to dispatching requests,<br />
filtering web requests, adding listeners, downloading files etc. There is a section that covers Servlet 3.0 Non-Blocking I/O and Async APIs<br />
which will be very beneficial for readers interested in processing requests asynchronously and not having to block for a long running task<br />
to complete and send the response.</p>
<h2>Chapter 2: JavaServer Pages</h2>
<p>Chapter 2 covers JavaServer Pages(JSP) and starts with a simple JSP. It covers the lifecycle of the JSP, embedding Java in JSP page,<br />
embedding expressions in EL, creating custom JSP tags, error handling, disabling scriptlets in JSP pages etc. I particularly liked the<br />
database sample which shows how to create an input form for a database record and loop through the records.<br />
The first two chapters covered the initial foundation extremely well to get started with JavaServer Faces in Chapter 3.</p>
<h2>Chapter 3: The Basics of JavaServer Faces</h2>
<p>This chapter begins with developing a simple JSF example. It covers details on breaking down a JSF application which consists of the<br />
components for a JSF application. It covers the life cycle of a JSF application. Further sections discuss on writing a managed bean<br />
and access it within a JSF view using EL. The Managed Bean Scopes section was very informative. The building sophisticated views<br />
with components covered how to build well formed views with JSF and HTML. It also highlighted navigation techniques within JSF applications<br />
and how to validate inputs in the application before they can be persisted.</p>
<h2>Chapter 4: Facelets</h2>
<p>Chapter 4 starts off with Facelets which is the default view definition language since JSF 2.0. Josh shows how to use Netbeans IDE<br />
to create Facelet Template view and then how to apply the template to a view. This section also covered how to reuse a<br />
component and its resources in any JSF view within the application by utilizing the facelets <b>ui:component</b> tag.<br />
Also it covered handling variable length data with <b>ui:repeat</b> tag<br />
I particularly liked the section on debugging the view layout with <b>ui.debug</b> tag</p>
<h2>Chapter 5: Java Server Faces Standard components </h2>
<p>This chapter focusses on JSF component library and shows how to use external component libraries. It showed how to use<br />
Bean validation with JSF. Using a concrete example of subscribing to a news letter the chapter demonstrates various<br />
topics layering one on the other. This is one of the best chapters of the book.</p>
<h2>Chapter 6: Advanced Java Server Faces and Ajax </h2>
<p>This chapter delves into using JSF components with Ajax. It covers Ajax validation using <b>f:ajax</b> tag to add immediate validation<br />
to JSF views thus avoiding the need for JavaScript for client side validation and allows asynchronous validation between the client and<br />
server logic in the JSF managed bean. Additionally it covers how to make partial page updates which was very interesting.<br />
This chapter demonstrates how to listen for system life cycle events such as <b>PreDestroyApplicationEvent</b> and <b>PostConstructApplicationEvent</b>.<br />
Another example is how to get periodic updates to pages without doing a manual refresh using the poll component. The section on<br />
developing JSF components containing HTML5 was very good read which demonstrated how to create an HTML5 video component<br />
from a JSF composite component. It also covers a flow instance which is a new feature in JSF 2.2 allowing sharing of information<br />
between the views of a flow instance.</p>
<p>Overall I found that this book was a great source of information for JavaEE developers wanting to develop component based<br />
user interfaces running on browsers for rapid development and deployment.<br />
I would highly recommend this book to anyone who wishes to know about JavaServer Faces from scratch as well as advanced users<br />
who want to get more acquainted with the nuts and bolts of newer features.</p>
http://www.java.net/blog/bhaktimehta/archive/2015/01/06/book-review-javaserver-faces-introduction-example-josh-juneau#commentsAjaxBlogsGlassFishNetBeansTue, 06 Jan 2015 21:50:49 +0000bhaktimehta931367 at http://www.java.netMy new book "RESTful Java Patterns and Best Practices"http://www.java.net/blog/bhaktimehta/archive/2014/09/24/my-new-book-restful-java-patterns-and-best-practices
<!-- 316 | 0 --><img src="/images/people/bhakti_mehta.jpg" border="0", align="left" /><p><b><a href="https://www.packtpub.com/web-development/restful-java-patterns-and-best-practices">RESTful Java Patterns and Best Practices</a></b> is the second book which I have worked on and is recently published.</p>
<p>
<a href="https://www.packtpub.com/web-development/restful-java-patterns-and-best-practices"><img src="https://www.java.net/sites/default/files/7963OS_cov.jpg"></img></a></p>
<h1>Overview</h1>
<p>The convergence of social networking, cloud computing, and era of mobile applications creates a generation<br />
of emerging technologies that allow different networked devices to communicate with each other over the Internet.<br />
As the technology landscape evolves, today’s applications are built on the notion of producing and consuming APIs<br />
This API based architecture enables agile development, easier adoption and prevalence, scale and integration with<br />
applications within and outside the enterprise.</p>
<p>The advent of mobile applications calls for a stricter delineated client-server model. Companies building applications on IOS<br />
and Android platform can consume the REST based API and extend and deepen their reach by combining data from multiple<br />
platforms because of the API centric REST based architecture. </p>
<p>The widespread adoption of REST and JSON opens up the possibilities of applications incorporating and leveraging<br />
functionality from other applications as needed. Popularity of REST is mainly because it enables building lightweight<br />
simple, cost-effective modular interfaces, which can be consumed by a variety of clients. </p>
<p>One of the most important considerations for the apps is dealing with security. The developers building apps should not be<br />
concerned with the user's credentials. .The clients can be acting on behalf of other users and must be authorized to perform<br />
actions for them without the user having to share his credentials for username and password.This is where the OAuth 2.0<br />
specification comes into picture.</p>
<p>Another important aspect to consider when building distributed applications is traceability, which will involve logging the<br />
data related to requests for debugging purposes in an environment encompassing multiple micro services, which can be<br />
geographically distributed and deal with thousands of requests.</p>
<p>Similarly caching, rate-limiting, validation and exception handling as well as asynchronous processing are essential<br />
elements to be considered when building RESTful services. Micro services based architecture comprises of breaking<br />
a monolithic application into fine grained services which can provide benefits of simplicity, separation of concerns,<br />
isolation of problems, independent scale up and scale down thus providing the foundation for a resilient architecture.</p>
<p><b><a href="https://www.packtpub.com/web-development/restful-java-patterns-and-best-practices">RESTful Java Patterns and Best Practices</a></b> aims to cover all these topics in detail with code samples using JAX-RS<br />
along with best practices and case studies from the ubiquitous platforms like Facebook, GitHub, Twitter, PayPal etc.</p>
<h1>What this book will cover</h1>
<ul>
<li>How to build RESTful web services using <b>JAX-RS 2.0 API</b></li>
<li>Gain insights into techniques related to <b>versioning</b>, <b>error handling</b>, <b>response codes</b> in REST</li>
<li>Clarify advanced topics related to <b>SAML</b> and <b>OAUTH 2.0</b>, similarities between <b>SAML</b> and <b>3-legged OAuth</b><br />
as well as best practices for <b>OAuth</b></li>
<li>Discuss <b>caching techniques</b>, <b>validation</b>, <b>rate-limiting</b>, <b>asynchronous operations</b> and other best practices<br />
to improve application responsiveness</li>
<li>Review best practices for <b>logging</b>, <b>pagination</b>, <b>documentation</b>, <b>testing</b> of RESTful services. </li>
<li>Show how highly available cloud applications tend to move to a networked component model where<br />
applications are decomposed into <b>micro services</b>, which can be deployed and scaled independently </li>
<li>Cover the future of REST and evolving standards along with case studies on how different enterprises use them</li>
<li>Compare and contrast other technologies like <b>WebHooks</b>, <b>WebSockets</b> and <b>Server-Sent Events</b> for delivering real time data to clients</li>
<li>Compare REST API from <b>Twitter</b>, <b>GitHub</b>, <b>Facebook</b> and others</li>
</ul>
<h1>Who this book is for</h1>
<p><a href="https://www.packtpub.com/web-development/restful-java-patterns-and-best-practices">RESTful Java Patterns and best practices</a>, is a practical, hands-on guide that provides you with clear and pragmatic<br />
information to take advantage of the real power of RESTful services and gives you a good foundation for using them<br />
in your applications. The book is aimed at novice developers who want to gain insights in building RESTful services as well<br />
as advanced developers who want to delve into complicated topics.</p>
<h1>Approach</h1>
<p>A step-by-step approach to build complex RESTful services for the real world applications explained<br />
in a conversational and easy-to-follow style. Each topic is explained sequentially and scrupulously by building<br />
on ideas and discussions covered in previous chapters, thus tying the concepts neatly together</p>
<p>. <a href="https://twitter.com/bhakti_mehta" class="twitter-follow-button" data-show-count="false">Follow @bhakti_mehta</a></p>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>http://www.java.net/blog/bhaktimehta/archive/2014/09/24/my-new-book-restful-java-patterns-and-best-practices#commentsBlogsGlassFishGlassFishJava EnterpriseJava Web Services and XMLThu, 25 Sep 2014 05:11:51 +0000bhaktimehta930617 at http://www.java.netHow JDK 8 standardizes and augments to Guava library functionalitieshttp://www.java.net/blog/bhaktimehta/archive/2014/07/14/how-jdk-8-standardizes-and-augments-guava-library-functionalities
<!-- | 0 --><p><a href="http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html">JDK 8</a> introduced a lot of new features and improvements in the platform from <b>Lamda expressions, Stream collection types,<br />
Functional interfaces, Type annotations, Nashorn</b> etc.</p>
<p><a href="https://code.google.com/p/guava-libraries/">Guava library</a> from Google provided some support for functional programming idioms prior to JDK 8.<br />
I have been using Guava for some of my projects. So here is a small write up on<br />
how new functionality added in <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html">JDK 8</a> makes it possible to achieve standardized way to functionality offered by Google's <a href="https://code.google.com/p/guava-libraries/">Guava</a>.<br />
This article further highlights similarities and differences between the two APIs and was inspired by <a href="https://groups.google.com/forum/#!topic/guava-discuss/fEdrMyNa8tA">this</a> discussion on google groups.</p>
<p>The following table shows some of the API which I will cover in detail wrt. Guava and JDK 8</p>
<table border="1">
<tr>
<th> Functionality
</th>
<th> Guava
</th>
<th> JDK 8
</th>
</tr>
<tr>
<td> Predicate
</td>
<td> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Predicate.html">apply(T input)</a>
</td>
<td> <a href="http://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html">test(T input)</a>
</td>
</tr>
<tr>
<td> Combining predicates
</td>
<td> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Predicates.html"> Predicates.and/or/not</a>
</td>
<td> <a href="http://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html">Predicate.and/or/negate</a>
</td>
</tr>
<tr>
<td> Supplier
</td>
<td> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Supplier.html">Suplier.get</a>
</td>
<td> <a href="http://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html">Supplier.get</a>
</td>
</tr>
<tr>
<td> Joiner/StringJoiner
</td>
<td> <a href="http://guava-libraries.googlecode.com/svn-history/r14/trunk/javadoc/com/google/common/base/Joiner.html">Joiner.join()</a>
</td>
<td> <a href="http://download.java.net/lambda/b81/docs/api/java/util/StringJoiner.html">StringJoiner.add()</a>
</td>
</tr>
<tr>
<td> SettableFuture<T>/CompletableFuture<T>
</td>
<td> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/SettableFuture.html">SettableFuture.set(T input)</a>
</td>
<td> <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html">CompletableFuture.complete(T input)</a>
</td>
</tr>
<tr>
<td> Optional
</td>
<td> <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html">Optional.of/ofNullable/empty</a>
</td>
<td> <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Optional.html">Optional.of/fromNullable/absent</a>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<h1>Source Code</h1>
<p>The following code snippets are part of a complete sample available at <a href="https://github.com/bhakti-mehta/samples/tree/master/jdk8-and-guava">https://github.com/bhakti-mehta/samples/tree/master/jdk8-and-guava</a><br />
For the sake of simplicty, I have a simple sample which has a collection of people's data.<br />
We start with a simple POJO Person as shown below for both the JDK 8 and Guava cases<br />
<pre class="prettyprint"><code>public class Person {<br /><br /> private String firstName;<br /><br /> private String lastName;<br /><br /> private int age;<br /><br /> private Optional<String> suffix;<br />...<br />...</code></pre>
<p>As shown in the above snippet the Person class has fields like firstName, lastName, age, an <b>Optional</b> suffix and getters and setters for these.</p>
<h1>1.0 Predicates</h1>
<p>A Predicate is a boolean valued function for an argument.<br />
Now we will define Predicate in Guava and JDK 8 and show how to get the list of people whose age is over 30.</p>
<p>The following snippet shows how to use a <b>Predicate<Person></b> which has an <b>apply (Person input)</b> method that takes a <b>Person</b> object as input and validates if the age of the person is above 30</p>
<h2> 1.1 Predicate with Guava</h2>
<p>Here is the code showing how to use <b>com.google.common.base.Predicate</b><br />
<pre class="prettyprint"><code> final List<Person> persons = Person.createList();<br /><br /> final Predicate<Person> ageOver30 = new Predicate<Person>() {<br /> public boolean apply(Person input) {<br /> return input.getAge() > 30;<br /> }<br /> <br /> };<br /><br /> Collection<Person> filteredPersons = Collections2.filter(persons,<br /> ageOver30);<br /> </code></pre><br />
The above snippet returns a <b>Collection<Person></b> that satisfy that predicate <b>ageOver30</b> by using <b>Collections2.filter()</b> method which takes a Predicate as an argument. </p>
<h2>1.2 Predicate with JDK8</h2>
<p>Here is a snippet of how to achieve the same behaviour using <b> java.util.function.Predicate</b><br />
The <b>Predicate<Person></b> has a test method what checks for the <b>ageOver30</b> Predicate<br />
<pre class="prettyprint"><code>final List<Person> persons = Person.createList();<br /><br /> final Predicate<Person> ageOver30 = new Predicate<Person>() {<br /> public boolean test(Person person) {<br /> return person.getAge() > 30;<br /><br /> }<br /> };<br /><br /> Stream<Person> filteredPersons = persons.stream().filter(<br /> ageOver30);</code></pre>
<p>The above snippet transforms (List<Person>) into a Stream with the <b>stream()</b> method on the Collection interface. The <b>filter()</b> method takes the <b>ageOver30</b> Predicate and returns a stream that satisfies the criteria.</p>
<h1>2.0 Combining Predicates</h1>
<p>Predicates can be combined with other predicates. For example in our sample we need to find a list of people<br />
whose age is over 30 and whose name begins with "W", we can achieve this functionality with creating two<br />
Predicates </p>
<ul>
<li><b>ageOver30</b></li>
<li><b>nameBeginsWith</b></li>
</ul>
<p>Next we combine the 2 predicates by calling the <b>and</b> method with these two predicates.</p>
<h2>2.1 Combining Predicates with Guava</h2>
<p>Here is a code snippet with Guava predicate class which defines 2 predicates <b>ageOver30</b> and <b>nameBeginsWith</b><br />
<pre class="prettyprint"><code> final List<Person> persons = Person.createList();<br /><br /> final Predicate<Person> ageOver30 = new Predicate<Person>() {<br /> public boolean apply(Person input) {<br /> return input.getAge() > 30;<br /> }<br /><br /> };<br /> final Predicate<Person> nameBeginsWith = new Predicate<Person>() {<br /> public boolean apply(Person person) {<br /> return person.getLastName().startsWith("W");<br /><br /> }<br /> };<br /><br /> Collection<Person> filteredPersons = Collections2.filter(persons,<br /> Predicates.and(ageOver30, nameBeginsWith));</code></pre><br />
The above snippet returns a filtered list from the Collections2.filter() method by passing the combined predicates <b>Predicates.and(ageOver30,nameBeginsWith)</b></p>
<h2> 2.2 Combining Predicates with JDK 8</h2>
<p>Here is the same functionality using <b>java.util.function.Predicate.and/or/negate</b><br />
<pre class="prettyprint"><code> public Stream<Person> getMultiplePredicates() {<br /> final List<Person> persons = Person.createList();<br /><br /> final Predicate<Person> ageOver30 = new Predicate<Person>() {<br /> public boolean test(Person person) {<br /> return person.getAge() > 30;<br /><br /> }<br /> };<br /> final Predicate<Person> nameBeginsWith = new Predicate<Person>() {<br /> public boolean test(Person person) {<br /> return person.getLastName().startsWith("W") ;<br /><br /> }<br /> };<br /><br /> Stream<Person> filteredPersons = persons.stream().filter(<br /> ageOver30.and(nameBeginsWith));<br /> return filteredPersons;<br /> }</code></pre><br />
The above snippet returns a stream by filtering the combined <b>ageOver30.and(nameBeginsWith))</b> predicates.</p>
<h1>3.0 Supplier </h1>
<p>Supplier is a functional interface that encapsulates an operation and allows lazy evaluation of the operation. It supplies objects of a particular type.</p>
<h2> 3.1 Supplier in Guava</h2>
<p>Here is a snippet of how to use <b>com.google.common.base.Supplier</b> in Guava<br />
<pre class="prettyprint"><code>public int getSupplier() {<br /> Supplier<Person> person = new Supplier<Person>() {<br /> public Person get() {<br /> return new Person("James", "Sculley", 53,Optional.of("Sr"));<br /> }<br /> };<br /><br /> return person.get().getAge();<br /> }</code></pre><br />
As seen in the above snippet we create a new <b>Supplier<Person></b> and the <b>get()</b> method returns a new instance of <b>Person</b>.</p>
<h2> 3.2 Supplier in JDK 8 </h2>
<p>The following code shows how to create a <b>java.util.function.Supplier</b> with Lamda expressions in JDK 8.<br />
<pre class="prettyprint"><code>public int getSupplier() {<br /> final List<Person> persons = Person.createList();<br /> Supplier<Person> anotherone = () -> { Person psn = new Person("James", "Sculley", 53, Optional.of("Sr"));<br /> return psn;<br /> };<br /><br /> return anotherone.get().getAge();<br /> }</code></pre><br />
As shown in above snippet, similar to the Guava case, we create a new <b>Supplier<Person></b> and the <b>get()</b> method returns a new instance of <b>Person</b>.</p>
<h1>4.0 Joiner/StringJoiner</h1>
<p>A Joiner in Guava/ StringJoiner in JDK8 joins text together separated by delimiters.</p>
<h2> 4.1 Joiner in Guava</h2>
<p>Here is an example of a Joiner in Guava which joins the various string delimited by ';'<br />
<pre class="prettyprint"><code> public String getJoiner() {<br /> Joiner joiner = Joiner.on("; ");<br /> return joiner.join("Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red");<br /> }</code></pre>
<h2> 4.2 StringJoiner in JDK 8</h2>
<p>The following snippet shows how the equivalent functionality in JDK 8 is:<br />
<pre class="prettyprint"><code> public String getJoiner() {<br /> StringJoiner joiner = new StringJoiner("; ");<br /> return joiner.add("Violet").add( "Indigo").add( "Blue").add( "Green")<br /> .add("Yellow").add( "Orange").add( "Red").toString();<br /> }</code></pre>
<h1>5.0 java.util.Optional</h1>
<p><b>java.util.Optional<T></b> is a way for programmers to indicate that there may have been a value initially, that is now set to null or no value was ever found. </p>
<h2> 5.1 Optional in Guava</h2>
<p>Here is a sample of <b>com.google.common.base.Optional</b></p>
<ul>
<li>Optional.of(T) :Make an Optional containing the given non-null value, or fail fast on null.</li>
<li>Optional.absent(): Return an absent Optional of some type.</li>
<li>Optional.fromNullable(T): Turn the given possibly-null reference into an Optional, treating non-null as present and null as absent.</li>
</ul>
<p>Here is the code which declares the suffix of a Person as Optional<br />
<pre class="prettyprint"><code>Optional suffix = Optional.of("Sr")</code></pre>
<h2> 5.2 Optional in JDK8 </h2>
<ul>
<li>
Optional.of(T); Returns an Optional with the specified present non-null value.
</li>
<li>
Optional.ofNullable(T);Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional
</li>
<li>
Optional.empty(); Returns an empty Optional instance. No value is present for this Optional.
</li>
</ul>
<p>Here is the code which declares the suffix of a Person as Optional<br />
<pre class="prettyprint"><code>Optional suffix = Optional.of("Sr")</code></pre>
<h1>6.0 SettableFuture in Guava/ CompletableFuture in JDK 8</h1>
<p>These extend the Future<T> and provide asynchronous, event-driven programming model in contrast to the blocking nature of Future<T> in java.</p>
<p>SettableFuture is similar to CompletableFuture in JDK 8 which can help to create a Future object for an event or a task which will occur. Code calling future.get() will block forever. When the asynchronous task finishes execution it calls future.set(). Now all the code blocking on Future.get() will get the details.</p>
<h2> 6.1 SettableFuture in Guava</h2>
<p>Here is a simple case demonstrating this functionality in Guava and JDK8<br />
<pre class="prettyprint"><code>public SettableFuture<String> getSettableFuture() {<br /> final SettableFuture<String> future = SettableFuture.create();<br /> return future;<br /> }<br /><br /> public void handleFutureTask(SettableFuture<String> sf) throws InterruptedException {<br /> Thread.sleep(5000);<br /> sf.set("Test");<br /> }</code></pre><br />
In the above snippet we create a new <b>SettableFuture</b> in default state using <b>SettableFuture.create()</b>. The set() method sets the value for this future object.</p>
<h2>6.2 CompletableFuture in JDK8</h2>
<p>The following code shows how the equivalent functionality is achieved with CompletableFuture in JDK 8.<br />
<pre class="prettyprint"><code>public CompletableFuture<String> getCompletableFuture() {<br /> final CompletableFuture<String> future = new CompletableFuture<>();<br /> return future;<br /> }<br /><br /> public void handleFutureTask(CompletableFuture<String> cf) throws InterruptedException {<br /> Thread.sleep(5000);<br /> cf.complete("Test");<br /> }</code></pre><br />
As shown in the above snippet we create a CompletableFuture and invoke the <b>complete</b> method to set the value for this future object. </p>
<p>The above samples showed how JDK 8 standardizes in the platform and augments to some of the functionality with Guava library aimed to provide with JDK7. JDK 8 has been a great leap in terms of the newer capabilities it provided. Guava will definitely provide additional improvements using the standardized API. </p>
<p><a href="https://twitter.com/bhakti_mehta" class="twitter-follow-button" data-show-count="false">Follow @bhakti_mehta</a></p>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>http://www.java.net/blog/bhaktimehta/archive/2014/07/14/how-jdk-8-standardizes-and-augments-guava-library-functionalities#commentsBlogsJ2SEJava DesktopJava PatternsJava ToolsOpen JDKMon, 14 Jul 2014 11:11:11 +0000bhaktimehta902229 at http://www.java.netBook review: Mining the Social Web by Mathew A. Russellhttp://www.java.net/blog/bhaktimehta/archive/2014/02/16/book-review-mining-social-web-mathew-russell
<div class="field field-type-filefield field-field-thumb-100x70">
<div class="field-items">
<div class="field-item odd">
<img class="imagefield imagefield-field_thumb_100x70" width="180" height="236" alt="" src="http://www.java.net/sites/default/files/bhaktimehta/cat.gif?1391495234" /> </div>
</div>
</div>
<p>There is so much potential in extracting, processing and synthesizing the the multi faceted, realtime data that can be mined from social sites.<br />
<a href="http://shop.oreilly.com/product/0636920030195.do">Mining the Social Web</a> by Mathew A. Rusell covers these topics scrupulously. Here is my detailed review of the book<br><br />
<a href="http://shop.oreilly.com/product/0636920030195.do"><img src="https://www.java.net/sites/default/files/cat_0.gif"></a></p>
<h2>Chapter 1: Mining Twitter, Exploring Trending topics, Discovering what users are talking about</h2>
<p>This is an informative chapter which covers from the basics of how to create applications with Twitter, authorizing an application to access Twitter data, looking for trends, searching for tweets and how to extract the text, screen names and hashtags from the tweets. It also covers how to compute the lexical diversity of the tweets and<br />
visualizing the data with histograms. It covers <a href="http://matplotlib.org/">matplotlib</a>, <a href="https://pypi.python.org/pypi/PrettyTable">prettytable</a> and other Python packages. I have used Twitter APIs extensively and found this chapter very useful and well written.</p>
<h2>Chapter 2 : Mining Facebook: Analyzing Fan Pages, Examining Friendships, and More</h2>
<p>This chapter covers the developer tools for Facebook, <a href="https://developers.facebook.com/tools/explorer">Graph API explorer</a>, using the API over HTTP, <a href="http://ogp.me/">Open Graph Protocol</a>, examining friendships and analyzing social graph connections. It demonstrates how to use facebook-sdk package to make FQL queries. Other examples include computing overlapping likes in social network, analyzing mutual friendships and visualizing with <a href="http://d3js.org/">D3.js</a>.<br />
This chapter makes it apparent that there are many exciting possibilities for what can be done with social data, and that there’s enormous value tucked away on Facebook which can be extracted and studied.</p>
<h2>Chapter 3 : Mining LinkedIn: Faceting Job Titles, Clustering Colleagues, and More</h2>
<p>This chapter covers how to use the <a href="https://www.link<br />
edin.com/secure/developer">LinkedIn developer API</a>, retrieving LinkedIn connections. It also covers data normalization and similarity computation techniques, visualizing locations with cartograms, clustering algorithms. I think this was one of the most detailed and informative chapters of the book and I thoroughly enjoyed reading it.</p>
<h2>Chapter 4 : Mining Google+: Computing Document Similarity, Extracting Collocations, and More</h2>
<p>This chapter covers introduction to Google+ Developer API. It covers TF-IDF which stands for term frequency-inverse document frequency, it also covers algorithms to find similar documents, visualizing document similarities with martix diagrams,<br />
contingency tables and scoring functions. Most importantly this chapter covered so many techniques to extract information from unstructured text with Information retrieval techniques in meticulous detail.</p>
<h2>Chapter 5 : Mining Web Pages: Using Natural Language Processing to Understand Human Language, Summarize Blog Posts, and More</h2>
<p>Chapter 5 discusses context driven techniques and goes in the semantics of human language data. It covers the <a href="http://code.google.com/p/boilerpipe/wiki/QuickStart">Boilerpipe library</a> to extract text from a web page, feedparser to extract from RSS feeds, web crawling techniques, EOS detection,Tokenization, Part-of-speech tagging and Chunking. It shows how to use Natural Language Toolkit (NLTK) to extract entities from unstructured text.</p>
<h2>Chapter 6 : Mining Mailboxes: Analyzing Who’s Talking to Whom About What, How Often, and More</h2>
<p>Chapter 6 covers basic semantics of mbox, mail headers, how to convert mbox to json and import to MongoDB, querying by date time, analyzing patterns in sending and receiving messages using Enron data. It also covers how to analyse your own mail data and access Gmail data with OAuth. This chapter is built on previous ones and covers a lot from basic mbox to mining mboxes to slicing and dicing the data.</p>
<h2>Chapter 7 : Mining GitHub: Inspecting Software<br />
Collaboration Habits, Building Interest Graphs, and More </h2>
<p>This chapter covers <a href="http://developer.github.com/v3/">GitHub’s developer platform</a> and how to make API requests. It covers an example with <a href="https://pypi.python.org/pypi/PyGithub">PyGithub</a> to access the query objects. Additionally it covers the concept of an interest graph and how to construct an interest graph from GitHub data and how to model property graphs with NetworkX. I found the section on getting the repositories from a graph, finding the programming languages for each user and the <a href="http://www.githubarchive.org/">GitHubArchive</a> very educative.</p>
<h2> Chapter 8 : Mining the Semantically Marked-Up Web:<br />
Extracting Microformats, Inferencing over RDF, and More</h2>
<p>This chapter talks about microformats an examples covered using <a href="http://www.google.com/webmasters/tools/richsnippets">Google's Data testing tool</a> to access semantic markup from web pages for eg. LinkedIn's profiles, <a href="https://www.wikipedia.org/">Wikipedia</a>, <a href="http://www.about.com/">About.com</a>, based on microformats, Additionally there is an interlude to the semantic web and the evolution of web with the various manifestations and characteristcis which was very interesting.</p>
<h2>Part 2 Twitter Cookbook</h2>
<p>This is a whole section dedicated to recipes for mining Twitter's accessible APIs due to the openness and emerging popularity. I have done a few sentiment analysis related projects with Twitter API and found this really helpful for people who want to dig deeper in the API. This covers different recipes in form of problems, solutions and discussions from topics ranging from OAuth, finding the populatr trends, searching tweets. I particularly liked the recipes for using the Twitter Streaming API to sample data from the Twitter firehose, saving and access Twitter feeds with MongoDB.</p>
<h2> Additional Observations</h2>
<ul>
<li>I like the author's use of additional online resources for further reference as well as the recommended exercises section at the end of each chapter.</li>
<li>I enjoyed the author's style of introducing the social website, the API to fetch the data, the techniques and complexities and every chapter had some handy tips and tools which could be learnt about. Additionally every chapter was built upon a lot of ideas and discussions covered in the previous ones which tied the concepts neatly.</li>
<li>I think the code samples based on Python and the myriad of packages introduced in the various chapters help make data access, manipulation and visualization easy to follow.
</ul>
<h2>Conclusion</h2>
<p>I thoroughly enjoyed reading and reviewing <a href="http://shop.oreilly.com/product/0636920030195.do">"Mining the Social Web"</a> .<br />
This is a great book to explore the rich data that can be extracted from Twitter, Facebook, Linkedin, Google+, GitHub. It has detailed information for everyone from an Information Retrieval(IR) enthusiast, a data scientist, an analyst or just a curious reader looking to learn the different API available out there to extract, mine, visualize and interpret the data and explore the infinite possiblities by using the diverse building blocks together. </p>
http://www.java.net/blog/bhaktimehta/archive/2014/02/16/book-review-mining-social-web-mathew-russell#commentsBlogsGlobal Education and LearningMon, 17 Feb 2014 07:34:40 +0000bhaktimehta901037 at http://www.java.netJAX-RS and Bean Validationhttp://www.java.net/blog/bhaktimehta/archive/2013/10/30/jax-rs-and-bean-validation
<!-- | 0 --><p>One of the newer features introduced in <b>JAX-RS 2.0</b> is the support for validating resource classes with <b>Bean Validation</b><br />
Bean Validation support comes in Jersey 2.x by adding jersey-bean-validation module to the class-path. </p>
<p>The following sample shows how to use Bean Validation with JAX-RS 2.0. I show how to define a custom constraint which will validate any Enum class.<br />
Additionally I will show code on how to use bean validation with Jersey 1.x which is a reference implementation for JAX-RS 1.0</p>
<p> I demonstrate a sample of a Coffee shop which can take orders for coffee and get details of a particular order. The following code shows a basic CoffeesResource. Consider placing an order for coffee and the choices to be made. In post cases these choices can be validated by using java.lang.Enum. So in this sample I have a simple Enum Validator which can validate all such constraints. Here are some of the choices for a coffee order<br />
<pre class="prettyprint"><code>Type:Expresso,Blended,Chocolate,Brewed</td><br />Size: Small, Medium, Large, X Large<br />Preference: Regular, Non Fat, Soy Milk, Whipped Cream</code></pre><br />
The following code shows how the Coffee resource looks<br />
<pre class="prettyprint"><code>/**<br /> *<br /> * A simple JAX-RS resource which demonstrates Bean Validation<br /> * @author Bhakti Mehta<br /> *<br /> */<br />@Path("v1/coffees")<br />public class CoffeesResource {<br /> @Context<br /> javax.ws.rs.core.UriInfo uriInfo;<br /><br /> @GET<br /> @Path("{order}")<br /> @Produces(MediaType.APPLICATION_XML)<br /> @NotNull(message="Coffee does not exist for the order id requested")<br /> public Coffee getCoffee( @PathParam("order") int order) {<br /> return CoffeeService.getCoffee(order);<br /><br /> }<br /><br /> @POST<br /> @Consumes(MediaType.APPLICATION_XML)<br /> @Produces(MediaType.APPLICATION_XML)<br /> @ValidateOnExecution<br /> public Response addCoffee(@Valid Coffee coffee) {<br /> int order = CoffeeService.addCoffee(coffee);<br /> return Response.created(uriInfo.getAbsolutePath())<br /> .entity("<order>" + order + "</order>").build();<br /> }<br />}</code></pre><br />
As you can see in the preceeding snippet there is a <b>GET</b> and <b>POST</b> method. The <b>@GET</b> annotated method <b>getCoffee()</b> checks if a coffee exists for the PathParam order and returns it else returns null. There is an <b>@NotNull</b> annotation for the method to provide a message incase there is no coffee by the order specified</p>
<p>The <b>@POST</b> annotated <b>addCoffee()</b> method adds a new order for the coffee. Notice the <b>@Valid</b> annotation for the request parameter coffee. It indicates to validate the object coffee<br />
The next snippet shows how the Coffee object looks like.<br />
<pre class="prettyprint"><code>@XmlRootElement<br />public class Coffee {<br /><br /> @VerifyValue(Type.class)<br /> private String type;<br /><br /> @VerifyValue(Size.class)<br /> private String size;<br /><br /> @NotNull<br /> private String name;<br /><br /> private double price;<br /><br /><br /> private int order;<br /><br /> ....///getters and setters<br />}</code></pre><br />
I have two Enum <b>Size</b> and <b>Type</b> associated with the Coffee. Each of the enums are annotated with <b>@VerifyEnum()</b> annotation.<br />
The <b>@VerifyValue</b> is a custom constraint I introduced to validate any Enum object.<br />
It will be covered below.<br />
The following snippet shows how the Size and Type enums.<br />
<pre class="prettyprint"><code>public enum Size {<br /> Small("S"), Medium("M"), Large("L"), ExtraLarge("XL");<br /> private String value;<br /><br /> private Size(String v) {<br /> this.value = v;<br /> }<br /> public String getValue() {<br /> return value;<br /> }<br /> <br /><br /><br />}</code></pre><br />
<pre class="prettyprint"><code>public enum Type {<br /> Expresso, Brewed, Blended, Chocolate ;<br /><br />}</code></pre><br />
The following code shows how I have a custom bean validation constraint called <b>VerifyValue</b> which verifies if the value for the Enum is valid<br />
<pre class="prettyprint"><code>@Retention(RUNTIME)<br />@Target({FIELD, METHOD})<br />@Documented<br />@Constraint(validatedBy = VerifyValueValidator.class)<br />public @interface VerifyValue {<br /><br /> String message() default "Value specified is not valid";<br /> Class<?>[] groups() default {};<br /> Class<? extends Payload>[] payload() default {};<br /> Class<? extends Enum<?>> value();<br /><br />}</code></pre><br />
Here is the implementation for the <b>VerifyValueValidator</b><br />
<pre class="prettyprint"><code>/**<br /> * Implementation for the user-defined constraint annotation @VerifyValue<br /> * This is a general purpose validator which verifies the value for any enum<br /> * If an Enum object has a getValue() method it will validate based on the value of the Enum<br /> * else will use the EnumConstant<br /> *<br /> * @author Bhakti Mehta<br /> */<br />public class VerifyValueValidator implements ConstraintValidator<VerifyValue, Object> {<br /><br /> Class<? extends Enum<?>> enumClass;<br /><br /> public void initialize(final VerifyValue enumObject) {<br /> enumClass = enumObject.value();<br /><br /> }<br /><br /> public boolean isValid(final Object myval,<br /> final ConstraintValidatorContext constraintValidatorContext) {<br /><br /><br /> if ((myval != null) && (enumClass != null)) {<br /> Enum[] enumValues = enumClass.getEnumConstants();<br /> Object enumValue = null;<br /><br /> for (Enum enumerable : enumValues) {<br /> if (myval.equals(enumerable.toString()) ) return true;<br /> enumValue = getEnumValue(enumerable);<br /> if ((enumValue != null)<br /> && (myval.toString().equals(enumValue.toString()))) {<br /> return true;<br /> }<br /> }<br /> }<br /> return false;<br /> }<br /><br /> /**<br /> * Invokes the getValue() method for enum if present<br /> * @param enumerable The Enum object<br /> * @return returns the value of enum from getValue() or<br /> * enum constant<br /> */<br /> private Object getEnumValue(Enum<?> enumerable) {<br /> try {<br /> for (Method method: enumerable.getClass().getDeclaredMethods()) {<br /> if (method.getName().equals("getValue")) {<br /> return method.invoke(enumerable);<br /> }<br /> }<br /> } catch (IllegalAccessException e) {<br /> e.printStackTrace();<br /> } catch (InvocationTargetException e) {<br /> e.printStackTrace();<br /> }<br /> return null;<br /> }</code></pre><br />
The <b>isValid()</b> method looks for all the Enum objects if its value matches that specified in the request and returns true else returns false. There is no straightforward method to get an enum from a value specified so I have implemented the <b>getEnumValue()</b> method. The <b>EnumSet</b> will return the EnumConstants but not an Enum based on its value.The <b>getEnumValue()</b> method uses reflection to invoke the <b>getValue()</b> method for the Enum. There can be further optimization to cache the enum based on the value in a HashMap so future references can be looked up from the map first.</p>
<p>Here is the Application class which has the following properties set<br />
<pre class="prettyprint"><code>public Map<String,Object> getProperties() {<br /> Map<String,Object> properties = new HashMap<String,Object>() ;<br /> properties.put(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);<br /> <br /> return properties;<br /> }</code></pre><br />
The <b>ServerProperties.BV_SEND_ERROR_IN_RESPONSE</b> is a Bean Validation (JSR-349) support customization property that will allow the validation errors to be sent back in the response<br />
Complete sample can be downloaded from <a href="https://github.com/bhakti-mehta/samples/tree/master/jax-rs-bean-validation">https://github.com/bhakti-mehta/samples/tree/master/jax-rs-bean-validation</a></p>
<h3>Running and testing the sample</h3>
<p>Install GlassfFish 4.0<br />
Build the sample using mvn install<br />
Deploy the war to GlassFish<br />
<pre class="prettyprint"><code>Using curl to the URL <a href="http://localhost:8080/jax-rs-bean-validation/v1/coffees<br />curl" title="http://localhost:8080/jax-rs-bean-validation/v1/coffees<br />curl">http://localhost:8080/jax-rs-bean-validation/v1/coffees<br />curl</a> -X POST -d @test.xml <a href="http://localhost:8080/jax-rs-bean-validation/v1/coffees" title="http://localhost:8080/jax-rs-bean-validation/v1/coffees">http://localhost:8080/jax-rs-bean-validation/v1/coffees</a> <br />--header "Content-Type:application/xml"</code></pre><br />
This will give you an order id for the coffee created.<br />
Here is the sample input for the POST request in the test.xml file<br />
<pre class="prettyprint"><code>&lt;coffee&gt;<br /> &lt;type>Expresso&lt;/type&gt;<br /> &lt;size>XL&lt;/size&gt; <br /> &lt;name>Cafe Latte&lt;/name&gt;<br /> &lt;price>6.50&lt;/price&gt;<br />&lt;/coffee&gt;</code></pre>
<pre class="prettyprint"><code>Send a GET request to <a href="http://localhost:8080/jax-rs-bean-validation/v1/coffees/<order>" title="http://localhost:8080/jax-rs-bean-validation/v1/coffees/<order>">http://localhost:8080/jax-rs-bean-validation/v1/coffees/<order></a> <br />You will get a validation error incase there is no coffee with the order specified</code></pre><br />
You can send some invalid values in the Type or the Size and see the validation errors.</p>
<h2> Jersey 1.1.x and Bean Validation</h2>
<p>In <b>Jersey 1.x (RI for JAX-RS 1.1)</b> <b>Bean Validation</b> is not supported by default.</p>
<p>With Jersey 1.x I have enabled bean validation for resource parameters by using <b>Aspect oriented Programming</b> by implementing a <a href="http://aopalliance.sourceforge.net/doc/org/aopalliance/intercept/MethodInterceptor.html"> MethodInterceptor</a><br />
This feature enables us to write code that is executed each time a matching method is invoked.</p>
<pre class="prettyprint"><code>/**<br /> * Intercepts resource methods before they are invoked to check for <br /> * parameters annotated with @Valid annotation<br /> * and validates the method arguments<br /> * <br /> * Incase the argument is not valid an appropriate exception with the error<br /> * message underlying the cause of constraint violation errors is thrown <br /> * @author Bhakti Mehta<br /> *<br /> */<br />public class ValidationInterceptor implements MethodInterceptor {<br /> private final Validator validator <br /> <br /> public static IsValidable isValidable() {<br /> return new IsValidable();<br /> }<br /><br /> public ValidationInterceptor() {<br /> validator = Validation.buildDefaultValidatorFactory().getValidator();<br /> }<br /> <br /><br /> @Override<br /> public Object invoke(MethodInvocation invocation) throws Throwable {<br /> Method method = invocation.getMethod();<br /> Object argument = null;<br /> Annotation[][] parameterAnnotations = method.getParameterAnnotations(); <br /> if (parameterAnnotations != null) {<br /> for (int i = 0; i < parameterAnnotations.length; i++) {<br /> Annotation[] annotationsArray = parameterAnnotations[i];<br /> for(Annotation annotation : annotationsArray){<br /> if (annotation instanceof Valid) {<br /> argument = invocation.getArguments()[i];<br /> }<br /> }<br /> }<br /> }<br /> <br /> <br /> StringBuilder stringBuilder = new StringBuilder();<br /> stringBuilder.append("\n");<br /> if (argument != null ) {<br /> Set<ConstraintViolation<Object>> violations = validator.validate(argument);<br /> if (!violations.isEmpty()) {<br /> for(ConstraintViolation<?> violation : violations) {<br /> stringBuilder.append(violation.getMessage()).append("\n");<br /> }<br /> throw new ConstraintViolationException(<br /> String.format("Error when validating method %s due to %s", method.getName(),<br /> stringBuilder.toString())<br /> ,violations);<br /> <br /> }<br /> }<br /> return invocation.proceed();<br /><br /> }<br />}<br />class IsValidable extends AbstractMatcher<Method> {<br /> @Override<br /> public boolean matches(Method method) {<br /> Class<?>[] interfaces = method.getDeclaringClass().getInterfaces();<br /><br /> if (interfaces.length > 0) {<br /> Class<?> resource = interfaces[0];<br /><br /> try {<br /> Method resourceMethod = resource.getMethod(method.getName(),<br /> method.getParameterTypes());<br /> <br /> return Modifier.isPublic(resourceMethod.getModifiers());<br /> <br /> } catch (NoSuchMethodException nsme) {<br /> return false;<br /> }<br /> } else {<br /> return false;<br /> }<br /> }<br />}</code></pre>
<p>The above snippet shows the implementation of a <a href="http://aopalliance.sourceforge.net/doc/org/aopalliance/intercept/MethodInterceptor.html"> MethodInterceptor</a></p>
<p>On the <b>invoke()</b> method we get an instance of the <b>MethodInvocation</b> object. As you can see in the above snippet<br />
we get the <b>Method</b> from the <b>invocation.getMethod()</b> call and iterate through the parameter annotations for the method and check if there is an <b>@Valid</b> annotation<br />
If a param has an annotation with <b>@Valid</b> we get the argument from the methodInvocation using <b>invocation.getArguments()[i]</b></p>
<p>Incase the argument is not Null we call the <b>validator.validate(argument)</b><br />
For all the <b>ConstraintViolations</b> we throw a ConstraintViolationException with the list of violations<br />
Finally we call through the underlying method by calling <b>invocation.proceed()</b></p>
<p>The following code shows how to inject the ValidationInterceptor so it works with Jersey 1.1.x<br />
<pre class="prettyprint"><code>public class MyConfigurator extends JerseyServletModule {<br />@Override<br /> protected void configureServlets() {<br /> MethodInterceptor validationInterceptor = new ValidationInterceptor();<br /> requestInjection(validationInterceptor);<br /> bindInterceptor(Matchers.any(),<br /> ValidationInterceptor.isValidable(), validationInterceptor);</code></pre><br />
The above code shows how we inject interceptors. </p>
<p>Another solution provided which can be useful is using <b>ResourceFilterFactory</b> as mentioned <a href="http://stackoverflow.com/questions/16303694/how-to-get-resource-method-matched-to-uri-before-jersey-invokes-it/16446746#16446746">here</a><br />
However in my case I needed to know the arguments of the method and validate them and I found the <b>AOP method interceptor</b> worked well.</p>
<h3>Summary</h3>
<p>This blog showed how to use Bean Validation with JAX-RS 2.0. A complete sample is available for download from <a href="https://github.com/bhakti-mehta/samples/tree/master/jax-rs-bean-validation">https://github.com/bhakti-mehta/samples/tree/master/jax-rs-bean-validation</a><br />
Additionally for people who cannot upgrade to JAX-RS 2.0 we covered how to support Bean Validation using two approaches<br />
1. AOP with method interceptors<br />
2. Using RequestFilterFactory and RequestFilters<br />
Hope this was helpful. </p>
http://www.java.net/blog/bhaktimehta/archive/2013/10/30/jax-rs-and-bean-validation#commentsBlogsGlassFishGlassFishJava EnterpriseThu, 31 Oct 2013 05:39:10 +0000bhaktimehta899774 at http://www.java.netMy new Book "Developing RESTful Services with JAX-RS 2.0, WebSockets and JSON"http://www.java.net/blog/bhaktimehta/archive/2013/10/18/my-new-book-developing-restful-services-jax-rs-20-websockets-and-json
<!-- 292 | 0 --><img src="/images/people/bhakti_mehta.jpg" border="0", align="left" /><p><b>Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON</b> is the new book which <a href="http://kalali.me/">Masoud Kalali</a> and I have worked on and recently published.</p>
<p><a href="http://www.packtpub.com/developing-restful-services-with-jax-rs2-json-websockets/book"><img src="https://www.java.net//sites/default/files/book-image.JPG"></a><br />
As the technology landscape moves focus towards smaller devices, the need for building scalable, flexible, lightweight, and real-time communications-based applications grows.<br />
HTML 5 and Java EE 7 provide a new synthesis of technologies that demonstrate tremendous scope and potential in areas of device independence,<br />
asynchronous communication, interoperability, and portability. Newer technologies in JavaEE 7 like WebSockets, JSON , asynchronous invocation capable components keep the platform innovative and improve developer productivity.<br />
Developing RESTful Services with JAX-RS 2.0, WebSockets, and JSON is a practical, hands-on guide that provides you with clear and pragmatic<br />
information to take advantage of the real power behind HTML5 and Java EE technologies.<br />
This book covers</p>
<ul>
<li>Developing RESTful Web Services using the JAX-RS 2.0 API</li>
<li>Building applications with the JavaScript and Java Client API for WebSockets and Server-Sent Events</li>
<li>Understanding security, fault tolerance with WebSockets and Server-Sent Events</li>
<li>Producing, parsing, and manipulating JSON data with the help of standard JSON API</li>
<li>Best practices in building applications with WebSockets, Server-Sent Events, and JAX-RS 2.0</li>
<li>Using the aspects of asynchronous programming to improve scalability</li>
</ul>
<p>The last chapter of the book includes design and development of two complete applications: one event based application based on Twitter API<br />
and other library based application which will integrate the different JavaEE 7 technologies together.<br />
For more information you can check <a href="http://www.packtpub.com/developing-restful-services-with-jax-rs2-json-websockets/book">here</a>.</p>
http://www.java.net/blog/bhaktimehta/archive/2013/10/18/my-new-book-developing-restful-services-jax-rs-20-websockets-and-json#commentsBlogsGlassFishJava EnterpriseFri, 18 Oct 2013 20:10:19 +0000bhaktimehta899460 at http://www.java.netSilicon Valley Code Camp 2013 Reporthttp://www.java.net/blog/bhaktimehta/archive/2013/10/06/silicon-valley-code-camp-2013-report
<!-- 956 | 0 --><img src="/images/people/bhakti_mehta.jpg" border="0", align="left" /><p><a href="http://www.siliconvalley-codecamp.com">Silicon Valley Code Camp</a> is one of the best known secrets and one of the best organized conferences in the Bay Area.<br />
I have the pleasure to speak at this conference for the past two years and am amazed at its growing popularity.<br />
Here are some statistics for this year</p>
<p><b>4500 registrations and registration was closed</b><br />
<b>230 sessions</b></p>
<p>The Code Camp consists of these points:</p>
<li>By and for the developer community</li>
<li>No Charge To Attendees</li>
<li>Never occurs during working hours</li>
<p>Sessions range from informal chalk talks to presentations. There was an awesome kids track with young speakers like Shadaj Laddad on Scala,<br />
talks like Python programming for kids to Pacman in 50 minutes. My good friend Arun Gupta led a track on Minecraft modding which was a huge success. </p>
<p>Here are some images from the conference this year.<br />
<img src="https://www.java.net//sites/default/files/photo_1.JPG"></img><br />
<img src="https://www.java.net//sites/default/files/photo-38.JPG"></img></p>
<p>What does it take to fuel 4500 attendees? 400 pizzas and 1000 subs<br />
<img src="https://www.java.net//sites/default/files/photo_4.JPG"> </img><br />
<img src="https://www.java.net//sites/default/files/photo_3.JPG"</img></p>
<p>6 dedicated parking lots and yet overflowing<br />
<img src="https://www.java.net//sites/default/files/photo_2.JPG"</img></p>
<p>These are the slides for my sessions this year </p>
<li><a href="http://www.slideshare.net/mobile/bhaktiks/fight-empirehtml5">Fight the empire lightweightly with HTML5, WebSockets, Server-Sent Events and others </a> </li>
<li><a href="http://www.slideshare.net/bhaktiks/think-async-26916964"> Think Async</a></li>
<p>I would like to thank Peter Kellner and his team for putting together such a wonderful show.<br />
Also thanks to the sponsors as well as Foothill College for supporting this effort.<br />
Till next year ...</p>
<table id="attachments" class="sticky-enabled">
<thead><tr><th>Attachment</th><th>Size</th> </tr></thead>
<tbody>
<tr class="odd"><td><a href="http://www.java.net/sites/default/files/photo_1.JPG">photo_1.JPG</a></td><td>171.24 KB</td> </tr>
<tr class="even"><td><a href="http://www.java.net/sites/default/files/photo_2.JPG">photo_2.JPG</a></td><td>138.51 KB</td> </tr>
<tr class="odd"><td><a href="http://www.java.net/sites/default/files/photo_3.JPG">photo_3.JPG</a></td><td>202.16 KB</td> </tr>
<tr class="even"><td><a href="http://www.java.net/sites/default/files/photo_4.JPG">photo_4.JPG</a></td><td>135.13 KB</td> </tr>
<tr class="odd"><td><a href="http://www.java.net/sites/default/files/photo-38.JPG">photo-38.JPG</a></td><td>128.61 KB</td> </tr>
</tbody>
</table>
http://www.java.net/blog/bhaktimehta/archive/2013/10/06/silicon-valley-code-camp-2013-report#commentsJ2SEJava EnterpriseJava User GroupsJava Web Services and XMLMon, 07 Oct 2013 04:02:05 +0000bhaktimehta899157 at http://www.java.netMy sessions at Silicon Valley Code Camp 2013http://www.java.net/blog/bhaktimehta/archive/2013/10/02/my-sessions-silicon-valley-code-camp-2013
<!-- | 0 --><p>I will be presenting the following sessions at <b><a href="http://www.siliconvalley-codecamp.com/">Silicon Valley Code Camp 2013</a></b>. For those in the Bay Area, Silicon Valley Code Camp is on Oct 5,6 2013 in Foothill College, Los Altos. It is a very well organized conference by the developers for the developers. This year has 232 sessions and 4500 registrations and am always amazed at the way Peter Kellner and his team pull this off!</p>
<p>These are my talks which I am looking forward to present.</p>
<h2> <a href="http://www.siliconvalley-codecamp.com/Session/2013/fight-the-empire-lightweightly-with-html5-websockets-serversentevents-o">Fight the empire lightweightly with HTML5, WebSockets, ServerSentEvents &amp; others</a> </h2>
<p>Sat Oct 5 at 5pm<br />
Based on the <b>Star Wars theme</b>, this session focuses on how Java EE 7 provides an extensive set of new and enhanced features to support standards such as HTML5, WebSocket, and Server-sent events, among others. The session shows how these new features are designed and matched to work together for developing lightweight solutions matching end users’ high expectations for Web application responsiveness. It covers best practices and design patterns associating the technologies with analogies from Star Wars. So join me in this fun filled talk where technology meets science and innovation..<br />
<i><b>May the force be with you!</b></i></p>
<h2> <a href="http://www.siliconvalley-codecamp.com/Session/2013/think-async">Think Async</a> </h2>
<p>Sun Oct 6 at 2:45 pm<br />
With the growing challenges we face with shortage of resources there is a constant need to improve scalability and performance. Fortunately Java EE 7 and Java SE 7 has provided a rich set of APIs which can be used to avoid the conventional request-response paradigm. The session will span across JSRs cover how JAX-RS, Servlets, WebSockets, EJB provide support to submit asynchronous requests and cover topics like callbacks, timeouts, client side asynchrony, API like non blocking IO and lots of good stuff from Java EE 7 and Java SE 7 . Prerequisite: An open mind and be ready to “Think async”</p>
<p>For more details on presenters check <a href="http://www.siliconvalley-codecamp.com/Presenter/2013">here</a>. Looking forward to a fun filled weekend at Silcon Valley Code Camp!</p>
http://www.java.net/blog/bhaktimehta/archive/2013/10/02/my-sessions-silicon-valley-code-camp-2013#commentsBlogsJ2EEJ2MEJ2SEJava EnterpriseJava Web Services and XMLWed, 02 Oct 2013 15:56:28 +0000bhaktimehta899092 at http://www.java.netNew enhancements to Admin Command framework in Glassfish 4.0http://www.java.net/blog/bhaktimehta/archive/2013/06/13/new-enhancements-admin-command-framework-glassfish-40
<!-- 5410 | 0 --><img src="/images/people/bhakti_mehta.jpg" border="0", align="left" /><p></p><p>Glassfish 4.0 is released. This is the reference implementation for Java EE 7 and focusses on HTML 5 and improving developer productivity. You can download the bits from here <a href="https://glassfish.java.net/download.html" title="https://glassfish.java.net/download.html">https://glassfish.java.net/download.html</a></p>
<p>Apart from the Java EE 7 support in GlassFish 4.0 there have been numerous other areas where Glassfish 4 has provided lots of improvements and innovation<br />
<a href="https://twitter.com/MartinJMares/" class="bb-url">Martin Mares</a> ,<a href="https://blogs.oracle.com/kasso/" class="bb-url"> Chris Kasso</a> and I have been working on the Admin Command Framework.<br />
These are some new enhancements that were added to Glassfish 4.0.</p>
<p><span style="font-weight:bold">o Support for Progress status using Server Sent Events</span><br />
<span style="font-weight:bold">o Job Management support</span></p>
<p><h2><a name="Support_for_Progress_status_in_commands_using_Server_Sent_Events">Support for Progress status in commands using Server Sent Events.</a></h2><br />
This section will cover the newly introduced <span style="font-weight:bold">@Progress</span> annotation. We will walk through the basic usages of Progress API.<br />
Next we will see how ServerSentEvents fits in with the Progress API.</p>
<p><h3><a name="_Progress_API_in_Glassfish_40"> Progress API in Glassfish 4.0</a></h3><br />
Consider some long running commands say start-cluster. It would be useful to be notified about the progress of the command as it is executing.<br />
To facilitate support for Progress status in AdminCommands a new annotation <span style="font-weight:bold">@Progress</span> is added.</p>
<p>Any command which wants to use the Progress status API can be annotated with <span style="font-weight:bold">@Progress</span><br />
The ProgressStatus object can be obtained from the <span style="font-weight:bold">AdminCommandContext</span>.<br />
The Progress API can be used to specify the total steps for execution. Once the total steps are known the percentage can be computed.<br />
Additionally the ProgressStatus API takes a message that can be added as the command progresses like Installing, Parsing... etc.<br />
As the command is executing, the progress can be updated by specifying the steps and the message to be sent to the client.<br />
<pre class="prettyprint"><code>@Progress<br />public class SomeCommand implements AdminCommand {<br /> <br /> public void execute(AdminCommandContext context) {<br /><br /> ProgressStatus ps = context.getProgressStatus();<br /> ps.setTotalStepCount(3);<br /> ...<br /> ..<br /> ps.progress(1, "Parsing files..");</code></pre>
<p>The above snippet shows the <span style="font-weight:bold">@Progress</span> annotation on the command. It also demonstrates how to get the <span style="font-weight:bold">ProgressStatus</span> object from the <span style="font-weight:bold">AdminCommandContext</span>.<br />
It shows how to use the<span style="font-weight:bold"> ProgressStatus.progress()</span> method to specify the number of steps taken and a message to be emitted.<br />
Here is the Progress Status API which command developers can read for detailed information. <a href="http://grepcode.com/file/maven.java.net/content/groups/promoted/org.glassfish.main.common/glassfish-api/4.0-b78/org/glassfish/api/admin/ProgressStatus.java" title="http://grepcode.com/file/maven.java.net/content/groups/promoted/org.glassfish.main.common/glassfish-api/4.0-b78/org/glassfish/api/admin/ProgressStatus.java">http://grepcode.com/file/maven.java.net/content/groups/promoted/org.glas...</a></p>
<p><h3><a name="_Using_ServerSentEvents_to_emit_progress"> Using ServerSentEvents to emit progress</a></h3><br />
Server-Sent Events (SSE) is a technology for providing push notifications from servers to clients once an initial client connection has been established.<br />
For our case of long running commands which emits progress as it executes, the server can continuously sending the progress using Server Sent Events API.</p>
<p><h3><a name="Definition_of_a_ManagedJob">Definition of a ManagedJob</a></h3><br />
Any command which has progress information in it ie annotated with <span style="font-weight:bold">@Progress</span> or which is run with <span style="font-weight:bold">--detach</span> (See section below) option is known as a <span style="font-weight:bold">ManagedJob</span>. Each job has a job id associated with it.<br />
You can query the status of a <span style="font-weight:bold">ManagedJob</span> using <span style="font-weight:bold">list-jobs</span> command.</p>
<p><h2><a name="How_it_fits_together_">How it fits together </a></h2><br />
1. When a managed job is executed in GlassFish the REST client will open an SSE connection with header Accept: text/event-stream.<br />
2. The command gets executed on a dedicated thread pool which is provided by the JobManager.<br />
3. Once the channel of communication is established all the progress feedback is sent as Server Sent Events and the channel is kept open to keep sending progress as it occurs.<br />
4. The Response is closed when the command finishes execution. </p>
<p><img width="600" height="400" alt="" src="http://weblogs.java.net/sites/default/files/sse.png" class="bb-image" /><br />
The above figure shows the interaction between the Server and the command which is annotated with @Progress executed by the client.<br />
The progress is sent via SSE and finally the ActionReport is sent once the command finishes execution.</p>
<p><h2><a name="Job_Management_commands">Job Management commands</a></h2><br />
These are newer commands which are introduced<br />
<ul class="bb-list" style="list-style-type:circle;">
<li>detach option to commands</li>
<li>attach command</li>
<li>list-jobs command</li>
<li> configure-managed-jobs</li></ul></p>
<p> </p>
<p><h3><a name="detach_option_to_commands_">detach option to commands </a></h3><br />
Any command can be run with <span style="font-weight:bold">--detach</span> option. This will give a job id associated with the command and the job is run in the background.<br />
You can then lookup the job using the <span style="font-weight:bold">list-jobs</span> command. (Similar to the jobs command in Unix)<br />
You can later attach to the job using the <span style="font-weight:bold">attach</span> command with the job id too and see the progress.</p>
<p><h3><a name="attach_command_">attach command </a></h3><br />
The following image shows a sample command started by the client which emits progress status information.<br />
1. Client 1 starts the sample command which has some progress information<br />
2. The server executes the command and sends the progress to the client using ServerSentEvents.</p>
<p>You can open another terminal for Client 2 and<br />
attach to the same job and see the same progress updates on both the clients.</p>
<p><img width="500" height="300" alt="" src="http://weblogs.java.net/sites/default/files/image.png" class="bb-image" /><br />
Fig 1. Multiple clients attaching to get progress via Server Sent Events.</p>
<p>Bboth the terminals Client1 and Client2 are both getting the same set of progress related Server Sent Events at the same time. Even if one client kills using Ctrl C the other will still see the updates.</p>
<p><h3><a name="listjobs">list-jobs</a></h3><br />
The <span style="font-weight:bold">list-jobs</span> command can provide information regarding the jobs.<br />
It lists the job id, the name, the time the job was started, the state and the Exitcode.<br />
Here is a sample output of list-jobs command<br />
<pre class="prettyprint"><code>asadmin list-jobs<br />NAME JOB ID TIME STATE EXIT CODE USER <br />sample-command1 1 2013-02-05 14:11:24 COMPLETED SUCCESS admin </code></pre>
<p>You can even run list-jobs with a single job id<br />
<pre class="prettyprint"><code>asadmin list-jobs 1<br />NAME JOB ID TIME STATE EXIT CODE USER <br />sample-command1 1 2013-02-05 14:11:24 COMPLETED SUCCESS admin </code></pre><br />
Using curl to get the data of the list-jobs<br />
<pre class="prettyprint"><code>This will get the information of all jobs <br />curl -vSs -H 'X-Requested-By foo' -X GET http://localhost:4848/management/jobs</code></pre><br />
<pre class="prettyprint"><code>This will get the information of job whose id is 1<br />curl -vSs -H 'X-Requested-By foo' -X GET <a href="http://localhost:4848/management/jobs/id/1" title="http://localhost:4848/management/jobs/id/1">http://localhost:4848/management/jobs/id/1</a> </code></pre>
<p><h3><a name="configuremanagejobs_command">configure-manage-jobs command</a></h3><br />
The <span style="font-weight:bold">configure-managed-jobs</span> command is used to clean up these <span style="font-weight:bold">ManagedJobs</span>. By default the job retention period is 24 hours. But using this command you can specify how long you want to keep the jobs.</p>
<p><h3><a name="How_you_can_contribute">How you can contribute</a></h3></p>
<p>Download GlassFish 4.0 from <a href="https://glassfish.java.net/download.html" title="https://glassfish.java.net/download.html">https://glassfish.java.net/download.html</a> and try the newer features.<br />
Java EE 7 tutorial is here <a href="http://docs.oracle.com/javaee/7/tutorial/doc/home.htm" title="http://docs.oracle.com/javaee/7/tutorial/doc/home.htm">http://docs.oracle.com/javaee/7/tutorial/doc/home.htm</a><br />
You can file bugs using this link <a href="https://java.net/jira/browse/GLASSFISH" title="https://java.net/jira/browse/GLASSFISH">https://java.net/jira/browse/GLASSFISH</a><br />
Provide feedback at <a href="mailto:users@glassfish.dev.java.net">users@glassfish.dev.java.net</a>.</p>
<table id="attachments" class="sticky-enabled">
<thead><tr><th>Attachment</th><th>Size</th> </tr></thead>
<tbody>
<tr class="odd"><td><a href="http://www.java.net/sites/default/files/image.png">image.png</a></td><td>83.96 KB</td> </tr>
<tr class="even"><td><a href="http://www.java.net/sites/default/files/sse.png">sse.png</a></td><td>31.8 KB</td> </tr>
</tbody>
</table>
http://www.java.net/blog/bhaktimehta/archive/2013/06/13/new-enhancements-admin-command-framework-glassfish-40#commentsThu, 13 Jun 2013 16:26:08 +0000bhaktimehta894448 at http://www.java.netRunning osgi shell commands with asadmin in Glassfishhttp://www.java.net/blog/bhaktimehta/archive/2012/11/20/running-osgi-shell-commands-asadmin-glassfish-0
<!-- | 0 --><p>GlassFish comes preconfigured with Apache Felix Gogo, which is an implementation of OSGi RFC 147, and is a proposed standard shell for OSGi environments. </p>
<p>For Glassfish 4.0 there is no longer need to open a separate port to access the shell. The OSGi shell commands are integrated with asadmin, so you can now access the OSGi shell<br />
commands via asadmin tool.</p>
<p>There is a remote command called osgi which accepts subcommands which are fed to the OSGi shell and their result returned via asadmin. </p>
<p>This integration allows you to secure the OSGi commands using GlassFish admin credentials as well.<br />
If you have turned on “secure admin” feature in GlassFish, then you can even access the shell via asadmin osgi command from remote hosts. </p>
<p>To try this feature download the latest glassfish bits from <a href="http://dlc.sun.com.edgesuite.net/glassfish/4.0/">here</a><br />
<pre class="prettyprint"><code>asadmin osgi <em>subcommand</em><br />You can use the subcommand you would have used after telnetting to osgi shell here</code></pre><br />
e.g, <pre class="prettyprint"><code>%asadmin osgi lb -l <br />START LEVEL 2<br /> ID|State |Level|Name<br /> 0|Active | 0|System Bundle (4.0.2)<br /> 1|Active | 1|javax.annotation API v.1.1 (4.0.0.SNAPSHOT)<br /> 2|Active | 1|jaxb-api (2.2.7)<br /> 3|Active | 1|Metro Web Services API OSGi Bundle (2.3.0.b100)<br /> 4|Active | 1|OSGi resource locator bundle - used by various API providers that rely on META-INF/services mechanism to locate providers. (1.0.1)<br /> 5|Installed | 1|ACC Config Classes (JAXB) (4.0.0.SNAPSHOT)<br /> 6|Active | 1|admin-cli (4.0.0.SNAPSHOT)<br /> 7|Installed | 1|admin-core (4.0.0.SNAPSHOT)<br /> 8|Active | 1|admin-util (4.0.0.SNAPSHOT)<br /> 9|Installed | 1|AMX V3 Core (4.0.0.SNAPSHOT)<br /> 10|Installed | 1|AMX V3 Java EE Management (JSR 77) API and Implementation (4.0.0.SNAPSHOT)<br /> 11|Resolved | 1|GlassFish Java EE Annotation Framework (4.0.0.SNAPSHOT)<br /> 12|Resolved | 1|Ant repackaging (4.0.0.SNAPSHOT)</code></pre>
http://www.java.net/blog/bhaktimehta/archive/2012/11/20/running-osgi-shell-commands-asadmin-glassfish-0#commentsGlassFishTue, 20 Nov 2012 20:24:32 +0000bhaktimehta892563 at http://www.java.net