Featured FREE Whitepapers

What's New Here?


Getting started with Scala and Scalatra – Part II

In the previous part of the tutorial we created a simple application from scratch and setup Eclipse so we could edit the scala files for scalatra. In this second part of the tutorial you’ll learn how to do the following:How to start scalatra with embedded Jetty for easy testing and debugging Create a simple REST API that returns JSON data Test your service using specs2We will start by changing the way we start scalatra. Instead of running it using sbt like we did in the previous part, we’ll start scalatra directly from Eclipse. You can download the project for this tutorial from here. Remember to run the following from the project directory before importing in Eclipse. $ sbt > update > eclipse How to start scalatra with embedded Jetty for easy testing and debugging We’ve seen that you can start scalatra (and your service) directly using sbt. $ sbt > container:start > ~ ;copy-resources;aux-compile This will start a Jetty server and automatically copy over the resources and compile them. Even though this works fine you can sometimes run into memory problems where reloading stops, debugging is very hard to do and when an exception is thrown you can’t just click on the exception to jump to the relevant source code. This is something we can easily fix. Scalatra uses Jetty internally, and is itself nothing more than a servlet. So what we can do is just run an embedded Jetty instance that points to the servlet. For this we create the following scala object. package org.smartjava.scalatra.server; import org.eclipse.jetty.server.Server import org.eclipse.jetty.webapp.WebAppContext object JettyEmbedded { def main(args: Array[String]) { val server = new Server(9080) val context: WebAppContext = new WebAppContext(); context.setServer(server) context.setContextPath('/'); context.setWar('src/main/webapp') server.setHandler(context); try { server.start() server.join() } catch { case e: Exception => { e.printStackTrace() System.exit(1) } } } } Before you run this, also create a logback.xml file to control the logging. This is just a basic logging configuration that only logs the message at info level or greater. If you don’t have this, you’ll see a whole lot of Jetty log messages. For our own log messages we set the level to debug. <configuration> <appender name='STDOUT' class='ch.qos.logback.core.ConsoleAppender'> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <logger name='org.smartjava.scalatra' level='DEBUG'/> <root level='info'> <appender-ref ref='STDOUT' /> </root> </configuration> You can run this as an application directly from Eclipse: ‘Run->Run As->Scala Application’. The output you’ll see will be something like this: 21:37:33.421 [main] INFO org.eclipse.jetty.server.Server - jetty-8.1.5.v20120716 21:37:33.523 [main] INFO o.e.j.w.StandardDescriptorProcessor - NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet 21:37:33.589 [main] INFO o.e.j.server.handler.ContextHandler - started o.e.j.w.WebAppContext{/,file:/Users/jos/Dev/scalatra/firststeps/hello-scalatra/src/main/webapp/},src/main/webapp 21:37:33.590 [main] INFO o.e.j.server.handler.ContextHandler - started o.e.j.w.WebAppContext{/,file:/Users/jos/Dev/scalatra/firststeps/hello-scalatra/src/main/webapp/},src/main/webapp 21:37:33.631 [main] INFO o.scalatra.servlet.ScalatraListener - Initializing life cycle class: Scalatra 21:37:33.704 [main] INFO o.e.j.server.handler.ContextHandler - started o.e.j.w.WebAppContext{/,file:/Users/jos/Dev/scalatra/firststeps/hello-scalatra/src/main/webapp/},src/main/webapp 21:37:33.791 [main] INFO o.f.s.servlet.ServletTemplateEngine - Scalate template engine using working directory: /var/folders/mc/vvzshptn22lg5zpp7fdccdzr0000gn/T/scalate-6431313014401266228-workdir 21:37:33.812 [main] INFO o.e.jetty.server.AbstractConnector - Started SelectChannelConnector@ Now you can work with scalatra directly from Eclipse. Well that was easy. Next step, lets create a REST API. Before we do that though, if you work with Chrome, install ‘Dev HTTP Client‘. This is a great HTTP Client that works directly from Chrome. Very easy to use.Create a simple REST API that returns JSON data For this part of the tutorial we’ll start by creating a very simple REST API. We’ll create an API that allows us to bid on items. A sort of mini eBay. We won’t make it very large at the moment and only provide three operations:Get auction item based on id. Make a bid on a specific item. Get a bid a user has made.We won’t add persistency yet (that’s something for the next tutorial), we’ll only look at the API side of things. We’ll start with the first one.Get auction item based on id For this we want to be able to do the following: Request: GET /items/123 Response: 200 OK Content-Length: 434 Server: Jetty(8.1.5.v20120716) Content-Type: application/vnd.smartbid.item+json;charset=UTF-8 { 'name':'Monty Python and the search for the holy grail', 'id':123, 'startPrice':0.69, 'currency':'GBP', 'description':'Must have item', 'links':[ { 'linkType':'application/vnd.smartbid.item', 'rel':'Add item to watchlist', 'href':'/users/123/watchlist' }, { 'linkType':'application/vnd.smartbid.bid', 'rel':'Place bid on item', 'href':'/items/123/bid' }, { 'linkType':'application/vnd.smartbid.user', 'rel':'Get owner's details', 'href':'/users/123' } ] } As you can see we make a simple GET request to a specific URL and what we get back are the details of an item. This item has some properties and a number of links. These links can be followed by the user of your API to explore other resources or execute some action on your API. I won’t go into much detail here, but if you want to know what to do to create an easy to use and flexible API look at my presentation. We know what our client needs to do to get this resource. The scalatra code is very easy: package org.smartjava.scalatra import grizzled.slf4j.Logger import org.scalatra._ import scalate.ScalateSupport import net.liftweb.json.compact import net.liftweb.json.render import net.liftweb.json.JsonDSL._ import net.liftweb.json.Serialization.{read, write} import org.smartjava.scalatra.repository.ItemRepository import net.liftweb.json.Serialization import net.liftweb.json.NoTypeHints import org.scalatra.Ok import org.scalatra.NotFound import org.smartjava.scalatra.repository.BidRepository import org.scalatra.Created import scala.collection.immutable.Map import org.smartjava.scalatra.model.Bid class HelloScalatraServlet extends ScalatraServlet with ScalateSupport { // simple logger val logger = Logger(classOf[HelloScalatraServlet]); // repo stores our items val itemRepo = new ItemRepository; val bidRepo = new BidRepository; // implicit value for json serialization format implicit val formats = Serialization.formats(NoTypeHints); get('/items/:id') { // set the result content type contentType = 'application/vnd.smartbid.item+json' // convert response to json and return as OK itemRepo.get(params('id').toInt) match { case Some(x) => Ok(write(x)); case None => NotFound('Item with id ' + params('id') + ' not found'); } } } For this first REST operation I list the complete class, for the rest I’ll only show the relevant functions. To handle the request we need to define a ‘route’. get('/items/:id') { // set the result content type contentType = 'application/vnd.smartbid.item+json' // convert response to json and return as OK itemRepo.get(params('id').toInt) match { case Some(x) => Ok(write(x)); case None => NotFound('Item with id ' + params('id') + ' not found'); } This route listens for GET operations on the /items/:id url. Whenever a request is received, this function is invoked. In this function we first set the resulting content-type. I’m a proponent of creating custom media-types for my resources, so we set our result content-type to ‘application/vnd.smartbid.item+json’. Next we need to retrieve our item from our repository and serialize it to JSON. For JSON serialization I’ve used lift-json. With this library you can automatically serialize case classes (or create and parse the json by hand). To use lift-json you need to add the following line to the libraryDependencies in build.sbt file and update the eclipse project from sbt.. 'net.liftweb' %% 'lift-json' % '2.4', The code that writes our the class files as json is this one-liner case Some(x) => Ok(write(x)); If we can find the item in the repository we write it out as json using the write function. We return this JSON as a ‘200 OK’ response by using the scalatra OK function. If the resource can’t be find, we sent out a 404 using this one-liner. case None => NotFound('Item with id ' + params('id') + ' not found'); For completeness sake I’ll list model and dummy repo implementation: Model: case class Item( name:String, id: Number, startPrice: Number, currency: String, description: String, links: List[Link] ); case class Link( linkType: String, rel: String, href: String ); case class Bid( id: Option[Long], forItem: Number, minimum: Number, maximum: Number, currency: String, bidder: String, date: Long ); Dummy repo: class ItemRepository { def get(id: Number) : Option[Item] = { id.intValue() match { case 123 => { val l1 = new Link('application/vnd.smartbid.item','Add item to watchlist','/users/123/watchlist'); val l2 = new Link('application/vnd.smartbid.bid','Place bid on item','/items/' + id + '/bid'); val l3 = new Link('application/vnd.smartbid.user','Get owner's details','/users/123'); val item = new Item( 'Monty Python and the search for the holy grail', id, 0.69, 'GBP', 'Must have item', List(l1,l2,l3)); Option(item); }; case _ => Option(null); } } def delete(item: Item) = println('deleting user: ' + item) } With this code we’ve got our first REST operation finished. We can test this service easily using Chrome’s Dev HTTP client I mentioned earlier:In the response you can see a number of links, one of them is the following: { 'linkType':'application/vnd.smartbid.bid', 'rel':'Place bid on item', 'href':'/items/123/bid' } You can see a href attribute here. We can follow this link to place a bid.Make a bid on a specific item. To do this we need to make a POST to ‘/items/123/bid’ with a bid of type ‘application/vnd.smartbid.bid’. The format looks like this: { 'forItem':123, 'minimum':20, 'maximum':10, 'currency':'GBP', 'bidder':'jdirksen', 'date':1347269593301 } Let’s look once again at the code for this operation. post('/items/:id/bid', request.getContentType == 'application/vnd.smartbid.bid+json') { contentType = 'application/vnd.smartbid.bid+json' var createdBid = bidRepo.create(read[Bid](request.body)); Created(write(createdBid), Map('Location'->('/users/' + createdBid.bidder + '/bids/'+createdBid.id.get))); } As you can see by the name, this operation listens for a POST on ‘/items/:id/bid’. Since I want the API to be media-type driven I added an extra condition to this route. With ‘ request.getContentType == ‘application/vnd.smartbid.bid+json’ we require the clients of this operation to indicate that the type of resource they sent is of this specific type. The operation itself isn’t so complex. We set the content-type of the result and use a repository to create a bid. For this we use the read operation from lift-json to convert the incoming JSON to a scala object. The created object is returned with a ‘201 Created’ status message and contains a location header that points to the resource that we just created.Get a bid a user has made. The final operation we support for now is a simple one where we can view the bid we just created. We know where to look, because the location of the just created resource was returned in the location header. The scala code for this function is shown here: /** * Route that matches retrieval of bids */ get('/users/:user/bids/:bid') { contentType = 'application/vnd.smartbid.bid+json' bidRepo.get(params('bid').toInt,params('user')) match { case Some(x) => Ok(write(x)); case None => NotFound('Bid with id ' + params('bid') + ' not found for user: ' + params('user') ); } } Pretty much the same as we’ve seen for the retrieval of the items. We retrieve the resource from a repository, if it exists we return it with a ‘200 OK’, if not we return a 404.Test your service using specs2 In the final section for this part of the tutorial we’ll have a quick look at testing. When you create a new scalatra project as we’ve shown in the previous part, we also get a stub test we can extend to test our service. For this exampe I won’t write low level, simple JUnit tests, but we’ll create a specification that describes how our API should work. The code for a (part) of the specification is listed here: package org.smartjava.scalatra import org.scalatra.test.specs2._ import org.junit.runner.RunWith import org.scalatra.test.Client import org.specs2.SpecificationWithJUnit import org.eclipse.jetty.util.log.Log /** * Set of JUnit test to test our API */ class HelloScalatraServletSpec extends ScalatraSpec { // add the servlet so we can start testing addServlet(classOf[HelloScalatraServlet], '/*') // some constants val EXPECTED_BID = '''{'id':345,'forItem':123,'minimum':20,'maximum':10,'currency':'GBP','bidder':'jdirksen','date':1347285103671}''' val BID_URL = '/users/jdirksen/bids/345'; val MED_TYPE = 'application/vnd.smartbid.bid+json' def is = 'Calling an unknown url on the API ' ^ 'returns status 404' ! statusResult('/unknown',404)^ end ^ p ^ 'Calling a GET on ' + BID_URL + ' should' ^ 'return status 200' ! statusResult(BID_URL,200)^ 'and body should equal: ' + EXPECTED_BID ! {get(BID_URL){response.body must_== EXPECTED_BID}}^ 'and media-type should equal: ' + MED_TYPE ! {get(BID_URL){response.getContentType must startWith(MED_TYPE)}} end def statusResult(url:String,code:Int) = get(url) { status must_== code } } For a more complete introduction into specs2 look at their website, I’ll just explain the code shown here. In this code we create a scenario the ‘def is’ part. ‘is’ contains a number of statements that must be true. 'Calling an unknown url on the API ' ^ 'returns status 404' ! statusResult('/unknown',404)^ end ^ p ^ The first test we do is checking what happens when we call an unknown URL on our API. We define that for this we expect a 404. We check this by calling the statusResult function. If 404 is returned this check will pass, if not we’ll see this in the results. The actual ‘statusResult’ function is also defined in this file. This function uses the build in ‘get’ function to make a call to our API, which runs embedded from this test. Next we’re going to check how the get bid URL should work. 'Calling a GET on ' + BID_URL + ' should' ^ 'return status 200' ! statusResult(BID_URL,200)^ 'and body should equal: ' + EXPECTED_BID ! {get(BID_URL){response.body must_== EXPECTED_BID}}^ 'and media-type should equal: ' + MED_TYPE ! {get(BID_URL){response.getContentType must startWith(MED_TYPE)}} As you can see, the same basic structure is followed. We run a number of checks that should pass. If we run this we can instantly see how our API should behave (instant documentation) and whether it confirms to our specification. This is the output from the test. HelloScalatraServletSpec Calling an unknown url on the API + returns status 404 Calling a GET on /users/jdirksen/bids/345 should + return status 200 + and body should equal: {'id':345,'forItem':123,'minimum':20,'maximum':10,'currency':'GBP','bidder':'jdirksen','date':1347285103671} + and media-type should equal: application/vnd.smartbid.bid+json Total for specification HelloScalatraServletSpec Finished in 846 ms 4 examples, 0 failure, 0 error Specs2 has a number of different ways it can be run. It can be run directly as a JUnit testcase, from maven or using it’s own launcher. Since I’m developping in Eclipse I wanted to run these tests directly from Eclipse. So I started out with the JUnit testrunner. The problem, however, with this runner is that it seems to conflict with the internally used Jetty from Eclipse. When I rant this the test tried to contact a Jetty instance on port 80, instead of using the embedded one it had started itself. To fix this I created a simple launcher that ran this test directly. To do this make the following launch configuration to get the output I just showed. Run configuration part 1Run configuration part 2Now whenever you run this configuration the specs2 tests are run. That’s it for this part of the tutorial. In the next part we’ll look at database access and using akka. Happy coding and don’t forget to share! Reference: Tutorial: Getting started with scala and scalatra – Part II from our JCG partner Jos Dirksen at the Smart Java blog....

Android Custom Hyperlinked TextView

Finding Links in Android is very simple you might have heard of Linkify which is a great class in which there are many static methods for getting a simple job done but the problem is that in Linkify you cannot specify the behavior that you require on clicking the links at the Most what Linkify does is that it simply finds the links based on the “Pattern” you provide and adds a “Scheme” string to complete the URL and created a Android Intent for Launching the Browser. The Linkify behavior cannot be overridden as all the methods in Linkify class are static final. This was the issue that inspired me to create a Custom TextView Widget the one which collects the links in my scenario I also programmed it to collect the the Strings starting with “@” and “#” but this things can be changed by simply changing the Patterns that you require and giving the proper Regular Expression for them. The LinkEnableTextView class is like this: import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Context; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ClickableSpan; import android.util.AttributeSet; import android.view.View; import android.widget.TextView;public class LinkEnabledTextView extends TextView { // The String Containing the Text that we have to gather links from private SpannableString linkableText; // Populating and gathering all the links that are present in the Text private ArrayList<Hyperlink> listOfLinks;// A Listener Class for generally sending the Clicks to the one which requires it TextLinkClickListener mListener;// Pattern for gathering @usernames from the Text Pattern screenNamePattern = Pattern.compile('(@[a-zA-Z0-9_]+)');// Pattern for gathering #hasttags from the Text Pattern hashTagsPattern = Pattern.compile('(#[a-zA-Z0-9_-]+)');// Pattern for gathering http:// links from the Text Pattern hyperLinksPattern = Pattern.compile('([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\'>\\]\\)]*[^\\. ,'\'>\\]\\)])');public LinkEnabledTextView(Context context, AttributeSet attrs) { super(context, attrs); listOfLinks = new ArrayList<Hyperlink>();}public void gatherLinksForText(String text) { linkableText = new SpannableString(text); //gatherLinks basically collects the Links depending upon the Pattern that we supply //and add the links to the ArrayList of the links gatherLinks(listOfLinks, linkableText, screenNamePattern); gatherLinks(listOfLinks, linkableText, hashTagsPattern); gatherLinks(listOfLinks, linkableText, hyperLinksPattern);for(int i = 0; i< listOfLinks.size(); i++) { Hyperlink linkSpec = listOfLinks.get(i); android.util.Log.v('listOfLinks :: ' + linkSpec.textSpan, 'listOfLinks :: ' + linkSpec.textSpan); // this process here makes the Clickable Links from the text linkableText.setSpan(linkSpec.span, linkSpec.start, linkSpec.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } // sets the text for the TextView with enabled links setText(linkableText); }// sets the Listener for later click propagation purpose public void setOnTextLinkClickListener(TextLinkClickListener newListener) { mListener = newListener; }//The Method mainly performs the Regex Comparison for the Pattern and adds them to //listOfLinks array listprivate final void gatherLinks(ArrayList<Hyperlink> links, Spannable s, Pattern pattern) { // Matcher matching the pattern Matcher m = pattern.matcher(s);while (m.find()) { int start = m.start(); int end = m.end(); // Hyperlink is basically used like a structure for storing the information about // where the link was found. Hyperlink spec = new Hyperlink();spec.textSpan = s.subSequence(start, end); spec.span = new InternalURLSpan(spec.textSpan.toString()); spec.start = start; spec.end = end;links.add(spec); } }// This is class which gives us the clicks on the links which we then can use.public class InternalURLSpan extends ClickableSpan { private String clickedSpan;public InternalURLSpan (String clickedString) { clickedSpan = clickedString; }@Override public void onClick(View textView) { mListener.onTextLinkClick(textView, clickedSpan); } }// Class for storing the information about the Link Locationclass Hyperlink { CharSequence textSpan; InternalURLSpan span; int start; int end; } Now, having this you require just another interface for propagating the clicks to the place you require to handle them in my case I implemented the interface in my Activity and simple wrote a Log Command there. The TextLinkClickListener interface is like this: import android.view.View;public interface TextLinkClickListener { // This method is called when the TextLink is clicked from LinkEnabledTextView public void onTextLinkClick(View textView, String clickedString) }After doing all this you just require to create an Activity using the Custom LinkEnabledTextView and check the things out yourself. There are a few things that you must do while creating a object of the Custom LinkEnabledTextView those are mentioned and described in the Code of the Activity below: import android.text.method.MovementMethod; import com.umundoinc.Tvider.Component.LinkEnabledTextView.LinkEnabledTextView; import com.umundoinc.Tvider.Component.LinkEnabledTextView.TextLinkClickListener; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.View;//Here the Activity is implementing the TextLinkClickListener the one we have created //the Clicks over the Links are forwarded over here from the LinkEnabledTextView public class TextViewActivity extends Activity implements TextLinkClickListener { private LinkEnabledTextView check; protected void onCreate(Bundle savedInstance) { super.onCreate(savedInstance);String text = "This is a #test of regular expressions with http://example.com/ links as used in @twitter for performing various operations based on the links this handles multiple links like http://this_is_fun.com/ and #Awesomess and @Cool";check = new LinkEnabledTextView(this, null); check.setOnTextLinkClickListener(this); check.gatherLinksForText(text); check.setTextColor(Color.WHITE); check.setLinkTextColor(Color.GREEN);MovementMethod m = check.getMovementMethod(); if ((m == null) || !(m instanceof LinkMovementMethod)) { if (check.getLinksClickable()) { check.setMovementMethod(LinkMovementMethod.getInstance()); } }setContentView(check); }public void onTextLinkClick(View textView, String clickedString) { android.util.Log.v('Hyperlink clicked is :: ' + clickedString, 'Hyperlink clicked is :: ' + clickedString); }Here, is the Screenshot describing the output in my Listener method I programmed it to display a Toast but anything can be achieved in same method.Now that’s pretty much all that you’ll need that makes the Custom LinkEnabledTextView working, try it out and share your views and reviews over it. Reference: Android Custom Hyperlinked TextView from our JCG partner Y Kamesh Rao at the OrangeApple blog....

How Hackers Choose Tools

Recently, a 2001 blog post with the title Java’s Cover written by Paul Graham (of Y Combinator fame) spread across Twitter and was linked by all the other usual tech site suspects. The piece was about what Graham called ‘hacker’s radar‘, which he describes as the ability of hackers to ‘develop a nose for good (and bad) technology‘. For his description of hacker’s radar, he decided to cite Java as an example of a technology that smelled bad at the time. Java’s popularity in 2001 made it a pretty big target for critique. The title Java’s Cover is a reference to judging a book by the cover, and Graham argued that Java’s cover was a stinker. Graham admits in the article that he had never written Java and his main exposure was when he ‘glanced over reference books‘, though Graham does have substantial tech credibility as a hacker. He lists 12 reasons why he didn’t like the look of Java, and mentions that he had a hunch that Java would not be a very ‘successful language‘ (but he ‘may turn out to be mistaken‘). The commentary on the aforementioned usual suspect sites seems, predictably and unfortunately, to be centered on the accuracy (‘is Java truly successful?’) or inaccuracy (Java is everywhere) of the prediction itself. I feel it is a much more interesting exercise to take the opportunity to go into the author’s opinions as representative of an advanced technologist, and to see what factors would lead a like-minded and influential technologist to potentially have the same negative reaction to a new tool/language based on relatively non-technical factors. Every day we read articles that are highly critical of languages, frameworks, design patterns, and anything else you can imagine, and it can be difficult to tell how much experience the author may actually have (or even need) to make such assertions. When an industry voice writes an opinion on a topic based on the factors listed by Graham, what weight is given to the conclusions by the community? Graham’s article is somewhat unique in that he was willing to list the ‘smell’ reasons for his suspicion. Looking at each reason Graham gave individually may give us some insight into how technologists yesterday and today may form opinions about a variety of topics, and whether or not we can use these tests to determine future success. 1. It has been so energetically hyped. While it is certainly true that excessive hype can be a sign of any potential product’s weakness, that certainly isn’t always the case. Graham mentions notes that ‘A real standard tends to be already established by the time most people hear about it’. You will find that almost every technology that is highly criticized has been blessed/cursed with a fair amount of hype, either generated by marketing people with profit motive or evangelists that may have much smaller (or even zero) financial interests. I’m not sure that hype alone should make technologists wary about a new offering, but people who are naturally skeptical will surely be wary of over-the-top hype efforts. 2. It’s aimed low. This one seems to have some merit. In this case Graham is saying that Java is intentionally dumbed down, and that ‘Java’s designers were consciously designing a product for people not as smart as them. Historically, languages designed for other people to use have been bad: Cobol, PL/I, Pascal, Ada, C++. The good languages have been those that were designed for their own creators: C, Perl, Smalltalk, Lisp.‘ When people create a product/tool for other people to use, they obviously want their audience to be able to learn it, and Graham seems to argue that by ‘aiming low’ and focusing on ease of use you are probably placing unnecessary limitations on the product you are building. If you were creating based solely on the need to solve specific problems, ease of use would not be as great a factor. 3. It has ulterior motives. In this case Graham is speaking of Sun’s plan to ‘undermine‘ Microsoft. We could certainly apply some tests of ulterior motives to several new developments in tech over the past several years, but I’d imagine it would be a difficult task to find similar motives in the overwhelming majority of new products. This one is probably, in most cases, not applicable. 4. No one loves it. Ouch! Every language, every tool, is loved by someone. Remember all those people in #1 above that make up the hype machine? Perhaps by saying ‘I’ve never heard anyone say that they loved Java‘, Graham meant that that no one of any influence or importance loves it. If a product is eschewed by the most widely respected folks in industry, that is a warning sign. When some thought leaders begin to endorse tools they become viable for others to adopt (see alternative JVM programming language adoption by big firms today). Some former Java evangelists professing a love for Scala comes to mind. 5. People are forced to use it. Being told that you have to use a tool does not make it questionable, but in Graham’s brief description he infers that the anecdotal evidence includes smart people that would have used the tool voluntarily if it were good. This is probably better said as ‘Outside forces with potentially differing objectives force technologists to use it against the techie’s own better judgement.’ It’s hard to argue with that. 6. It has too many cooks. This one is quite interesting, especially with the changes that have occurred in the industry since 2001 and the emergence of open source as a dominant player in the market. Graham went on to write that ‘the best programming languages have been developed by small groups. Java seems to be run by a committee. If it turns out to be a good language, it will be the first time in history that a committee has designed a good language.‘ Issues with the JCP over the years have been written about ad nauseam. But what would Graham make of other open source developments over the years? I imagine the rebuttal would be that only the highest level members of an open source project are truly the ‘cooks’ he refers to, with the rest of the members merely relegated to chopping and slicing. Maybe not. Being suspicious of multiple decision-makers pandering to multiple masters would be natural, and warranted. 7. It’s bureaucratic. In this case Graham is referring to the language structure itself and not the leadership. This can be perhaps lumped into #2 It’s aimed low although not in every instance. If a language is ‘aimed low’, you might expect that the designers would try and limit the types of mistakes users could make (see #9 as well). 8. It’s pseudo-hip. Interesting perspective. I’d argue it was hip. Graham continued, ‘Sun now pretends that Java is a grassroots, open-source language effort like Perl or Python. This one just happens to be controlled by a giant company. So the language is likely to have the same drab clunkiness as anything else that comes out of a big company.‘ I couldn’t help but notice the words Graham uses to critique Java in 2001 are very similar to how Democrats paint the modern day Tea Party (an observation on the language, not a political statement). The real meat of this criticism seems to be that the product is controlled by a large organization, which per Graham would by default make it ‘clunky’, but posing as a much more community-friendly and open option. I’m guessing this element of Graham’s opinion would have been amplified dramatically after the Oracle acquisition. Would hackers feel differently if a big company tool wore the corporate badge proudly? 9. It’s designed for large organizations. Graham specifies that Java was designed to limit large teams of mediocre programmers from causing damage. This seems very much like reasons #2 It’s aimed low and #7 It’s bureaucratic above. This is probably more accurately categorized as ‘designed for mediocre programmers‘. I would assume that any advanced technologist would probably be less interested in a tool that seems to be created for a lesser engineer. Graham wants only languages for big boys and girls, and most advanced and even intermediate hackers would probably agree. 10. The wrong people like it. Graham lists the wrong people as ‘suits’ tuned into the hype from #1, big company programmers from #9, and college kids looking to get a job. He feels that all three of these groups change their minds regularly. I’d say the college kids of 2012 appear to be interested in newer technologies (Ruby, Python, functional programming, mobile) that are probably not the core of their curriculum (Java), and in 2001 they were also interested in newer technologies (Java) that were also not the focus of their education (C/C++). Does the interest of college grads in Ruby and Python make those tools the wrong tools, or do today’s college grads have a bit more of a sophisticated hacker palate? What do the suits and big company programmers love today? Tools with ample talent supply, maybe? 11. Its daddy is in a pinch. Java’s OLD daddy was, but Java’s new daddy buys islands! But this isn’t about Java. The financial standing of the steward of a language or product is certainly a valid consideration to make when evaluating the future viability regarding use in developing a product. But who would be deemed the daddy of open source tools? Individual project owners perhaps? The vendor ecosystem that supports them? The landscape has changed enough since 2001 that this criticism might be less of a factor now. 12. The DoD likes it. Guilt by association, and Graham calls DoD culture the ‘opposite‘ of hacker culture. In some recent discussions about Java and alternative JVM languages, I’ve seen this discrimination used in reverse, where Java supporters claim that the use of the alternative JVM languages by start-ups is a strike against using the alternative options. The argument is that start-ups are all run by kids and cowboys, so any choices they make can’t be grounded in solid technical judgment. Interesting how two groups, who both probably feel they are above-average technologists, can come up with opposite interpretations. CONCLUSION If you made it to the very bottom of Graham’s post, there is a link to an article called Trevor Re: Java’s Cover, which refers to comments by Trevor Blackwell (also a YC partner) about the post. Blackwell classifies programmers as either ‘brilliant hackers‘ or ‘corporate drones‘ with most tools being written for the drones, so hackers need to know the smell tests to decipher quickly which tools are meant for the hacker and which were designed for the drones. Of course, very few of the people Blackwell calls drones probably feel they are in that camp, which just complicates the issues even more. I feel that Graham’s article is interesting as a time capsule to compare how hackers thought about new tools in 2001 and how they may come to conclusions about languages today. As an investor, I’m sure some of the same smell tests Graham listed would apply to how he evaluates start-ups for potential funding. Whether Graham was right or wrong about Java doesn’t matter at all, but getting a glimpse into his thought process then is quite valuable. How would the current batch of popular and emerging technologies fair today, using Graham’s microscope? Don’t forget to share! Reference: How Hackers Choose Tools (thoughts on Paul Graham’s Java’s Cover) from our JCG partner Dave Fecak at the Job Tips For Geeks blog....

Gateway interaction in Smack API

Gateway interaction is described by XEP-0100. The query xmlns (namespace) used for this is same as IN-Band registration, that is “jabber:iq:register”. Smack API provides an easy way handle gateway interaction with the server. It has predefined classes for the required namespace and operations which one can easily use and do the thing. In this article I will explain how one can register, edit, unregister and retrieve gateway information using Smack library. I have listed both XML and code using Smack API for the purpose. I have used Openfire server with Kraken plugin in it for gateway related operations described in this article. 1. Gateway service discovery First you have to send an IQ-get with xmlns of the service discovery info to the Gateway. The XML would look like this: <iq id='uLQX1-3' to='gtalk.mtHost' type='get'> <query xmlns='http://jabber.org/protocol/disco#info'></query> </iq> And in return Gateway returns identity information like this: <iq id='uLQX1-3' to='user1@myHost/Smack' from='gtalk.myHost' type='result'> <query xmlns='http://jabber.org/protocol/disco#info'> <identity category='gateway' name='Google Talk Transport' type='xmpp'/> <feature var='http://jabber.org/protocol/disco#info'/> <feature var='http://jabber.org/protocol/disco#items'/> <feature var='jabber:iq:gateway'/> <feature var='jabber:iq:register'/> <feature var='jabber:iq:version'/> <feature var='vcard-temp'/> </query> </iq> By this you can identify which namespace features are supported by the gateway. To register and/or unregister the gateway “jabber:iq:register” support is required. This response can differ at your side based on your server and Gateway support. Now the code using Smack API for this operation is as follows: DiscoverInfo iq = new DiscoverInfo(); iq.setType(IQ.Type.GET); iq.setTo('gtalk.myHost'); PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(iq.getPacketID())); connection.sendPacket(iq); IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel(); System.out.println(response.toXML()); And to check for specific feature is supported or not and getting information of items in response do the following: if (response != null && !response.getType().equals(IQ.Type.ERROR) && response instanceof DiscoverInfo) { DiscoverInfo info = (DiscoverInfo) response; Iterator<Identity> identities = info.getIdentities(); while (identities.hasNext()) { DiscoverInfo.Identity identity = (DiscoverInfo.Identity) identities.next(); System.out.println('identity name -> ' + identity.getName()); System.out.println('identity category -> ' + identity.getCategory()); System.out.println('identity type -> ' + identity.getType()); } System.out.println(info.containsFeature('jabber:iq:register')); }2. Get information of gateway To query gateway id about which information is required to register, you need to send following xml: <iq id='VT12T-4' to='gtalk.myHost' type='get'> <query xmlns='jabber:iq:register'></query> </iq> In response server will respond something like this: <iq id='VT12T-4' to='user1@myHost/Smack' from='gtalk.myHost' type='result'> <query xmlns='jabber:iq:register'> <instructions>Please enter your e-mail address and password used with GMail and GTalk</instructions> <username></username> <password></password> <x xmlns='jabber:x:data' type='form'> <instructions>Please enter your e-mail address and password used with GMail and GTalk.</instructions> <field label='Address' var='username' type='text-single'></field> <field label='Password' var='password' type='text-private'></field> </x> <x xmlns='jabber:iq:gateway:register'></x> </query> </iq> By this you will know that which fields are required for gateway registration. Here in this example 2 fields are require, one is username and another is password. Code to do this in smack is: 1) Send GET request to gateway Registration iq = new Registration(); iq.setType(IQ.Type.GET); iq.setTo('gtalk.myHost'); connection.sendPacket(iq); 2) Get the response. PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(iq.getPacketID())); IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel(); System.out.println(response.toXML()); 3) Process the response for extracting required information like this: if (response != null && !response.getType().equals(IQ.Type.ERROR) && response instanceof Registration) { Registration registration = (Registration) response; System.out.println(registration.getInstructions()); if (registration.getAttributes() != null && !registration.getAttributes().isEmpty()) { Map<String, String> map = registration.getAttributes(); System.out.println(map); } }3. Register gateway: To register a gateway using one has to send IQ SET with the required attributes: <iq id='WiISc-2' to='gtalk.myHost' type='set'> <query xmlns='jabber:iq:register'> <username>user</username> <password>pass</password> </query> </iq> And as a successful response server will send back following xml: <iq type='result' from='gtalk.myHost' to=user1@myHost/Smack' id='WiIsc-2'/> And here is the code to do registration using Smack API: 1) Send an IQ set packet. For jabber:iq:register we will use Registration class from smack library: Map<String, String> attributes = new HashMap<String, String>(); attributes.put('username', 'user'); attributes.put('password', 'pass'); Registration registration = new Registration(); registration.setType(IQ.Type.SET); registration.setTo('aim.myHost'); registration.setAttributes(attributes); connection.sendPacket(registration); 2) Get the response: PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(registration.getPacketID())); IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel();4. Retrieve registered gateway information: To retrieve registered gateway information one has to send an IQ GET packet with “jabber:iq:register” query to the gateway id (i.e. gtalk.myHost). This is similar what we did to get gateway information. In short when you can query gateway for information it will return the information with currently registered information, if any and if there there are no registered information then response is just about the required field names to register. <iq id='VT12T-4' to='gtalk.myHost' type='get'> <query xmlns='jabber:iq:register'></query> </iq> The gateway returns registration requirements with already registered information like following: <iq type='result' id='VT12T-4'> <query xmlns='jabber:iq:register'> <registered/> <username>user</username> <password>pass</password> </query> </iq> One can do this thing in Smack API as follows: 1) Send IQ GET packet to gateway: Registration message = new Registration(); message.setTo('gtalk.myHost'); message.setType(IQ.Type.GET); connection.sendPacket(message); 2) Get and process the response returned by gateway: PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(message.getPacketID())); IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel(); if (response != null && !response.getType().equals(IQ.Type.ERROR) && response instanceof Registration) { Registration registration = (Registration) response; if (registration.getAttributes() != null && !registration.getAttributes().isEmpty()) { Map<String, String> map = registration.getAttributes(); // map contains information about registration. } }5. Edit registered information: To edit registered information one has to first fetch information as shown in above section and then follow the same code for registering gateway. In simple words do point 3 & 4 form this article in reverse order.6. Unregister gateway To unregister a gateway first query for the registered gateway to see if any gateway information is registered or not. If it is registered then to unregister you just have to add a “remove” attribute in the IQ set as follows: <iq type='set' from=user1@myHost/Smack' to='gtalk.myHost' id='VTiLk-4'> <query xmlns='jabber:iq:register'> <remove/> <!—remove is for unregisterting the gateway --> </query> </iq> This is very similar to the register gateway xml so difference in code is very small. Instead of adding username and password as attributes in Map you just add a “remove” attribute and everything else is same. Remove these 2 lines from register gateway code: attributes.put('username', 'user'); attributes.put('password', 'pass'); And add following line instead: attributes.put('remove', ''); // no need to provide any value as remove tag is an empty tag Everything else in the code is same. Response is also similar to the register gateway response. Happy coding and don’t forget to share! Reference: Gateway interaction in Smack API from our JCG partner Harsh Raval at the harryjoy blog....

Common code violations in Java

At work, recently I did a code cleanup of an existing Java project. After that exercise, I could see a common set of code violations that occur again and again in the code. So, I came up with a list of such common violations and shared it with my peers so that an awareness would help to improve the code quality and maintainability. I’m sharing the list here to a bigger audience. The list is not in any particular order and all derived from the rules enforced by code quality tools such as CheckStyle, FindBugs and PMD. Here we go!Format source code and Organize imports in Eclipse: Eclipse provides the option to auto-format the source code and organize the imports (thereby removing unused ones). You can use the following shortcut keys to invoke these functions.Ctrl + Shift + F – Formats the source code. Ctrl + Shift + O – Organizes the imports and removes the unused ones.Instead of you manually invoking these two functions, you can tell Eclipse to auto-format and auto-organize whenever you save a file. To do this, in Eclipse, go to Window -> Preferences -> Java -> Editor -> Save Actions and then enable Perform the selected actions on save and check Format source code + Organize imports. Avoid multiple returns (exit points) in methods: In your methods, make sure that you have only one exit point. Do not use returns in more than one places in a method body. For example, the below code is NOT RECOMMENDED because it has more then one exit points (return statements). private boolean isEligible(int age){ if(age > 18){ return true; }else{ return false; } } The above code can be rewritten like this (of course, the below code can be still improved, but that’ll be later). private boolean isEligible(int age){ boolean result; if(age > 18){ result = true; }else{ result = false; } return result; }Simplify if-else methods: We write several utility methods that takes a parameter, checks for some conditions and returns a value based on the condition. For example, consider the isEligible method that you just saw in the previous point. private boolean isEligible(int age){ boolean result; if(age > 18){ result = true; }else{ result = false; } return result; } The entire method can be re-written as a single return statement as below. private boolean isEligible(int age){ return age > 18; }Do not create new instances of Boolean, Integer or String: Avoid creating new instances of Boolean, Integer, String etc. For example, instead of using new Boolean(true), use Boolean.valueOf(true). The later statement has the same effect of the former one but it has improved performance.Use curly braces around block statements. Never forget to use curly braces around block level statements such as if, for, while. This reduces the ambiguity of your code and avoids the chances of introducing a new bug when you modify the block level statement. NOT RECOMMENDED if(age > 18) result = true; else result = false; RECOMMENDED if(age > 18){ result = true; }else{ result = false; }Mark method parameters as final, wherever applicable: Always mark the method parameters as final wherever applicable. If you do so, when you accidentally modify the value of the parameter, you’ll get a compiler warning. Also, it makes the compiler to optimize the byte code in a better way. RECOMMENDED private boolean isEligible(final int age){ ... }Name public static final fields in UPPERCASE: Always name the public static final fields (also known as Constants) in UPPERCASE. This lets you to easily differentiate constant fields from the local variables. NOT RECOMMENDED public static final String testAccountNo = '12345678'; RECOMMENDED public static final String TEST_ACCOUNT_NO = '12345678';, Combine multiple if statements into one: Wherever possible, try to combine multiple if statements into single one. For example, the below code; if(age > 18){ if( voted == false){ // eligible to vote. } } can be combined into single if statements, as: if(age > 18 && !voted){ // eligible to vote }switch should have default: Always add a default case for the switch statements.Avoid duplicate string literals, instead create a constant: If you have to use a string in several places, avoid using it as a literal. Instead create a String constant and use it. For example, from the below code, private void someMethod(){ logger.log('My Application' + e); .... .... logger.log('My Application' + f); } The string literal “My Application” can be made as an Constant and used in the code. public static final String MY_APP = 'My Application';private void someMethod(){ logger.log(MY_APP + e); .... .... logger.log(MY_APP + f); }Additional Resources:A collection of Java best practices. List of available Checkstyle checks. List of PMD Rule setsReference: Common code violations in Java from our JCG partner Veera Sundar at the Veera Sundar blog....

Apache Digester Example – Make Easy Configuration

Address Problem – Hard Coding , Need to create custom configuration for your application like struts configuration file to vary application behavior just by changing the file. Apache Digester can do it for you easily. Transforming an XML document into a corresponding hierarchy of Java bean objects is a fairly easy using Apache Digester. See Digester in action below. Digester introduces three important concepts:element matching patterns processing rules the object stack.Element matching patterns associate XML elements with processing rules. Example : What you have:Java Classes XML files containing dataYou have java classes and corresponding xml files. You want java classses instances to be created from xml data. What extra code you need to write. Step by step tasks:Add Apache Digester 3 jar file, Commons logging jar, Beanutils jar,cglib jar in your class path If don’t have the java classes, create java classes for corresponding xml file.Or if don’t have xml files, create it as per the java classes.Note- property name,hierarchy in xml and java class should match, otherwise you need to provide mapping in your digester xml rule not mentioned here. Create a digester rule xml file as mentioned in the example below Use few lines of to load java objects from xmlNow In Action – Here is my eclipse project structure :Task 2 - create data xml file as below you want data from which to be loaded say – chain-config.xml <?xml version="1.0" encoding="UTF-8"?><catalogs><!-- Default Catalog: "Path Info" example --> <catalog><!-- Command that maps "Path Info" patterns to Commands --> <chain name="COMMAND_MAPPER"> <command className="org.apache.commons.chain.web.servlet.PathInfoMapper"/> <command forward="/pathinfo.jsp" className="org.apache.commons.chain.apps.example.ForwardCommand"/> </chain><!-- Foo Command --> <chain name="/foo"> <command attribute="pathinfoFooCount" className="org.apache.commons.chain.apps.example.CountCommand"/> </chain><!-- Bar Command --> <chain name="/bar"> <command attribute="pathinfoBarCount" className="org.apache.commons.chain.apps.example.CountCommand"/> </chain></catalog><!-- Catalog for "Request Parameter" example --> <catalog name="reqparam"><!-- Command that maps a "Request Parameter" to Commands --> <chain name="COMMAND_MAPPER"> <command catalogName="reqparam" className="org.apache.commons.chain.web.servlet.RequestParameterMapper"/> <command forward="/reqparam.jsp" className="org.apache.commons.chain.apps.example.ForwardCommand"/> </chain><!-- Foo Command --> <chain name="foo"> <command attribute="reqparamFooCount" className="org.apache.commons.chain.apps.example.CountCommand"/> </chain><!-- Bar Command --> <chain name="bar"> <command attribute="reqparamBarCount" className="org.apache.commons.chain.apps.example.CountCommand"/> </chain></catalog></catalogs>Create corresponding java classses Catalog.java : import java.util.ArrayList; import java.util.List;public class Catalog {/** * @uml.property name="name" */ private String name;/** * Getter of the property <tt>name</tt> * @return Returns the name. * @uml.property name="name" */ public String getName() { return name; }/** * Setter of the property <tt>name</tt> * @param name The name to set. * @uml.property name="name" */ public void setName(String name) { this.name = name; }/** * @uml.property name="chains" */ private List<Chain> chains=new ArrayList<Chain>(); public void addChains(Chain chain) { this.chains.add(chain); }}Chain.java : import java.util.ArrayList; import java.util.List;public class Chain {/** * @uml.property name="name" */ private String name;/** * Getter of the property <tt>name</tt> * @return Returns the name. * @uml.property name="name" */ public String getName() { return name; }/** * Setter of the property <tt>name</tt> * @param name The name to set. * @uml.property name="name" */ public void setName(String name) { this.name = name; }/** * @uml.property name="commands" */ private List<Command> commands=new ArrayList<Command>();/** * Setter of the property <tt>commands</tt> * @param commands The commands to set. * @uml.property name="commands" */ public void addCommands(Command command) { this.commands.add(command); }}Command.java : import java.util.ArrayList; import java.util.List;public class Chain {/** * @uml.property name="name" */ private String name;/** * Getter of the property <tt>name</tt> * @return Returns the name. * @uml.property name="name" */ public String getName() { return name; }/** * Setter of the property <tt>name</tt> * @param name The name to set. * @uml.property name="name" */ public void setName(String name) { this.name = name; }/** * @uml.property name="commands" */ private List<Command> commands=new ArrayList<Command>(); /** * Getter of the property <tt>commands</tt> * @return Returns the commands. * @uml.property name="commands" */ public List getCommands() { return commands; }/** * Setter of the property <tt>commands</tt> * @param commands The commands to set. * @uml.property name="commands" */ public void addCommands(Command command) { this.commands.add(command); }} Task 3 – Create digester rules digester-catalog-rules.xml <?xml version="1.0"?> <!DOCTYPE digester-rules PUBLIC "-//Apache Commons //DTD digester-rules XML V1.0//EN" "http://commons.apache.org/digester/dtds/digester-rules-3.0.dtd"> <digester-rules><pattern value="catalogs/catalog"><object-create-rule classname="Catalog"/><set-properties-rule/><!-- comment :<bean-property-setter-rule pattern="name"/>use as shown above if say <catalog><name>reparam</name> </catalog> instead of <catalog name="reparam"> </catalog>--><!-- Nested Pattern for Characters --><pattern value="chain"><object-create-rule classname="Chain"/><set-properties-rule/><!-- Nested Pattern for Characters --> <pattern value="command"><object-create-rule classname="Command"/><set-properties-rule/><set-next-rule methodname="addCommands" paramtype="Command"/> </pattern> <set-next-rule methodname="addChains" paramtype="Chain"/> </pattern> <set-next-rule methodname="add" paramtype="Catalog"/> </pattern> </digester-rules> Task 4 – Client program to load xml data import java.io.IOException; import java.io.InputStream; import java.net.URL;import org.apache.commons.digester3.Digester; import org.apache.commons.digester3.binder.DigesterLoader; import org.apache.commons.digester3.xmlrules.FromXmlRulesModule; import org.xml.sax.SAXException;import java.util.ArrayList; import java.util.List;public class runProgram {/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Create an instance of the Digester from the XML rule setDigesterLoader digesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() { @Override protected void loadRules() { // TODO Auto-generated method stub loadXMLRules( getClass( ).getResource("/com/tatu/resources/digester-catalog-rules.xml"));} }); Digester digester = digesterLoader.newDigester();List<Catalog> catalogs = new ArrayList<Catalog>();// Push a reference to the plays List on to the Stackdigester.push(catalogs);// Parse the XML documentInputStream input = Digester.class.getClass().getResourceAsStream("/com/tatu/resources/chain-config.xml");try { Object root = digester.parse(input); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); }}}Done. So have loaded the catalogs object with the xml data. Points to be noted from the above solution:object-create-rule creates an object Rest of the rules are straightforward as their name suggests, object-create-rule creates a new instance, set-properties-rule sets the properties of the object from xml attributes like name attribute of catalog element whereas bean-property-setter-rule sets properties of the object from nested xml elements like say <catalog><name>reparam</name> </catalog> instead of <catalog name=’reparam’> </catalog> - set-next-rule: (used for recursion) The set-next-rulerule moves to the next catalog, chain, and command tags. You have also specified the method to call in each case which will add the objects to a collection defined in the parent class, example : <set-next-rule methodname=’addCommands’ paramtype=’Command’/>, here addCommands() method adds a command object to commands collection object defined in parent chain class. You want new custom rules,create your own Rule class deriving from digester Rule class.Any question, put your comments. One more thought, you don’t want all these shit inbetween the xml files and java classes. Guess what, there is a trick to avoid that. But I don’t like this trick unless you are in hurry. But everytime you use shortcut, you have to lose flexibilities. Trick is to use Apache Betwixt. Remember to use Betwixt, you need to use apache digester 2.1. For more go to apache Betwixt site. Use Betwixt BeanWriter to write the java beans to a file and then, use BeanReader to read from that file. Once you get the file generated from BeanWriter, you can change the values abd load it with BeanReader. (Need to configure betwixt mapping omitted here) Happy coding and don’t forget to share! Reference: Using Apache Digester with Example -Make Easy Configuration from our JCG partner Bijay Deo at the My Software Development Blog blog....

Java Memory Profiling Simplified

As a typical Java developer I never monitored the memory usage of my application apart from following typical best practices like closing the connections, streams etc.. Recently we were struck with few issues in our JBoss servers that I had to dig in to the memory management.One of the best thing in java is that the developers are not required to handle the memory allocations when the objects are created. The JVM does that for us. Most of the time we just need the outer layer knowledge of heap memory and garbage collector. I will share some really interesting investigations that I had. I is a huge topic and I am writing from a point of view of a web application developer, what all minimum I thought we should understand about it.The Tools There are number of good tools available to profile the java applications some of them are, 1. Your Kit Java Profiler 2. JProfiler 3. Eclipse MAT 4. Visual VM Out of these Your Kit and JProfilers needs licences and others are free to use products. We are going to use VisualVM. It is a simple yet powerful tool and comes bundled inside the JDK. It has power list of plugins that you can download and use. To start using VisualVM, go to your <JDK_HOME>\bin and run the jvisualvm.exe. I found the below articles it useful to get going. 1.Profiling With VisualVM 2.VisualVM performance tuning tool 3.How to Get VisualVM to Profile JBoss Without Crashing Since we are talking about memory here make sure you install the Visual GC plugin on the VisualVM as told in this article. Setting the stage – JVM Memory Structure The JVM Memory is divided in to 3 parts as shown in the below image. In our applications we are concerned about the Heap Memory. We can input this value to JVM using the parameters, -Xmx<size> – to set the maximum Java heap size -Xms<size> – to set the initial Java heap sizeThe non-Heap memory stores per-class structures such as runtime constant pool, field and method data, and the code for methods and constructors, as well as interned Strings. Here is a nice article with more details on the JVM memory sizes. Read Javin’s article on JVM Heap space here. The one common confusion is about the stack memory and heap memory. This is well explained here.Stack values only exist within the scope of the function they are created in. Once it returns, they are discarded. Java only stores primitives on the stack. This keeps the stack small and helps keeping individual stack frames small, thus allowing more nested calls. Objects are created on the heap, and only references (which in turn are primitives) are passed around on the stack. Now, Lets get real. Given below the image from Visual GC, a plugin inside the VisualVM as told earlier. We see many graphs here a detailed decription of the output is available here.The Game begins – What happens when the application runs When the objects are created, they reside inside the Eden. When the Garbage collector(GC) runs, if the object is dead (means they are no active references) it is flushed out otherwise they are moved to S1(Survivor Space 1) or S2. This is called a GC cycle. Internal GM algorithm decides the frequency of the GC cycle. Eden + S1 + S2 section of Heap memory is called as Young generation. Objects that survives a fixed number of GC cycles are moved in to Old Gen space. Most number of java objects die as infant and never reach Old Gen. This typically includes local variables which are flushed after the methods are executed. The frequency of GC cycles inside the Old Gen is much lesser than Young Gen. Typical examples of Old Gen objects are singletons, cached objects and other application wide used data. When things do not go as per the plan In a typical application there will be less variation inside the Old Gen space. If the Old Gen space grows linearly with time even after the GC cycle that would lead to a OutOfMemoryError. This might be a indication of a memory leak inside the code. However we might need to use a profiler to find out the exact reason for the same. Here is a Dzon article on some of the Causes of Java EE Enterprise Performance Problems. These are the basic building blocks of how JVM memory is organized and reacts when the application is executed. From this point there are lots of topics including tuning the memory parameters and garbage collector. I will add some of the useful resources related to this. 1. Java Performance Tuning, Profiling, and Memory Management 2. InfoQ Presentation : Diagnosing Web Application OutOfMemoryErrors 3. InfoQ Presentation : Everything I Ever Learned about JVM Performance Tuning @twitter 4. InfoQ Presentation : Extreme Performance Java 5. Java theory and practice: Garbage collection and performance Reference: Java Memory Profiling Simplified from our JCG partner Manu PK at the The Object Oriented Life blog....

JBoss AS 7 classloading explained

This is a sample chapter taken from JBoss AS 7 Configuration Deployment and Administration book edited by Francesco Marchioni who is running a JBoss focused portal named mastertheboss.com. As mandated by Java EE specifications, an application server should ideally give its deployed applications the freedom to use whatever utility library and whatever version of it, regardless of the presence of concurrent applications that want to use the same library. This is also known as namespace isolation (Java EE 5 specifications, section EE.8.4). However, loading classes from different namespaces can raises some issues which are not easy to solve: for example, what happens if I pack a newer version of an utility library with my application, while an older version of the same library was loaded by the application server? Or also, how can I use two different versions of the same utility library, simultaneously, within the same instance of the application server? The JBoss AS classloading strategy has changed sensibly through the years: basically, the 4.x releases of the application server used a UnifiedClassLoader, which aimed at reducing communications overhead between running applications, as class data could be shared by reference or simple copies.One of the major outstanding issues not resolved with the UnifiedClassLoader is classloading dependencies. The idea being that if one application (A) uses the classes of another application (B), the system should know to redeploy A when B gets redeployed, otherwise it will be referencing stale classes. There were actually two different attempts to try to make this work, without the user having to configure anything. Neither attempt really worked and both were dropped. Since JBoss AS 5.0 was introduced, a new class loader based on the new Virtual File System (VFS). The VFS was implemented to simplify and unify file handling within the application server. The new class loader, named the VFS class loader, uses VFS to locate JAR and class files. Even though this represented a significant change in how classes are loaded in JBoss AS 5.0, the resulting behavior is much the same as for prior versions of JBoss AS. A common source of errors is including API classes in a deployment that are also provided by the container. This can result in multiple versions of the class being created and the deployment failing to deploy properly. Class loading in AS7 marks a radical departure from previous attempts. Class loading is now based on the JBoss modules project and any application that is deployed is in effect a module. This affirmation raises some questions from a careful reader: which is the module name assigned to a deployed application ? And also, how are dependencies between modules handled by the AS ? Let’s answer each question in a separate section: Getting to know module names Getting to know the module name is not an academic exercise. As a matter of fact, we can establish dependencies between modules, So for many cases, it’s needed to know which is the module name assigned to an application. Therefore, applications that are packaged as top-level archives (such as WAR, JAR, and SAR) are assigned the following module name: deployment.[archive name]For example, a Web application named WebExample1.war will be deployed as module name: deployment.WebExample1.warOn the other hand, on applications that contain nested modules (such as the EAR archive), every single archive will be assigned a module name using this classification: deployment.[ear archive name].[sub deployment archive name]So, the same Web application, if contained in the archive EnterpriseApp.ear, will be deployed with the name: deployment.EnterpriseApp.ear.WebExample1.warFinding the isolation level In the Chapter 2, Configuring the Application Server, we have intentionally deployed an application that used log4j Api, adding the log4j library into the WEB-INF/lib folder. The application was deployed without a hitch, leaving out with the question: why do we need adding libraries that are already included as a module in the application server? (In our case in the modules\org\apache\log4j\main path). The general rule is that on JBoss AS 7, every deployed application module is isolated from other modules; this means that, by default, it does not have visibility on the AS modules, nor the AS modules have visibility on the application. Using the application server modules is, however ,pretty easy and can be summarized in a simple sentence: add a dependency to the required module and the AS will use it. The application server automatically adds dependencies, or they need to be signaled by the user:The core module libraries (namely the Enterprise classes) are qualified as implicit dependencies, so they are automatically added to your application, when the deployer detects their usage The other module libraries need to be explicitly declared by the user in the application’s MANIFEST file or in a custom JBoss’s deployment file named jboss-deployment-structure.xml (more about this file in the Advanced deployment strategies section).Implicit dependencies: Pointing out dependencies for Api that are commonly used by Enterprise application can be tedious. So, as we have anticipated, they are automatically added for you by the application server. Some are added when the application server detects some annotations or configuration files which are typical of that module. For example, adding a beans.xml file triggers the automatic Weld dependency. The following mind map shows a synthetic view of the modules that are implicitly added to your application:The meaning of this image is simple: if your application uses any of the core modules indicated, then you don’t need specifying any dependency, as the application server is able to link the module automatically. Explicit dependencies Modules that are not qualified as implicit dependencies, need to be declared by the user. In our initial example, the log4j library is not mentioned as implicit dependency, so we had to package the log4j JAR along with our application. We can, however, instruct the deployer to use the log4j library, which is bundled in the application server distribution. The simplest and recommended approach to achieve it, is including into the META-INF/MANIFEST.MF the Dependencies: [module] declaration. In our case, to make your application dependent on log4j, just include in your manifest file the following code: Dependencies: org.apache.log4j Please note that the module name does not always matches with the package name of the library. The actual module name is specified in the module.xml file by the name attribute of the module element. Users will typically use the Eclipse (or any other IDE) to update the manifest file, without the need of performing any tedious archive update:You are not limited to a single dependency, as you can add multiple dependencies separated by a comma. For example, in order to add a dependency on both log4j and Apache Velocity Api, you would use the following: Dependencies: org.apache.log4j,org.apache.velocity You can even export the dependencies used by one application module to other applications, by adding the export keyword. For example, in the earlier application, we’re now exporting the dependencies to other modules:Applications that are marked as dependent to the deployment.WebApp.war module will also have access to its dependencies:The export parameter can also be used to export a dependency to all sub-deployments contained in the ear. Consequently, if you export a dependency from the top-level of the ear (or by a jar in the ear/lib directory) then the dependency will be available to all sub-deployment units as well. Within the META-INF/MANIFEST.MF, you can also specify additional commands that can modify the server deployer’s behavior. For example, the optional attribute can be added to specify that the deployment will not fail, if the module is not found at deployment time. Finally, when the services keyword is specified, the deployer will try to load services that are placed within the META-INF/services of the archive. The service Api has become public in Java SE 6. A service can be defined as a set of programming interfaces and classes that provides access to some specific application functionality or feature. A Service Provider Interface (SPI) is the set of public interfaces and abstract classes that a service defines. You can define a service provider, by implementing the service provider API. Usually, you will create a JAR file to hold your provider. To register your provider, you must create a provider configuration file in the JAR file’s META-INF/services directory. When adding the services attribute to your META-INF/MANIFEST.MF, you will be actually able to load the services contained in the META-INF/services directory. One excellent introduction to the SPI Api is available at: http://java.sun.com/developer/technicalArticles/javase/extensible. Setting up global modules This option resembles a bit to the old AS approach for loading common libraries, where you used to place them in the folder JBOSS_HOME/common/lib. If you define a section named global-modules within your standalone.xml/domain.xml, then you will make the module accessible to other AS modules. For example, instead of declaring a dependency on log4j, you could alternatively use the following section: <subsystem xmlns="urn:jboss:domain:ee:1.0"> <global-modules> <module name="org.apache.log4j" /> </global-modules> </subsystem>Although this approach is not generally recommended, as it brings us back to a concept of monolithic application server, it can still yield some benefits. For example, if you are migrating some older applications, and you don’t want or simply cannot specify dependencies into the archive. Advanced deployment strategies What we have learnt, so far, can be enough for configuring many kind of applications. If you are using a complex archive configuration, such as an EAR archive with several modules and dependencies, it would prove useful to define your classloading strategy in a single file. The configuration file jboss-deployment-structure.xml can do that exactly this. The advantage of using this file are many:You can define the dependencies of all application modules in a single file You can load the modules classes using a finer grained manner, by including/excluding all or part of modules You can define class loading isolation policy for your applications packaged in an Enterprise archiveLet’s see with some practical examples what jboss-deployment-structure.xml can do for you. Setting up a single module dependency We have already learnt how to activate a log4j dependency, using the Dependencies attribute in the archive’s MANIFEST file. The same effect can be achieved by using the jboss-deployment-structure.xml file. Let’s recap the archive structure, which is basically made up of a Web application named WebApp.war. As you can see, the file jboss-deployment-structure.xml needs to be placed within the META-INF folder of the EAR.Here’s its content: <jboss-deployment-structure> <sub-deployment name="WebApp.war"> <dependencies> <module name="org.apache.log4j" /> </dependencies> </sub-deployment> </jboss-deployment-structure>The file jboss-deployment-structure is not for exclusive use of EARs; as a matter of fact, you could deploy it also within the WebApp application, by placing it within the WEB-INF folder of the archive. It is, however, applicable only as top-level archive. Thus if a jboss-deployment-structure.xml is placed in the WAR’s WEB-INF folder and the WAR is packaged in a EAR archive, then the jboss-deployment-structure.xml is ignored. The relevant part of this file is the sub-deployment element, which references the Web application, including within it, the dependencies element. The expected outcome is that the application server will trigger the dependency to log4j Api, which will be therefore visible by our Web application. Excluding the server automatic dependencies Earlier in this chapter, we have shown how the application server is able to trigger some dependencies, automatically, when some conditions are met. For example, if you deploy a JSF application (containing the faces-config.xml file), then the JSF 2.1 Api implementation is automatically added. This might not be always the desired option, for example, because you want to provide another release implementation for that module. You can easily achieve this using the exclusion section in the jboss-deployment-structure.xml, as shown here: <jboss-deployment-structure> <deployment> <exclusions> <module name="javax.faces.api" /> <module name="com.sun.jsf-impl" /> </exclusions> <dependencies> <module name="javax.faces.api" slot="1.2"/> <module name="com.sun.jsf-impl" slot="1.2"/> </dependencies> </deployment> </jboss-deployment-structure>Notice in the dependencies section, we have added our alternate JSF 1.2 implementation, which will be used by your application. Actually this JSF implementation ships with the application server distribution along with the javax.faces.api module path, under the folder specified by the slot attribute. In our case, this corresponds to JBOSS_HOME/modules/javax/faces/api/1.2 folder. Isolating sub deployments Supposing you have an application that is made up of a Web application, an EJB module and a JAR file containing utility classes. All sub deployments are placed at the root of the archive, so that they will be able to see each other. This can be convenient, however, supposing that your Web application contains itself some implementations of the same EJB. That’s absolutely possible since Java EE 6 specification allow your Web application to include EJB classes within the WEB-INF/classes or WEB-INF/lib folder.How does the classloader solves this conflict? The application server classloader has a priority list when loading classes that are used to avoid any conflict between loaded classes.The maximum priority is given to modules, automatically, by the container, including the Java EE APIs. Libraries that are contained in the modules folder are included in this category. Then libraries that are indicated by the user within the MANIFEST.MF of the packaged archive as Dependencies(or in the jboss-deployment-structure.xml file). Next, libraries that are packed within the application itself, such as classes contained in WEB-INF/lib or WEB-INF/classes. Finally, libraries that are packed within the same EAR archive (in the EAR’s lib folder).So, in this example, the EJB libraries located in the WEB-INF folder will “hide” the implementations of EJB.jar top-level deployment. Whether or not this is the desired action from the container, you can still override it: <jboss-deployment-structure> <ear-subdeployments-isolated>false</ear-subdeployments-isolated> <sub-deployment name="WebApp.war"> <dependencies> <module name="deployment.App.ear.EJB.jar" /> </dependencies> </sub-deployment> </jboss-deployment-structure>In this example, we have added a dependency to the EJB.jar, which is placed at the root of the archive, which will override the implementation packed within the Web application. Notice the ear-subdeployments-isolated element placed at the top of the file. By setting the EAR isolation level, you will be able to indicate if the sub-deployments modules are visible to each other. The default value for this attribute is false, meaning that the sub-deployment modules will be able to see each other. If you are setting isolation to true each module will be then picked up by a different classloader, so, in our example, the Web application will not be able to find the classes contained in EJB.jar and Utility.jar library. If you want to keep deployment isolated, but allow visibility for some of them, then you have several choices available:Move the library to the EAR/lib folder, so that it will be picked up as a separate module Specify a dependency using Dependencies or using Class-Path in the MANIFEST.MF file of the calling applicationFrom the following screenshot, you can see how you could correctly set up your EAR, by placing common libraries in the lib folder, and adding a dependency to the EJB classes:And this is the corresponding configuration required in jboss-deployment-structure.xml: <jboss-deployment-structure> <ear-subdeployments-isolated>true</ear-subdeployments-isolated> <sub-deployment name="WebApp.war"> <dependencies> <module name="deployment.App.ear.EJB.jar" /> </dependencies> </sub-deployment> </jboss-deployment-structure>Packaging libraries in a shared library is available, since Java EE 5 is commonly used for holding the JAR files that are used by all modules of the EAR. The default name for the shared library is lib, however you can override it at any time using the library-directory element in the META-INF/application.xml file. For example, supposing you wanted to use the folder common for holding your shared library, then you could add to your application.xml : <library-directory>common</library-directory>As a side note, we suggest you to avoid placing component-declaring annotations (such as EJB3) in the shared folder, as it can have unintended and undesirable consequences on the deployment process. For this reason, we strongly recommend placing just utility classes in the shared library folder. Using Class-Path declaration to solve dependencies: Until now, we have solved dependencies between modules using JBoss’ way, which we obviously suggest as first choice. Nevertheless, we should account also for Java’s portable way to reference one or more library included in the EAR file. This can be done using the Class-Path attribute in the MANIFEST.MF file of a module, which needs to reference another library that could not be otherwise be visible to the application (think to the earlier example, of a deployment unit with isolation set to true). For example, supposing you needed to reference the Utility.jar application from within your Web application, then simply add to your META-INF/MANIFEST.MF the following:Manifest-Version: 1.0 Class-Path: Utility.jarYou can actually include more than one library to the Class-Path, keeping separated them by comma, much the same way you did with the JBoss’ Dependencies attribute. Unlike the Dependencies attribute, the Class-Path attribute points to the actual JAR file name (and not the module name) to reference dependant libraries. Choosing between Class-Path approach and JBoss’ Dependencies approach is a matter of how your application is structured: by using JBoss’ Dependencies buys you a richer set of options, in particular the ability to export the Dependencies to other deployments, as we have shown earlier. One more point in favor of the JBoss’ Dependencies approach, is the ability to reference modules, which are not actually packaged within the application; for example, we have seen how to add a dependency to log4j Api, which are part of the server distribution. On the other hand, the main advantage of the Class-Path approach relies on application portability. Thus, if a full-portable solution is a priority for you, you could consider switching to the Class-Path manifest attribute.This is a sample chapter taken from JBoss AS 7 Configuration Deployment and Administration book edited by Francesco Marchioni who is running a JBoss focused portal named mastertheboss.com. ...

Android dynamic and XML layout

Android activity contains various user interface components e.g Button, Radio button, List, Text field etc. The user interface component can be arranged/attached with the activity in two different ways.Declaring UI element in layoutfile Basically, Layout file is xml formatted file present in res/layout. In this file, tags are used to define any UI component and properties are used to configure the components. It is similar to HTML tags. This style is preferred because UI related codes and business logic codes are separated. It is comparatively easier to manage. Creating view element at runtime UI Companent can be created programmatically. UI component class setter methods help to configure the component. This style is not recommended unless it’s really required. In this style, business logic gets mixed with the component UI code. It doesn’t look neat and sometimes it’s hard to manage.In this tutorial, we will create two different Activity classes with the same UI components but with different techniques. Create an Android project(as shown in this tutorial) and name the Activity as XMLLayoutActivity and layout file as activity_xmllayout.xml. We will define some string constants to be used in layout file and Activity. Open the file string.xml present in res/values and put the following contents: <resources> <string name='app_name'>AndroidLayout</string> <string name='menu_settings'>Settings</string> <string name='title_activity_xmllayout'>XMLLayoutActivity</string> <string name='c4r'>Code4Reference.com</string> <string name='OtherActivity'>Other Activity</string> <string name='dynamic_layout_activity'>Dynamic Layout Activity</string> </resources> Now, we will write very simple layout file which contains Textview, EditText and Button UI components as shown below. <LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' xmlns:tools='http://schemas.android.com/tools' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical'><TextView android:layout_width='match_parent' android:layout_height='wrap_content' android:padding='@dimen/padding_medium' android:text='@string/c4r' tools:context='.XMLLayoutActivity' /> <EditText android:layout_width='match_parent' android:layout_height='wrap_content' android:padding='@dimen/padding_medium' android:hint='@string/c4r' tools:context='.XMLLayoutActivity'/> <Button android:id='@+id/btOtherActivity' android:layout_width='match_parent' android:layout_height='wrap_content' android:padding='@dimen/padding_medium' android:text='@string/OtherActivity' /> </LinearLayout> Let’s define the first activity class called XMLLayoutActivity. This Activity uses the layout file defined above. package com.code4reference.androidlayout;import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;public class XMLLayoutActivity extends Activity {Button btOtherActivity;@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Attaching the layout file with the current Activity. setContentView(R.layout.activity_xmllayout); // Associate the Button object with the Button defined in the layout // file. Notice that R.id.btOtherActivity is associated with the //button in activity_xmllayout.xml layoutfile. btOtherActivity = (Button) findViewById(R.id.btOtherActivity); //Attaching the OnclickListener with the button. btOtherActivity.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { //Creating an Intent which will invoke //the other Activity (DynamicLayoutActivity). Intent intent = new Intent(getApplicationContext(), DynamicLayoutActivity.class); //This method will start the other activity. startActivity(intent); } }); } } Now, add another DynamicLayoutActivity class to the same package which extends Activity class.This activity class will dynamically add the UI component to Activity. Put the following content in the class definition. The embedded comments will help to understand the code. package com.code4reference.androidlayout;import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import android.widget.Toast;public class DynamicLayoutActivity extends Activity {@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // This will create the LinearLayout LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); // Configuring the width and height of the linear layout. LayoutParams llLP = new LayoutParams( //android:layout_width='match_parent' an in xml LinearLayout.LayoutParams.MATCH_PARENT, //android:layout_height='wrap_content' LinearLayout.LayoutParams.MATCH_PARENT); ll.setLayoutParams(llLP);TextView tv = new TextView(this); LayoutParams lp = new LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);tv.setLayoutParams(lp); //android:text='@string/c4r' tv.setText(R.string.c4r); //android:padding='@dimen/padding_medium' tv.setPadding(8, 8, 8, 8); ll.addView(tv); EditText et = new EditText(this); et.setLayoutParams(lp); et.setHint(R.string.c4r); et.setPadding(8, 8, 8, 8); ll.addView(et); Button bt = new Button(this); bt.setText(R.string.OtherActivity); bt.setPadding(8, 8, 8, 8); ll.addView(bt); //Now finally attach the Linear layout to the current Activity. setContentView(ll);//Attach OnClickListener to the button. bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), 'This is dynamic activity', Toast.LENGTH_LONG).show(); } }); } } As you can see, the code doesn’t look that neat compared to the former one. In OnClickListener, Toast class has been used to prompt the message. Now, we need to modify the AndroidManifest file because another activity class has been added. <manifest xmlns:android='http://schemas.android.com/apk/res/android' package='com.code4reference.androidlayout' android:versionCode='1' android:versionName='1.0' > <uses-sdk android:minSdkVersion='8' android:targetSdkVersion='15' /> <application android:icon='@drawable/ic_launcher' android:label='@string/app_name' android:theme='@style/AppTheme' > <activity android:name='.XMLLayoutActivity' android:label='@string/title_activity_xmllayout' > <intent-filter> <action android:name='android.intent.action.MAIN' /> <category android:name='android.intent.category.LAUNCHER' /> </intent-filter> </activity> <activity android:name='.DynamicLayoutActivity' android:label='@string/dynamic_layout_activity'> <intent-filter > <category android:name='android.intent.category.LAUNCHER'/> </intent-filter> </activity> </application> </manifest> Once the coding is done, execute the application and you will notice the following Activity on screen.If you click the button, the next activity will appear having almost similar layout but with different title. If you click the button on the another activity, it will show you a toast message. You can get the source code from github/Code4Reference. You can read more about the android layout here. Reference: Android dynamic and xml layout from our JCG partner Rakesh Cusat at the Code4Reference blog....

Simple REST client in Java

Today most of the mobile applications that used to communicate to some server use REST services. These services are also common practice to use with JavaScript or jQuery. Right now I know 2 ways to create client for REST service in java and in this article I will try to demonstrate both the ways I know hoping that it will help someone in some way. 1. Using Apache HttpClient The Apache HttpClient library simplifies handling HTTP requests. To use this library you have to download the binaries with dependencies from their website. Here is the code for HTTP GET method: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet('http://restUrl'); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); String line = ''; while ((line = rd.readLine()) != null) { System.out.println(line); } } } And for Post method; for sending simple string in post: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost('http://restUrl'); StringEntity input = new StringEntity('product'); post.setEntity(input); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ''; while ((line = rd.readLine()) != null) { System.out.println(line); } } } You can also send full JSON or XML of a POJO by putting String representing JSON or XML as a parameter of StringEntity and then set the input content type. Something like this: StringEntity input = new StringEntity('{\'name1\':\'value1\',\'name2\':\'value2\'}'); //here instead of JSON you can also have XML input.setContentType('application/json'); For JSON you can use JSONObject to create string representation of JSON. JSONObject json = new JSONObject(); json.put('name1', 'value1'); json.put('name2', 'value2'); StringEntity se = new StringEntity( json.toString()); And for sending multiple parameter in post request: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost('http://restUrl'); List nameValuePairs = new ArrayList(1); nameValuePairs.add(new BasicNameValuePair('name', 'value')); //you can as many name value pair as you want in the list. post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ''; while ((line = rd.readLine()) != null) { System.out.println(line); } } }2. Using Jersey Jersey is the reference implementation forJSR-311 specification, the specification of REST support in Java. Jersey contains basically a REST server and a REST client. it provides a library to communicate with the server producing REST services. For http get method: import java.io.IOException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.apache.http.client.ClientProtocolException; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(UriBuilder.fromUri('http://restUrl').build()); // getting XML data System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_JSON).get(String.class)); // getting JSON data System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_XML).get(String.class)); } } There are also other media formats in which you can get the response like PLAIN or HTML. And for HTTP POST method: import java.io.IOException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import org.apache.http.client.ClientProtocolException; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.core.util.MultivaluedMapImpl; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource webResource = client.resource(UriBuilder.fromUri('http://restUrl').build()); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add('name1', 'val1'); formData.add('name2', 'val2'); ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); System.out.println('Response ' + response.getEntity(String.class)); } } If you are using your POJO in the POST then you can do something like following: ClientResponse response = webResource.path('restPath').path('resourcePath'). type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, myPojo); System.out.println('Response ' + response.getEntity(String.class)); Here myPojo is an instance of custom POJO class. You can also use Form class from Jersey to submit multiple parameters in POST request: import java.io.IOException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.apache.http.client.ClientProtocolException; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.representation.Form; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(UriBuilder.fromUri('http://restUrl').build()); Form form = new Form(); form.add('name1', 'value1'); form.add('name2', 'value1'); ClientResponse response = service.path('restPath').path('resourcePath'). type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form); System.out.println('Response ' + response.getEntity(String.class)); } }Happy coding and don’t forget to share! Reference: Simple REST client in java from our JCG partner Harsh Raval at the harryjoy blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: