X

Recent Posts

General

Silicon Valley Code Camp Kids Track 2013

Silicon ValleyCode Camp v8.0 concluded over the weekend. I've attended eachcode camp since the introduction of Java (2007,2008,2009,2010,2011,2012,and now this one). The code camp has stuck to its three coreprinciples from the beginning:By and for the developer community (no product or marketingpitches ;)No charge to attendeesNever occurs during work hoursThe code camp has shown constant growth over its lifespan as isevident by the trends below:The conference is definitely outgrowing its existing venue as theregistrations had to be closed early for the first time. It takes a village to organize a volunteer-driven conference andthat has indeed been the case for all these years. The conferencehas been primarily focused on professional developers for all thepast years. President Obama said "If we want America to lead in the 21st century, nothing is moreimportant than giving everyone the best education possible — fromthe day they start preschool to the day they start their career." So this year, other than my usual speaking engagements, I alsovolunteered to coordinate a new track focused on enabling futuregeneration of developers. It was astounding to see kids fromelementary school, middle school, and early high schoolers learningprogramming skills.This new track had 16 sessions delivered by 8 speakers:Building games inGreenfootTynkerRaspberryGaming 4 KidsTeaching Kids Java ProgrammingScala is Fun: Apps and GamesMinecraftModdingPacman in 60 minutesKojo Programming forKidsInternet Safety for TeensPython Programming for KidsMore details about the track are availablehere. About 200 kids attended stayed with their parents mostof the day and enjoyed interacting with other attendees.Here is some feedback we've heard so far:Thank you very much for the great classes this past Sunday. I had a lot of fun and learnt a lot.  I hope you have more ofsuch classes so I can also have my friends attend with me.Arun - thank you so much for volunteering your time andorganizing such a fantastic event today!! My kids had a blast andquoting my 9-yr old son "Mom, this was the best experience I'veever had" :-) We would be interested in any future events you maybe planning, one time or on-going.Thanks again for the Minecraft Mod workshop yesterday; my sonenjoyed it tremendously and I hope it will encourage him to learnhow to program in coming years.  I also enjoyed it as it gaveme some hints as to how Forge mod loader works.We enjoyed the minecraft modding class yesterday as part of codecamp.  My 11 year old has never coded (beyond Scratch) and hewas up and hacking minecraft within the first hour.  Arun’spreparatory materials, teaching approach and engaging style madethis a great experience.  I would definitely like to see morekid based courses in the future and would definitely recommend theminecraft session to anyone interested in modding.  I’d givethe course 4 out of 5 stars.A friend invited us this morning to SVCC, and although the roomwas packed, my son and I managed to get in and enjoyed learningmore about Java coding.  Thanks for putting this classtogether, and for making opportunities like this for father/sonactivity related to computer literacy.  We had a good time,please keep it up for next year :-)We loved kids sessions in code camp.  It motivated my kidprogramming.  Keep up the good work.My 12 year and 8 years old sons has been coming to code camp forover 4 years now.  It has been fun all these years, howeverthis year in their words "It was the best code camp ever!". Thank you Peter K., Kevin Nilson, Arun Gupta and Stephen Chin andall other volunteers for excellent sessions!"This was fun" says my 11 yr old son Aidan. As the dad, I've beenspending some time with him at home building mods in Java and it'sdefinitely a way to motivate him to learn programming.  He'sbeen able to slog through some rather dry Java materials so thathe can get better at Java programming. Re: the Minecraft class,you did a nice job of teaching theory and then connecting it tosomething applicable.If you attended any of the sessions, we'd love to hear your feedbackat kids@siliconvalley-codecamp.com.Many thanks to co-track lead DaveBriccetti and other speakers: Neil Brown, Stephen Chin, Lynn Langit, SamanthaLangit, Shadaj Laddad, Aditya Gupta, and RonVerghis.Check out some pictures from the event ...And complete album at: The two days were very exhausting, but extremely rewarding andsatisfying!Follow at @arungupta and@devoxx4kidsba(Devoxx 4 Kids Bay Area) for any future updates on similarworkshops!

src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/f3fbf1eee1ca914e445afcd3f8208663/svcc13.png" height="56" width="350">Silicon...

General

JavaOne 2013 Conference Report

18th JavaOne concluded a few days ago!Started with a wet and cold #GeekBikeRide ...... JUG Leaders and Java Champions brunch ....... GlassFish Community Event ...... Strategy and Technical Keynotes ...... Duke Choice Awards ...... GlassFish Party ...... lots of friends from all around the world ... .. several O'Reilly best-seller JavaEE 7 Essentials book signings ... ... lots of Java EE 7 sessions, panels, and EG meetings ... ... couple of sessions on kids and programming ...... Community Keynote ...And who all did I meet ...@myfear, @agoncal, @lincolnthree, @dblevins, @edburns,@fabiovelloso, @emmanuelbernard, @peter_pligrim, @javajuneau,@matthewmccull, @vanriper, @javaclimber, @reginatb38, @stephan007,@danieldeluca, @badrelhouari, @guatejug, @mnriem, @_tamanm,@reza_rahman, @jyeary, @noah_white, @heathervc, @tonyaraemoore,@evanchooly, @maxandersen, @brunoborges, @ingenthr, @javafxpert,@kohsukekawa, @mkheck, @donaldojdk, @venkat_s, @sjmaple,@trisha_gee, @goldstift, @ensode, @delabassee, @johanvos, @atsticks,@pbakker, @sander_mak, @bertertman, @mittie, @adambien,@stuartmarks, @wernerkeil, @yoshioterada, @harshadoak, @hirt,@smeyen, @yarasenger, @vsenger, @brjavaman, @fabianenardon,@maltron, @fguime, @speakjava, @danjavageek, @jj156416,@babadopulos, @chuggid, @webdevwilson, @mike_lehmann, @aa_lopez,@ameliaeiras, @soniazatoreilly, @codename_one, @sharat_chander,@steveonjava, @alexismp, @lightguardjp, @aslakknutsen,@kevin_farnham, @jodastephen, @geertjanw, @acaicedo, @ags313,@eyeseewaters, @briangoetz, @mreinhold, @spericas, @sonyabarry,@terrencebarr, @nivs333, @kittylyst, @robilad, @karianna, @ypoirier,@reza_rahman, @marek_potociar, @shaunsmith, @alexandrajava, @tnis23,@stevengharris, @gsaab, @cpurdy, @alrubinger, @bonbhel, @nilesh_,@anilgaur, @doug_clarke, @sachalabourey, @petrjiricka, @rogerk09,@jitsni, @singh_harpreet, @peppertech, @robc2, @rajivmordani,@vivekpandey, @jclingan, @javaperftuning, @michaelkolling,@cayhorstmann, @aalmiray, @ludoc, @paulsandoz, @bhlynne,@RockCimberT, @frankgreco, @meghanorm, @mullermarian, and manyothers ...Here are the different slide decks and github repos ... Fifty New Features of Java EE 7 in FiftyMinutes from ArunGupta CON 3431 - Introducing Java Programming to Kids from Arun Gupta CON-4456: Coding Java EE 7: Making Easy even Easier (githubrepo)HOL 2147: JavaEE7 Hands-on Lab CON 3496: Come Play! with Java EE 7 (githubrepo)BOF 8012: Teaching Java with Minecraft, Greenfoot, and ScratchWatch the complete photo album: And that's a wrap!

18th JavaOne concluded a few days ago! Started with a wet and cold #GeekBikeRide ... src="" height="216" width="288"> src="" height="288" width="216"> src="" height="216" width="288"> src=""height="21...

General

JavaOne 2013: Java EE 7, GlassFish Community Event, Book Signing, Geek Bike Ride, Hallway Track, ...

18th JavaOne is almost here .... literally a few days away now!5 days8 tracks500+ sessions490+ speakers70+ exhibitorsLots of late night partiesAll in the beautiful city of San FranciscoNow that is what makes a conference lot of fun and bound togive you a nerdgasm!If you are still not convinced, here are 25reasons to attend JavaOne.There is tons ofcoverage on the recently released Java EE 7 and GlassFish 4.The FocusOndocument provide a comprehensive set of sessions, BoFs, hands-onlabs, panels, etc related to Java EE Platform from Oracle, RedHat,IBM, and many others.This is going to be my 15th JavaOne and this blog has been servingreports/pictures from the conference for past 6 years (2007,2008,2009,2010,2011,2012).Here is my schedule so far and I would love to meet you before/aftermy speaking engagements:Saturday, 9/2111amGeekBike Ride7:30pmNetBeans PartySunday, 9/228amJUG Leaders and Java Champions Brunch9:15amGlassFishCommunity Event12pmStrategyand Technical Keynote8pmGlassFishPartyMonday, 9/2312:30pmOTN Lounge Expert Drop-in3pmCON4456:Coding Java EE 7: Making Easy Even Easier (co-speakingwith Lincoln Baxter III)4:15pmJavaEE 7 Essentials Book Signing at JavaOne Book Store6pmJCPParty (including book signing)8pmJUG Leaders and Java Champions Social EventTuesday, 9/2412:15pmPublishers Seminar2pmJavaEE 7 Essentials Book Signing at O'Reilly Booth3pmCON4510:Fifty Features of Java EE 7 in 50 Minutes (co-speakingwith Antonio Goncalves)4:30pmBOF8012: Teaching Java with Minecraft, Greenfoot, and Scratch(co-speaking with Daniel Green)7:30pmHOL2147: Java EE 7 Hands-on Lab (co-speaking with AntonioGoncalves, David Delabassee, and Marian Muller)Wednesday, 9/2510amCON3431:Introduce Java Programming to Kids (co-speaking withJames Weaver)1pmCON3496:Come and Play! with Java EE 7 (co-speaking withAntonio Goncalves)2:30pmJava EE 8 DiscussionsThursday, 9/263:30pmCON2406:Java EE 8 and Beyond (mostly observer)And of course, there is always the hallway track!Where will I see you ?

18th JavaOne is almost here .... literally a few days away now! 5 days 8 tracks 500+ sessions 490+ speakers 70+ exhibitors Lots of late night parties All in the beautiful city of San FranciscoNow...

General

Java EE 7 Launch Celebrations in Africa Trip Report

Morocco, Senegal, South Africa, and Uganda were the African fourcountries on my Makethe Future Java EE 7 Global Celebrations tour. The event wasorganized by JUG AFRICAand Max Bonbhel covered a few other countries as part of this tour.I was welcomed with a very warm African hospitality in each country.The JUG leaders took extreme care of me through out the stay,starting right from the airport pick up, organizing the events,working on logistics, and a multitude of other things. Remember, theJUG leader is a volunteer role but its the passion for technologyand sharing with the community that drives them. And that was trulyevident in each of them!A big shout out to BadrElhouari (Morocco), MamadouNgor Diouf (Senegal), MarkClark and Richard Kolb(South Africa), and NsubugaHassan (Uganda) for being the wonderful hosts!I had lots of opportunities to engage with African developers fromall around the continent. Yes, Africa is a continent with 54different countries! Typically, locals talk about North, East, West,and South Africa regions. I was fortunate to share some of my JavaEE 7 knowledge in all four regions, and in return learned a lot morefrom them.The format at each event was mostly similar - provide a code-drivenintroduction to Java EE 7 and keep it completely interactive. Itruly believe that the code should be written such that it speaksfor itself. The developer productivity enhancements made in the JavaEE platform over the years have certainly made it very much areality. A typical flow covered the following samples, in acompletely interactive manner:WebSocketCollaborative WhiteboardWebSocketChatBatchChunkBatch Split,Flow,and DecisionBatchListenersJAX-RS Endpointand ClientJAX-RS client-sideand server-sidecontent negotiationJTA @Transactionaland @TransactionScopeJerseyServer-Sent EventJSON Streaming Generateand ParseJSON Object Model Generateand ParseManagedExecutor using Concurrency UtilitiesJMSClassic and Simplified Sender/ReceiverJMSDefault Destination FactoryJPASchema Generation PropertiesDefaultData SourceNon-blockingI/O in ServletAsyncServletCDI defaultenabling and @VetoedJSFFaces FlowJSFResource Contracts LibraryJSFPass-through AttributesBeanValidation on POJOsAnd anything else that the developers askedThere was barely noticeable to no language barrier in all thecountries that I visited. This truly allowed a frank and directconversation with the developers, as opposed to using a translator.The trip started with the first event inCasablanca, Morocco (North Africa). Badr took time out ofhis family vacation to receive me at the airport andensuring a smooth operation of the event. There were about50 developers during a week day evening and otherwise ageneral holiday season. The interactive session had several existing Java EE developers.Riding a train from Rabat to Casablanca with a few of the JUGmembers gave a good 1-1 time to interact with them. One of thedevelopers showed me a sample application he has built to preparefor Java certification. One of the common feelings in Morocco atleast is that their sub-Saharan bretherens are preferred for anyAfrica-wide events. However I started my trip with North Africa, sono complaints there ;-)Something to learn about Morocco ...Sahara Desert is about 900 km from Rabat/Casablanca. Plan fora few days if you are interested in a desert safariCars are used to travel from/to airport, not camels ;-)Don't miss out on visiting one of the Kasbah, they are veryunique and colorful structuresHere are some pictures from that event: JMaghreb is the biggestJava developer conference in North Africa. I attended their inaugural conference last year and had a really good timegiving a Java EE 6 hands-on lab to a packed room. The conference isfocused towards a "pragmatic developer", not necessarily using allthe bleeding-edge technologies. Badr has already started planningfor JMaghreb 2.0 (Nov 7 and 8) and planning to expand the outreachto Southern Europe and other neighborhood countries. Reach out tohim if you are interested in speaking at that event, and of course register for this freeconference.The next stop of the trip was at Dakar,Senegal. There were about 30 developers for the Saturdaymorning event. On the request of JUG leader, I started theevent with a slide deck providing a complete overview of theplatform. And then showed a bunch of samples afterwards. TheJava EE 7 TechnicalKit provides a slidedeck (with speaker notes) that you can use to talkabout Java EE 7 at your local JUG. The attendees were notshy in asking questions and the session continued withcode-driven talk afterwards. I was fortunate to bump into couple of passionate GlassFishdevelopers who are using it for a local telecom company. Hear allabout their passion around Java EE 6, GlassFish, and NetBeans:Here are some pictures from that event:Some things to learn about Senegal ...Senegal visa can be obtained at the airport, but be preparedto "grease" the machineryArrange a pick up at the airport otherwise you'll beoverwhelmed with the cabbiesVisit Rebirthof Africa monument in Dakar, it is very very inspiringThe next stop of the trip was atJohannesburg, South Africa. Nobody amongst ~100 developerswanted to see any slides and so we jumped straight into thecode. I showed lots of code and had lots of interaction.I also had the opportunity to visit TheWanderers, a cricket stadium known for the second highest oneday total of 438 by South Africa. I spent significant part of my dayat the office and that's where the event was hosted in the eveningas well.Some things to learn about South Africa ...Johannesburg, with about 4.4 million population, is definitelya premier technology hub in all of AfricaBeing far South, they sort of feel in a silo and notcompletely connected from rest of the world. This is in spite ofthe fact that there is decent Internet connectivity.Startup culture is definitely prominent here - products areserving local needs because of infrastructure costs, otherwiseservices-based Here are some pictures from that event:The last stop of the trip was at Kampala,Uganda. Nsubuga Hassan picked me from the Entebbe airportand we shared a 1.5 hrs taxi ride to the hotel in Kampala.The number of women participants truly surpassed the numberof men at the event, and this was truly impressive. Itsprobably the most number of women I've ever seen at a JUGmeetup.There was even a discussion around starting a new KampalaJUG, so that is definitely promising.The event was hosted by Hivecolabwhich provides community-owned work environment for young techentrepreneurs in Kampala. Had a good chat with program directorBarbara who is also also leading Womenin Technology Uganda. Listen to an interesting conversation with Barbara on promoting technology amongst women inUganda.Some things to learn about Uganda ...English is the official language of the country, and has about40+ other local dialectsPeople are extremely soft-spoken and very welcoming everywhereLot of tech innovation happening in Uganda - Mobile Monday Kampala, @The Hub, Fin Africa, and othersLocal government encourages women to study at the universityI enjoyed riding the different local means of transport - boda boda andthe van. The visit to the local arts and craft market in any part ofworld not only promotes local artisans but also gives you theopportunity to buy authentic goods.Here are some pictures from that event:All the Java EE 7 samples are available at github.com/arun-gupta/javaee7-samples.Feel free to clone the repository or send a pull request if you wantto contribute new Java EE 7 samples. A recording of some of thesamples can be seen in the videos recorded at an earlier conference:Even though the local JUG leaders were my hosts in each country butthe real force behind all of this was Lamine Ba and Max Bonbhel. Ihad numerous emails exchanges on dates, cities, hotels, andeverything else and they were all dealt very promptly and in aprofessional manner. Max and Lamine - you are the agents of changein Africa and are truly helping African developers be visible at theglobal front, thanks for your efforts!I truly enjoyed my short stay in different countries and would loveto come back again!Here is the complete album from the trip: If you want to learn more about African developers, or contributethen there is an excellent panel "BOF3469:Java Trends in Africa" at JavaOne San Francisco (Sep 22-26).Registerand see ya there!

Morocco, Senegal, South Africa, and Uganda were the African four countries on my href="http://www.oracle.com/events/global/en/java-outreach/index.html">Make the Future Java EE 7 Global Celebrations t...

General

Java EE 7 Essentials from O'Reilly: Now Available in Paperback and Ebook

Hot off the press ...Announcing the availability of my new book Java EE 7Essentials.Release Date: TBD, 2013Language: EnglishPages: 362Print ISBN: 978-1-4493-7017-6 | ISBN 10:1-4493-7017-9Ebook ISBN: 978-1-4493-7016-9 | ISBN 10:1-4493-7016-0Chapter 1: Java Platform, Enterprise EditionChapter 2: ServletsChapter 3: JavaServer FacesChapter 4: RESTful Web ServicesChapter 5: SOAP-based Web ServicesChapter 6: JSON ProcessingChapter 7: WebSocketChapter 8: Enterprise JavaBeansChapter 9: Contexts and Dependency InjectionChapter 10: Concurrency UtilitiesChapter 11: Bean ValidationChapter 12: Java TransactionChapter 13: Java PersistenceChapter 14: Java Message ServiceChapter 15: Batch ProcessingChapter 16: Build an End-to-End ApplicationThis book is available from the following websites:O'ReillyMedia (Ebook, Ebook & Print, Print)Amazon(Kindle Edition & Paperback)Barnesand NobleOverstockbuy.comflipkartAnd other usual places.Learn more about the book from JavaSpotlight podcast #143.This book provides a code-intensive overview of the keyspecifications in the Java EE 7 platform (one specification perchapter). The main concepts from the different specifications areexplained using simple code samples. All the associated code isavailable on github. A significant part of this book is derived from my JavaEE 6 Pocket Guide. New chapters have been added to cover allthe new technologies in the platform - WebSocket 1.0, Batch 1.0,JSON-P 1.0, and Concurrency 1.0. New sections have been added orexisting sections updated to reflect the changes in the platform.If you have read the Java EE 6 Pocket Guide, then you can readthis book at a much faster pace; otherwise, you can read this bookfrom beginning to end. Alternatively, you can read specificchapters based upon your interest.The book also contains self-paced instructions on how to build anend-to-end Java EE application using NetBeans IDE.Here is how I can use your help ...Help spread the word about the bookIf you have bought a paperback or kindle edition, postyour review hereIf you have not purchased the book so far, then you can buy itusing any of the usual locations O'Reilly has arranged a book signing at their booth on Tuesday, Sep24, 2pm. Other book signing opportunities are also being worked uponand I'll update once they are confirmed. And the book will also beavailable at JavaOne book store.I hope you enjoy reading the book and learn a few new things fromit. Your feedback in any form is always appreciated!

Hot off the press ... Announcing the availability of my new book href="http://shop.oreilly.com/product/0636920030614.do">Java EE 7 Essentials.Release Date: TBD, 2013Language: EnglishPages: 362Print...

General

BeanManager: Obtain Contextual Reference to Beans (TOTD #215)

javax.enterprise.inject.spi.BeanManager allows toprogrammatically obtain contextual references to beans. Even thoughthe primary purpose is to allow a portable extension to interactdirectly with the container, it can be used by any Java EE componentas well.There are three ways to obtain BeanManager:@Inject BeanManager bm;BeanManager bm = CDI.current().getBeanManager();BeanManager bm = null;try {    InitialContext context = newInitialContext();    bm =(BeanManager)context.lookup("java:comp/BeanManager");} catch (NamingException | NullPointerException ex){   Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE,null, ex);    ex.printStackTrace(out);}The instance is with the scope @Dependent andqualifier @Default. It can be used toprogrammatically obtain the list of beans that are available forinjection such as:Set<Bean<?>> beans =bm.getBeans(Greeting.class);BeanManager has lots of other useful methods to, for example toobtain a contextual reference, an injectable reference, andnon-contextual instance. Go read the javadocs.Check out the complete sample source code at:https://github.com/arun-gupta/javaee7-samples/tree/master/cdi/beanmanagerHow would you use BeanManager in your applications ?

javax.enterprise.inject.spi.BeanManager allows to programmatically obtain contextual references to beans. Even though the primary purpose is to allow a portable extension to interactdirectly with the...

General

JSON Binding with JAX-RS - Moxy, JSON-P, Jackson, Jettison (TOTD #214)

One of the typical questions asked during presentations is how do Ienable JSON support in JAX-RS ?There are three basic approaches and four different modules inJersey that enable them. Here is a quick summary:MOXyJSON-PJacksonJettisonPOJO-based JSON BindingYesNoYesNoJAXB-based JSON BindingYesNoYesYesLow-level JSON parsing & processingNoYesNoYesMOXy is the default and preferred way of supporting JSON binding inyour Jersey applications. A new sample is now added at:https://github.com/arun-gupta/javaee7-samples/tree/master/jaxrs/moxyThe resource definition is:@Path("endpoint")public class MyResource {    @POST   @Produces(MediaType.APPLICATION_JSON)   @Consumes(MediaType.APPLICATION_JSON)    public MyObject echoObject(MyObjectmo) {        return mo;    }}POJO is defined as:public class MyObject {    private String name;    private int age;    public MyObject() {    }    public MyObject(String name, intage) {        this.name =name;        this.age =age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name =name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age =age;    }}Application class is:@ApplicationPath("webresources")public class MyApplication extends Application {}And the client code is:Client client = ClientBuilder.newClient();WebTarget target = client.target("http://"        +request.getServerName()        + ":"        +request.getServerPort()        +request.getContextPath()        +"/webresources/endpoint");System.out.println("POST request");MyObject mo = target        .request()       .post(Entity.entity(new MyObject("Duke", 18),MediaType.APPLICATION_JSON), MyObject.class);out.println("Received response: " + mo.getName() + ", "+ mo.getAge() + "<br><br>");JSON MOXy module (jersey-media-moxy.jar) is in your classpath thenJersey automatically discovers the module and enable JSON bindingsupport via MOXy.jersey.java.net/documentation/latest/media.htmlprovide more details on all the approaches and modules.

One of the typical questions asked during presentations is how do I enable JSON support in JAX-RS ? There are three basic approaches and four different modules inJersey that enable them. Here is a...

General

Java EE 7 Samples Galore

The JavaEE 7 SDK provides a comprehensive set of samples for differenttechnologies - both new and updated. They are very nicelydocumented, runs using Maven + using Cargo, and demonstrate a goodusage of the different APIs.The question I get typically asked is "how do you learn all theseAPIs and technologies ?".The SDK samples, reading specifications, and whitboarding withspecification leads is indeed a big source of my learning. But Ineed to write my own code, simple "hello world" style samples thatdemonstrates point usage of different APIs. I truly believe in "letthe code talk" and have given several slide-free code-driven sessionon Java EE 7 around the world. The source for these talks is about100+ samples I've written over the past few months. All of these samples are now available at: github.com/arun-gupta/javaee7-samplesThey are all Maven-based projects and have no documentation at all.However they are logically arranged by technologies and I've triedto give intuitive names to the directories. I don't intend to writeany documentation so please don't ask for it ;-) But at least nowyou've access to all the samples.Here is the complete list of samples at this time:javaee7-samples  + batch-samples    + batchlet-simple    + chunk-checkpoint    + chunk-exception    + chunk-mapper    + chunk-optional-processor    + chunk-partition    + chunk-simple    + decision    + flow    + batch-listeners    + multiple-steps    + split    + chunk-simple-nobeans  + concurrency-samples    + dynamicproxy    + executor    + schedule    + threads  + ejb-samples    + embeddable    + timer    + lifecycle    + el-samples    + standalone  + javamail-samples    + definition  + jaxrs-samples    + async-client    + async-server    + beanvalidation    + jaxrs-client    + dynamicfilter    + endpoint    + filter    + filter-interceptor    + interceptor    + invocation    + invocation-async    + link    + readerwriter    + readerwriter-json    + server-sent-event    + jsonp    + moxy  + jms-samples    + send-receive-simple    + send-receive    + temp-destination    + jmscontext-cdi  + jpa-samples    + criteria    + entitygraph    + jpa-listeners    + multiple-pu    + schema-gen    + storedprocedure    + jndi-context    + locking-optimistic    + schema-gen-scripts  + jta-samples    + transactional    + transaction-scope    + user-transaction    + tx-exception  + jsf-samples    + contracts    + contracts-library    + flows-simple    + flows-mixed    + flows-programmatic    + flows-declarative    + passthrough    + radio-buttons    + viewscoped    + file-upload    + components    + bean-validation  + json-samples    + object-builder    + object-reader    + streaming-generate    + streaming-parser  + servlet-samples    + nonblocking    + protocol-handler    + servlet-security    + metadata-complete    + validation    + methods  + websocket-samples    + binary    + chat    + encoder    + encoder-client    + encoder-programmatic    + endpoint    + endpoint-async    + endpoint-javatypes    + endpoint-programmatic    + endpoint-programmatic-async    + endpoint-programmatic-injection    + endpoint-security    + httpsession    + injection    + javase-client    + messagesize    + parameters    + properties    + websocket-vs-rest    + subprotocol    + websocket-client    + websocket-client-config    + websocket-client-programmatic    + websocket-client-programmatic-config    + websocket-client-programmatic-encoders    + whiteboardWill continue to add more as I dig into other pieces. I gave a3-hour presentation explaining some of these samples at UberConf andcaptured the screen during the session. Those two-part videos areavailable.The first part covers:WebSocket 1.0Batch 1.0JSON Processing 1.0Java Persistence API 2.1The second part covers:JavaServer Faces 2.2Java API for RESTful Web Services 2.0Java Message Service 2.0Java Transaction API 1.2Bean Vaildation 1.1Concurrency Utilities for Java EE 1.0Enjoy!

The href="http://www.oracle.com/technetwork/java/javaee/downloads/java-ee-sdk-7-jdk-7u21-downloads-1956231.html">Java EE 7 SDK provides a comprehensive set of samples for differenttechnologies -...

General

JMSContext, @JMSDestinationDefintion, DefaultJMSConnectionFactory with simplified JMS API: TOTD #213

"What's New in JMS 2.0" Part1 and Part2 provide comprehensive introduction to new messaging featuresintroduced in JMS 2.0. The biggest improvement in JMS 2.0 isintroduction of the "new simplified API". This was explained in theJava EE 7 Launch TechnicalKeynote. You can watch a complete replayhere.Sending and Receiving a JMS message using JMS 1.1 requires lot ofboilerplate code, primarily because the API was designed 10+ yearsago. Here is a code that shows how to send a message using JMS 1.1API:@Statelesspublic class ClassicMessageSender {@Resource(lookup = "java:comp/DefaultJMSConnectionFactory")ConnectionFactory connectionFactory;@Resource(mappedName = "java:global/jms/myQueue")Queue demoQueue;public void sendMessage(String payload) {  Connection connection = null;    try {      connection =connectionFactory.createConnection();      connection.start();      Session session =connection.createSession(false, Session.AUTO_ACKNOWLEDGE);      MessageProducer messageProducer =session.createProducer(demoQueue);      TextMessage textMessage =session.createTextMessage(payload);      messageProducer.send(textMessage);    } catch (JMSException ex) {      ex.printStackTrace();    } finally {      if (connection != null) {        try {         connection.close();        } catch (JMSExceptionex) {         ex.printStackTrace();        }      }    }  }} There are several issues with this code:A JMS ConnectionFactory needs to be created in a applicationserver-specific way before this application can run.Application-specific destination needs to be created in anapplication server-specific way before this application can run.Several intermediate objects need to be created to honor theJMS 1.1 API, e.g. ConnectionFactory -> Connection ->Session -> MessageProducer -> TextMessage.All APIs throw checked exceptions and so try/catch block mustbe specified.Connection need to be explicitly started and closed, and thatbloats even the finally block.The new JMS 2.0 simplified API code looks like:@Statelesspublic class SimplifiedMessageSender {  @Inject  JMSContext context;   @Resource(mappedName="java:global/jms/myQueue")  Queue myQueue;  public void sendMessage(String message) {   context.createProducer().send(myQueue, message);  }}The code is significantly improved from the previous version in thefollowing ways:The JMSContext interface combines in a singleobject the functionality of both the Connectionand the Session in the earlier JMS APIs.  Youcan obtain a JMSContext object by simply injectingit with the @Inject annotation. This of courseworks only in Java EE Web or EJB applications and does not applyin Java SE-based applications where injection is not available.No need to explicitly specify a ConnectionFactory. A defaultConnectionFactory under the JNDI name ofjava:comp/DefaultJMSConnectionFactoryis used if no explicit ConnectionFactory is specified.The destination can be easily created using newly introduced@JMSDestinationDefinition as:@JMSDestinationDefinition(name = "java:global/jms/myQueue",        interfaceName = "javax.jms.Queue")It can be specified on any Java EE component and the destinationis created during deployment.Creating JMSConsumer also starts the connection so there is noneed to explicitly start it.JMSContext, Session, Connection,JMSProducer and JMSConsumer objectsare now AutoCloseable. This means that theseresources are closed automatically by the management oftry-with-resources statement.New simplified API throws a new unchecked exception,JMSRuntimeException. This means try/catch blocks are notrequired.Method chaining on JMSProducers allows to use builderpatterns.No need to create separate Message object, you can specify themessage body as an argument to the send() method instead.Want to try this code ? Downloadsource code!Download Java EE 7 SDK andinstall.Start GlassFish: bin/asadmin start-domainBuild the WAR (in the unzipped source code directory): mvn packageDeploy the WAR: bin/asadmin deploy<source-code>/jms/target/jms-1.0-SNAPSHOT.warAnd access the application athttp://localhost:8080/jms-1.0-SNAPSHOT/index.jsp to send and receivea message using classic and simplified API.A replay of JMS 2.0 session from Java EE 7 Launch Webinar providescomplete details on what's new in this specification:Enjoy!

"What's New in JMS 2.0" href="http://www.oracle.com/technetwork/articles/java/jms20-1947669.html">Part 1 and href="http://www.oracle.com/technetwork/articles/java/jms2messaging-1954190.html">Part 2 ...

General

Java EE 7 SDK and GlassFish Server Open Source Edition 4.0 Now Available

Java EE 7 (JSR 342)is now final! I've delivered numerous talks on Java EE 7 and related technologiesall around the world for past several months. I'm loaded withexcitement to share that the Java EE 7 platform specification andimplementation is now in the records.The platform has three major themes: Deliver HTML5 Dynamic Scalable Applications Reduce response time with low latency data exchange usingWebSocketSimplify data parsing for portable applications withstandard JSON supportDeliver asynchronous, scalable, high performance RESTfulService Increase Developer ProductivitySimplify application architecture with a cohesive integratedplatform Increase efficiency with reduced boiler-plate code andbroader use of annotations Enhance application portability with standard RESTful webservice client supportMeet the most demanding enterprise requirements Break down batch jobs into manageable chunks foruninterrupted OLTP performance Easily define multithreaded concurrent tasks for improvedscalability Deliver transactional applications with choice andflexibility This "pancake" diagram of the major components helps understand howthe components work with each other to provide a complete,comprehensive, and integrated stack for building your enterprise andweb applications. The newly added components are highlighted in theorange color:In this highly transparentand participatory effort, there were 14 active JSRs:342: Java EE7 Platform338: JavaAPI for RESTful Web Services 2.0339: JavaPersistence API 2.1340: Servlet3.1341:Expression Language 3.0343: JavaMessage Service 2.0344:JavaServer Faces 2.2345:Enteprise JavaBeans 3.2346:Contexts and Dependency Injection 1.1349: BeanValidation 1.1352:Batch Applications for the Java Platform 1.0353:Java API for JSON Processing 1.0356:Java API for WebSocket 1.0236:Concurrency Utilities for Java EE 1.0The newly added components are highlighted in bold. And 9 Maintenance Release JSRs:250: CommonAnnotations 1.2322:Connector Architecture 1.7907: JavaTransaction API 1.2196: JavaAuthentication Services for Provider Interface for Containers115: JavaAuthorization for Contract for Containers919:JavaMail 1.5318:Interceptors 1.2109: WebServices 1.4245:JavaServer Pages 2.3Ready to get rolling ?BinariesJavaEE 7 SDKGlassFishServer Open Source Edition 4.0ToolsNetBeans7.3.1GlassFishTools for Kepler (Technology Preview)MavenCoordinatesDocsJavaEE 7 WhitepaperJava EE 7 Tutorial (htmlpdf)FirstCup Sample ApplicationJava EE 7 Hands-onLabJavadocs (onlinedownload)SpecificationsAll-in-oneGlassFish Documentation BundleA fewarticles have already been published on OTN:What'snew in JMS 2.0: Part 2 (Jun 2013)What'snew in JMS 2.0: Part 1 (May 2013)JavaEE 7 and JAX-RS 2.0 (Apr 2013)JSR356, Java API for WebSocket (Apr 2013)Tenways in which JMS 2.0 means writing less code (Apr 2013)HigherProductivity and Embracing HTML5 with Java EE 7 (Feb 2013)And more are coming! This blog hasalso published several TOTD on Java EE 7:TOTD#212:WebSocket Client and Server EndpointTOTD#211:Chunked Step using Batch ApplicationsTOTD#210:Consuming and Producing JSON using JAX-RS EntityProvidersTOTD#203:Concurrency Managed ObjectsTOTD#202:Resource Library Contracts in JSF 2.2TOTD#199:Java EE 7 and NetBeans IDETOTD#198:JSF 2.2 Faces FlowTOTD#196:Default DataSource in Java EE 7TOTD#194:JAX-RS Client API and GlassFish 4TOTD#192:Batch Applications in Java EE 7TOTD#191:Simple JMS 2.0 SampleTOTD#189:Collaborative Whiteboard using WebSocket in GlassFish 4TOTD#188:Non-blocking I/O using Servlet 3.1All the JSRs have been covered in the JavaSpotlight podcast:#136:Paul Parkinson on JSR 907/JTA 1.2#135:Marina Vatkina on JSR 318/Interceptors 1.2#134:Kin-man Chung on JSR 341/Expresion Language 3.0#133:Sivakumar Thyagarajan on JSR 322/Connectors 1.7#132:Shing-Wai Chan on JSR 340/Servlet 3.1#131:Nigel Deaking on JSR 343/JMS 2.0#130:Santiago Pericas-Geertsen on JSR 339/JAX-RS 2.0#129:Anthony Lai on JSR 236/Concurrency Utilities for Java EE 1.0#126:Jitendra Kotamraju on JSR 353/JSON 1.0#124:Chris Vignola from JSR 352/Batch 1.0#119:Emmanuel Bernard on JSR 349/Bean Validation 1.1#117:Danny Coward on JSR 356/WebSocket 1.0#115:Ed Burns on JSF 344/JSF 2.2#109:Pete Muir on JSR 346/CDI 1.1#90:Marina Vatkina on JSR 345/EJB 3.2#84:Anil Gaur on JSR 342/Java EE 7The latest issue of JavaMagazine is also loaded with tons of Java EE 7 content:Media coverage has started showing as well ...OfficialOracle PRJaxEnter.comInfoQAnd you can track lotmore here.You can hear the latest and greatest on Java EE 7 by watchingreplays from the launchwebinar:This webinar consists of:Strategy KeynoteTechnical Keynote16 Technical Breakouts with JSR Specification LeadsCustomer, partner, and community testimonialsAnd much moreDo you feel enabled and empowered to start building Java EE 7applications ? Just download Java EE 7 SDKthat contains GlassFishServer Open Source Edition 4.0, tutorial, samples,documentation and much more.Enjoy!

Java EE 7 (JSR 342) is now final! I've delivered numerous talks on Java EE 7 and related technologies all around the world for past several months. I'm loaded withexcitement to share that the Java EE...

General

Java EE 7 Launch Webcast: Jun 12th, Register Now

The JavaEE 7 Platform JSR was approved a few days ago and is ready tobe released ...ta da!Want to learn the latest and the greatest improvements in theplatform from the best ?Mark the date for webinars in two different time zones:Jun 12, 2013, 9am PTJun 12, 2013, 9pm PTRegisternow!What will you see in this online event ?Business Keynote (Hasan Rizvi and Cameron Purdy)Technical Keynote (Linda DeMichiel)Breakout Sessions on different JSRs by specification leadsLive ChatLots of DemosCommunity, Partner, and Customer video testimonialsFeel free to use any of the following images to promote the launchwebcast on your blog, website, social media, or elsewhere. You canalso copy/paste the code fragment shown next to them: <ahref="https://event.on24.com/eventRegistration/EventLobbyServlet?target=registration.jsp&eventid=615713&sessionid=1&key=453EBA948F6408FE613E61903CBAEBFA&partnerref=Java_EE7_Launch_glassfishblogs_06122013&sourcepage=register"><imgalt=""src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/cf19b49919064f53204de32f364deb18/javaee7_launch_jun12_185x225.png"border="0" height="225" width="185"></a><ahref="https://event.on24.com/eventRegistration/EventLobbyServlet?target=registration.jsp&eventid=615713&sessionid=1&key=453EBA948F6408FE613E61903CBAEBFA&partnerref=Java_EE7_Launch_glassfishblogs_06122013&sourcepage=register"><imgalt=""src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/4409794e0d78d224d4d9b44ec65b79cc/javaee7_launch_jun12_403x403.png"border="0" height="403" width="403"></a>Don't forget to register!Get ready to drink from the fire hose, no throttle!

The href="https://blogs.oracle.com/theaquarium/entry/java_ee_7_platform_completes">Java EE 7 Platform JSR was approved a few days ago and is ready to be released ...ta da!Want to learn the latest...

General

Suggestions for Java EE and Cloud Track at JavaOne 2013: CFP ends Apr 23

JavaOne Callfor Papers has been extendedand now will close on April 23. There are eight tracks to submityour talks:Client and Embedded Development with JavaFXCore Java PlatformEdge Computing with Java in Embedded, Smart Card, and IoTapplicationsEmerging Languages and the Java Virtual MachineSecuring JavaJava Development Tools and TechniquesJava EE Web Profile and Platform TechnologiesJava Web Services and the CloudA complete description of each track is providedhere. Five different kind of sessions can be submitted foreach track:Conference Session: A 60-minute session presented byOracle, customers, partners, developers, and/or user groupmembersPanel: A 60-minute session presented in a panel formatby multiple speakers consisting of Oracle, customers, partners,developers, and/or user group membersTutorials: A 2 hour speaker led session where thepresenter literally show attendees a live "How to" tutorial, andattendees can ask questions to the presenter during this. Itdoesn't require the attendee to have any equipment whatsoever.Ideally, the attendee should be listening and taking notes.Birds of a Feather (BOFs): A  60-minute sessionthat allows a closer interaction with the speakers and attendeesfocusing on a particular aspect of technology.Hands-on Lab (HOL): A two-hour hands-on, interactivelab sessionWe've seen a good response to paper submission so far and reallythankful for that! You've a few more days to submit your talks. As a track co-lead forJava EE and Cloud tracks, here are some talks that I'd like to seethere:Anything related to WebSocket, JSON, Concurrency, Batch,HTML5, Persistence, Dependency Injection, Transactions ?Do you have a creative use of Java EE technologies in yourapplications ?Are you an extreme believer in Java EE and use most of thecomponents for creating world-class applications ?Are you using multiple application servers in your deploymentenvironment ? Do you have any experience of migrating from earlier versionsof J2EE to Java EE ? Tutorials here would be nice.Do you want to show value of standards-based applicationdevelopment over proprietary frameworks ?Are you building support for Java EE 7 in your applicationsalready ?Performance, monitoring, testing, development, deploymentstrategies ?Any other enterprise Java technologies from the ecosystem ?Real case studies on how Java EE helped you deliver on time,within budget, and stay competitiveAnd now some suggestions for the Cloud track:How are your Java services powering web and cloud ?Anything related to REST/SOAP Web services and design patterns?How is Service Oriented Architecture (SOA) helping you realizethe benefits ? Do you have an interesting deployment topology across yourprivate and public cloud ?Do you have a case study showing why a particular deploymentscenario works ? Are you exposing services at IaaS, PaaS, and SaaS layers andshare guidelines on them ?How are you simplifying DevOps ?How are you using BigData in development and deployment ?Anything related to NoSQL ? Using a mix of NoSQL and RDBMS ?Keep the job of ContentReview Committe interesting, demanding, and challenging.Submit as many sessions as you can before April 23rd 11:50pm PT.Read the contentreview process and tips for submission from 2 years ago toimprove your chances of getting a paper selected.Submitnow!

src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/daab201df627805c1a24e4e50cefcd65/javaone_logo.png"height="189"...

General

WebSocket Client and Server Endpoint: Annotated and Programmatic (TOTD #212)

JSR 356 definesJava API for WebSocket 1.0. It defines a standard-based programmingmodel for creating WebSocket client and server endpoint. Both kindof endpoints can be created programmatically or using annotations.This Tip Of The Day (TOTD) provideshort snippets of how to write a WebSocket client and serverendpoint programmatically or using annotations.The complete source code in this sample can be downloaded fromhere.Lets start with annotation-based server endpoint.@ServerEndpoint("/websocket")public class MyEndpoint {      @OnMessage  public String echoText(String name) {    return name;  }}@ServerEndpoint marks the POJO as a WebSocket serverendpoint. URI of the deployed endpoint is as valueattribute of the annotation.  echoText method isinvoked whenever a message with text payload is received by thisendpoint. Payload of the message is mapped to the parameter name.A synchronous response is returned to the client using the returnvalue.Programmatic server endpoint can be defined as:public class MyEndpoint extends Endpoint {  @Override  public void onOpen(final Session session,EndpointConfig ec) {    session.addMessageHandler(newMessageHandler.Whole<String>() {      @Override      public voidonMessage(String text) {        try {         session.getBasicRemote().sendText(text);        } catch(IOException ex) {         Logger.getLogger(MyEndpoint.class.getName()).log(Level.SEVERE,null, ex);        }      }  });}A programmatic server endpoint is defined by extending Endpointabstract class. onOpen method is overridden to benotified of when a new conversation has started. Sessioncaptures the other end of the conversation. EndpointConfigidentifies the configuration object used to configure this endpoint.Multiple MessageHandlers are registered to handletext, binary, and pong messages. The first parameter of onOpencaptures the other end of the conversation. A synchronous responseto the client is sent by calling getBasicRemote().sendText(...)method.Programmatic server endpoint needs to be configured using ServerApplicationConfig.public class MyApplicationConfig implementsServerApplicationConfig {  @Override  public Set<ServerEndpointConfig>getEndpointConfigs(Set<Class<? extends Endpoint>> set){    return newHashSet<ServerEndpointConfig>() {      {       add(ServerEndpointConfig.Builder           .create(MyEndpoint.class, "/websocket")           .build());      }    };  }  @Override  public Set<Class<?>>getAnnotatedEndpointClasses(Set<Class<?>> set) {    return Collections.emptySet();  }}WebSocket runtime scans the WAR file with all implementations of ServerApplicationConfigand registers the endpoint returned from getEndpointConfigsand getAnnotatedEndpointClasses. The URI of the serverendpoint is published using ServerEndpointConfig.Builder.Now lets take a look at annotated client endpoint.@ClientEndpointpublic class MyClient {  @OnOpen  public void onOpen(Session session) {    try {      String name = "Duke";     System.out.println("Sending message to endpoint: " + name);     session.getBasicRemote().sendText(name);    } catch (IOException ex) {     Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null,ex);    }  }}@ClientEndpoint marks the POJO as a WebSocket clientendpoint. onOpen method is invoked whenever a newWebSocket connection is opened and is identified by @OnOpenannotation. Session captures the other end of theconversation. A synchronous message is sent to the server using session.getBasicRemote.sendText()method.This client can connect to the endpoint as:WebSocketContainer container =ContainerProvider.getWebSocketContainer();String uri = "ws://localhost:8080" +request.getContextPath() + "/websocket";container.connectToServer(MyClient.class,URI.create(uri));And finally programmatic client endpoint.public class MyClient extends Endpoint {  @Override  public void onOpen(final Session session,EndpointConfig ec) {    session.addMessageHandler(newMessageHandler.Whole<String>() {      @Override      public voidonMessage(String text) {       System.out.println("Received response in client from endpoint: " +text);      }  });  try {    String name = "Duke";     System.out.println("Sending message from client -> endpoint: "+ name);     session.getBasicRemote().sendText(name);    } catch (IOException ex) {     Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null,ex);    }  }}The first parameter of onOpen captures the other endof the conversation.  EndpointConfig identifiesthe configuration object used to configure this endpoint. Multiple MessageHandlersare registered to handle text, binary, and pong messages. onMessagemethod is called whenever a message is received from the endpoint. Asynchronous request to the server is sent by calling getBasicRemote().sendText(...)method.This client can connect to the endpoint as:WebSocketContainer container =ContainerProvider.getWebSocketContainer();String uri = "ws://localhost:8080" +request.getContextPath() + "/websocket";container.connectToServer(MyClient.class,                null,               URI.create(uri));Now go download your GlassFishb82, samplessource code, and run them.

JSR 356 defines Java API for WebSocket 1.0. It defines a standard-based programming model for creating WebSocket client and server endpoint. Both kindof endpoints can be created programmatically or...

General

Introducing Kids to Java Programming Using Minecraft

Minecraftis a wildly popular game among elementary and middleschoolers. The game allows players to build constructions oftextured cubes in a 3D world. My son has been playing the game for about a year, lets say addictedto it. Last Fall he told me that the game is corrupted because theJAR file snapshot has messed up the configuration. And that rightaway rang a bell in me as a Java Evangelist at Oracle. I learned from him that the game is written in Java, has a trialversion that runs as an applet in the browser, and downloaded as aJAR file for desktop. The game is modular where the players travelthrough a world and chunks are loaded and unloaded to keep thememory footprint small. Something unique about the game is theability to modify the game from what it was originally designed for.In Minecraft language, this is called as a "mod" - short formodifications. For example, a mod can add new characters to thegame, change look-and-feel of the play field, or make it easy tobuild new structures.The game has a server and a client component. This allows the gameto be played in a single player mode where a player connects to aserver using a client and plays the game. Alternatively multipleplayers, using different clients across platforms, can connect to aserver and play with each other collaboratively. Its very common tohave a server run with multiple mods. There are almost an infinitenumber of mods someone could do to make Minecraft a more amusinggame to play. There is no official API to create these mods butthere are several third-party vendors that provide that capability;Bukkit is one such API. The abilityto write mods and alter the game play gives players more controlover the game and gets them more excited.My son expressed his desire to write a mod and so we startedexploring further. Then onwards, he started teaching me Minecraftvocabulary and I taught him the Java programming concepts. Ourdiscussions in the car, on the dinner table, during the breakfastpreparation, and elsewhere changed to reflect that as well. Healready played with Scratchand Greenfoot lastSummer and that was extremely helpful during this learning curve. Weset up a goal to build a mod during Christmas break. Afterunderstanding the basic concepts and building a few mods, we decidedto share the knowledge with a broader set of Minecrafters. Andthat's where the concept of doing a Minecraft Workshop was born.My son came up with a list of his minecraft buddies and we announceda date for the workshop. Everybody invited for the workshopconfirmed their presence right away. I found out that both theinvited kids and their parents were equally excited. One friendcould not attend because of a prior commitment and was extremelydisappointed. On the day of the workshop, some kids were eager tocome even before the formal start of the workshop.The workshop was attended by 10 kids with age ranging from 10-14years. Most of the kids had no programming experience, let aloneJava. However there was high Minecraft experience in the group withsome kids playing for about 2 years and up to 2 hours every day.When given the topic of Minecraft, the small group would talkexcitedly about different aspects of the game, constantly usinghundreds of game-specific terms and phrases as if speaking adifferent language. My goal was to leverage their passion andintroduce them to Java programming. The challenge for me was to introduce programming to these kidsusing analogies from the daily life. Using a car, features,capabilities, types, and car dealers and correlating with class,properties, methods, instances, and packages seem to work. Fruitsand different methods of peeling, eating, and planting was used tointroduce the concept of Interface in Java. I asked, “What can youdo with a watermelon?” the first answer was obvious, “you can eatit.” The second one was a little less so, “You can chuck in a trashcan.” The response was greeted with scattered laughter. I used thatto explain the concept of Exceptions in Java. Short anecdotes and side-conversations keptthe livelihood of the group going throughout the five hourprogramming session. There are almost an infinite number ofmods someone could do to make Minecraft a more amusing gameto play. But all these mods hold the same basic frameworkthat we set up for any future work on making game-specificmods. By the end of the session, we had worked out an entireframework for making a mod. A Mavenarchetype to create a template Bukkit pluginallowed the attendees to avoid writing boilerplate code. Alower bar to get started and simplicity was the key for thisaudience. The mod built in the workshop added a newserver-side command and printed a trivial message.Although the goal of the workshop was to get an introductionon programming and make a Minecraft mod, I believe theattendees learned much more than that. I think the informalset up helped them discover that programming can be fun anduseful to add to gaming experience. Programming is a vastfield and we barely scratched the surface. But mostimportantly, the attendees had a good time and learned theirfirst lesson of Java programming to start off an interest init. "Fun", "Easy", "Quick", "Awesome", "Short", and "Intuitive"described attendees' one word summary of building and running theirfirst Hello World application using NetBeans.All the instructions followed in the workshop, including a lot morepictures, are available at java4kids.java.net/minecraft-workshop.For me, it was quite a humbling and learning experience. I'vedelivered multiple workshops all around the world but mostly toprofessional developers. I realized how the instructions need to becompletely spelled out in order for the attendees of this age tomake progress. Something as simple as "Hit Enter after entering thecommand", yes, that is required. Anyway I plan this to be the firstof many more workshops aimed to introduce the world of Javaprogramming to school students.One of the lessons learned during the workshop was to simplify theinstallation experience. All the kids had JDK and NetBeans set upalready, pretty straight forward. However I wonder why Maven insistson JAVA_HOME variable instead of figuring it out. I need toinvestigate how to seamlessly install JDK, NetBeans, and Maven in aplatform independent way. This will allow to focus more on buildingthe actual mod rather than the multi-step installations.This workshop was not possible without mentoring support from AllenDutra and other parents. A huge shout out to my family who helpedvalidate and calibrate my strategy for the audience. My nephewsfeedback from the lab is incorporated into this blog. Thanks toOracle for sponsoring the snacks!Thank you @notch for usingJava to build the game! You've provided a great platform for youngkids to learn Java and truly enabled Make The Future Java ...

src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/521551845495b02e1f67caac13d21911/minecraft_logo.png"height="54"...

General

Chunked Step using Batch Applications in Java EE 7: Getting Started with GlassFish 4 (TOTD #211)

TOTD#192 explained the key concepts of JSR 352. This TipOf The Day provides a working example of ahow to write a simple chunk step using JSR 352 ReferenceImplementation integrated in GlassFish4.The source code for this sample application can be downloadedfrom here and works on GlassFish4 b78.As explained in TOTD#192, JSR 352 defines item-oriented processing using chunkstep and task-oriented processing using batchlet step. Achunk consists of a reader that reads one item at a time, aprocessor that processes one item at a time, and a writerthat aggregates 'chunk' number of items and then writes them out.Here is an implementation of reader:@Namedpublic class MyItemReader extendsAbstractItemReader<MyInputRecord> {        private final StringTokenizertokens;        public MyItemReader() {        tokens = newStringTokenizer("1,2,3,4,5,6,7,8,9,10", ",");    }        @Override    public MyInputRecord readItem() {        if(tokens.hasMoreTokens()) {           return new MyInputRecord(Integer.valueOf(tokens.nextToken()));        }        return null;    }}Reader uses type information to specify the type of record that itis working on, MyInputRecord in this case. The readItemmethod returns null to indicate the end of items thatcan be read. In this case, a StringTokenizer is usedto read the items but you can use an InputStream hereif you like.Here is an implementation of processor:@Namedpublic class MyItemProcessor implementsItemProcessor<MyInputRecord,MyOutputRecord> {    @Override    public MyOutputRecordprocessItem(MyInputRecord t) {       System.out.println("processItem: " + t);                return(t.getId() % 2 == 0) ? null : new MyOutputRecord(t.getId() * 2);    }}Processor uses type information to specify the type of input andoutput records its working on, MyInputRecord is theinput record and MyOutputRecord is the output recordin this case. The processItem method reads the inputrecord and accepts only odd-numbered records. This is where yourbusiness logic would be implemented.And here is an implementation of writer:@Namedpublic class MyItemWriter extendsAbstractItemWriter<MyOutputRecord> {    @Override    public voidwriteItems(List<MyOutputRecord> list) {       System.out.println("writeItems: " + list);    }}Writer uses type information as well to specify the type of outputrecord, MyOutputRecord in this case. All theseelements are tied together using "Job XML" as shown:<job id="myJob" xmlns="http://batch.jsr352/jsl">    <step id="myStep" >        <chunkitem-count="3">           <reader ref="myItemReader"></reader>            <processor ref="myItemProcessor"></processor>           <writer ref="myItemWriter"></writer>        </chunk>        </step></job>Eventually, the references myItemReader, myItemProcessor,and myItemWriter will be resolved using CDI. But fornow, the references can be explicitly resolved using "batch.xml" asshown:<batch-artifacts xmlns="http://jcp.org.batch/jsl">    <ref id="myItemReader"class="org.glassfish.chunk.simple.MyItemReader"/>    <ref id="myItemProcessor"class="org.glassfish.chunk.simple.MyItemProcessor"/>    <ref id="myItemWriter"class="org.glassfish.chunk.simple.MyItemWriter"/></batch-artifacts>Once again, downloaded the source code fromhere and get it running on GlassFish4 b78.Post feedback on public@jbatch.java.netor users@glassfish.java.net.

href="https://blogs.oracle.com/arungupta/entry/batch_applications_in_java_ee">TOTD #192 explained the key concepts of href="http://jcp.org/en/jsr/detail?id=352">JSR 352. This TipOf The Day provides a...

General

Consuming and Producing JSON using JAX-RS Entity Providers and JSR 353 Streaming API (TOTD# 210)

TOTD#193 explained how JAX-RS Entity Providers can be used toprovide mapping between on-the-wire representations and theirassociated Java types. This blog shows how you can use Java API forJSON Processing (JSR 353), already integrated in GlassFish 4promoted builds, to produce and consume JSON payload usingEntity Providers.The source code in this blog can be downloadedhere and runs on GlassFishb76.Lets say your domain object is defined as:public class MyObject {  private String name;  private int age;  //. . .}And your resource endpoint is defined as:@Path("endpoint")public class MyResource {  @POST  @Consumes(MediaType.APPLICATION_JSON)  public MyObject echoObject(MyObject mo) {    return mo;  }} This is just echoing the domain object but I suspect yourdomain logic would be more complex than that ;-)Using JAX-RS Client API, this endpoint can be invoked as:WebTarget target = client.target(".../endpoint");MyObject mo = target              .request()              .post(                Entity.entity(new MyObject("Duke", 18),MediaType.APPLICATION_JSON),                MyObject.class);System.out.println("Received response: " + mo.getName() + ", " +mo.getAge() + "<br><br>");The MessageBodyWriter.writeTo method, that writes MyObjectto the underlying OutputStream, uses Streaming APIfrom JSR 353 and looks like:@Overridepublic void writeTo(MyObject t,                    Class<?> type,                     Type type1,                     Annotation[] antns,                     MediaType mt,                     MultivaluedMap<String, Object> mm,                     OutputStream out)           throws IOException, WebApplicationException {  JsonGeneratorFactory factory =Json.createGeneratorFactory();  JsonGenerator gen = factory.createGenerator(out);  gen.writeStartObject()     .write("name", t.getName())     .write("age", t.getAge())     .writeEnd();  gen.flush();} Similarly MessageBodyReader.readFrom method, thatreads MyObject from the underlying InputStream,uses Streaming API from JSR 353 and looks like:@Overridepublic MyObject readFrom(Class<MyObject> type,                        Type type1,                         Annotation[] antns,                         MediaType mt,                        MultivaluedMap<String, String> mm,                         InputStream in)               throws IOException, WebApplicationException {  MyObject mo = new MyObject();  JsonParser parser = Json.createParser(in);  while (parser.hasNext()) {    switch (parser.next()) {      case KEY_NAME:        String key =parser.getString();        parser.next();        switch (key) {          case "name":           mo.setName(parser.getString());            break;          case "age":           mo.setAge(parser.getIntValue());            break;          default:            break;        }        break;      default:        break;    }  }  return mo;} The code is pretty straight forward and refer to JavaAPI for JSON Processing javadocs if you need help inunderstanding the code.Download the sourcecode and enjoy!

href="https://blogs.oracle.com/arungupta/entry/jax_rs_custom_entity_providers">TOTD #193 explained how JAX-RS Entity Providers can be used toprovide mapping between on-the-wire representations and...

General

Updating to latest WebSocket API - Starting with GlassFish b78 (TOTD #209)

Java API for WebSocket (JSR 356) hasrecently gone through a majorrefactoring. The changes are integratedin Tyrus b12 and now available in GlassFishb78. This Tip Of The Day(TOTD) shows the change log for WebSocket endpoint in CollaborativeWhiteboard Sample (explained in TOTD#189) between GlassFish b76 and b78.First of all, everything stays in javax.websocket.*and javax.websocket.server.* package.There are name changes in annotations, APIs, class renames, and somebehavior change as well. Pavel'sblog provides a comprehensive list of changes and theannotation changes are listed here as well:Name before b78Name after b78@WebSocketEndpoint@ServerEndpoint@WebSocketClient@ClientEndpoint@WebSocketMessage@OnMessage@WebSocketPathParam@PathParam@WebSocketOpen@OnOpen@WebSocketClose@OnClose@WebSocketError@OnErrorHere is the change log for updating Whiteboard.java:--- <html>Whiteboard.java (<b>849f919</b>)</html>+++ <html><b>Current File</b></html>@@ -45,50 +45,48 @@ import java.util.HashSet; import java.util.Set; import javax.websocket.EncodeException;+import javax.websocket.OnClose;+import javax.websocket.OnMessage;+import javax.websocket.OnOpen; import javax.websocket.Session;-import javax.websocket.WebSocketClose;-import javax.websocket.WebSocketMessage;-import javax.websocket.WebSocketOpen;-import javax.websocket.server.WebSocketEndpoint;+import javax.websocket.server.ServerEndpoint; /** * @author Arun Gupta */-@WebSocketEndpoint(value = "/websocket",+@ServerEndpoint(value = "/websocket", encoders = {FigureEncoder.class}, decoders = {FigureDecoder.class}) public class Whiteboard { private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>()); - @WebSocketOpen+ @OnOpen public void onOpen(Session peer) { peers.add(peer); } - @WebSocketClose+ @OnClose public void onClose(Session peer) { peers.remove(peer); } - @WebSocketMessage+ @OnMessage public void boradcastFigure(Figure figure, Session session) throws IOException, EncodeException { System.out.println("boradcastFigure: " + figure); for (Session peer : peers) { if (!peer.equals(session)) {- peer.getRemote().sendObject(figure);+ peer.getBasicRemote().sendObject(figure); } } } - @WebSocketMessage+ @OnMessage public void broadcastSnapshot(ByteBuffer data, Session session) throws IOException { System.out.println("broadcastBinary: " + data); for (Session peer : peers) { if (!peer.equals(session)) {- peer.getRemote().sendBytes(data);+ peer.getBasicRemote().sendBinary(data); } } }The updated source code for the sample is availablehere and runs on GlassFishb78.Hopefully this gives you a good idea on how to migrate yourWebSocket applications from the older to the newer API. The changesare still evolving and the specification(PDF) and javadocs(ZIP) are the definitive source for the latest information. Thecomplete set of latest spec downloads are availablehere.As always, send the spec feedback to users@websocket-spec.java.netand implementation feedback to users@tyrus.java.net.

Java API for WebSocket (href="http://jcp.org/en/jsr/detail?id=356">JSR 356) has recently gone through a href="http://java.net/projects/websocket-spec/lists/jsr356-experts/archive/2013-02/message/58">m...

General

Transparency and Community Participation in Java EE 7

Ever since the launch of Java EE 7 and its component JSRs, Oraclehas been very committed to a high level of transparency for all ofthe JSRs under the Java EE 7 umbrella. We're so excited thatincreased transparency has resulted in more useful feedback that hasimproved the Java EE platform. Let me tell you what we've done, howit's helped, and how you can get involved too.One of the requirements for JCP 2.8 is:When voting to approve a JSR's transition to the next stage, ECmembers are expected to take into consideration the extent towhich the Spec Lead is meeting the transparency requirements.Now that many of these JSRs have gone through the Public ReviewBallot and others are in progress, it is useful to review how theyhave contributed to the transparency process. First of all, all Java EE 7 Expert Groups are operating using thetransparency rules defined JCP 2.8. Thetransparency rule requires:Public can read the names on the Expert GroupExpert Group business is regularly reported on a publiclyreadable aliasMechanism for allow public to provide feedbackSpec lead respond to the posts on the aliasSchedule of JSR is publicly available, current, and updatedregularlyOpen source process for the development of RI and/or TCKPublicly readable and/or writable issue-trackerPublicly accessible document archiveHappy to report that all the JSRs in Java EE 7 have followedthe guidelines mentioned above. Providing a specific example usingJSR 342:JSR 342 hasall the Expert Group member names publicly listedAll technical discussions on the Expert Group are reported onjsr342-experts@javaee-spec.java.net alias and archivedAnybody outside the Expert Group can subscribe to the alias atusers@javaee-spec.java.netand provide feedbackSpec leads regularly read and respond on the aliasSchedule of JSR is publicly reported at javaee-spec.java.netGlassFish is the ReferenceImplementation and is completely built in open source. The promotedbuilds have been available for several months, theschedule is completelytransparent, mavencoordinates are published, and NetBeanstooling is available for some time. All this allowsdevelopers to play with the bleeding edge Java EE 7 technologiesas they are integrated in GlassFish. Publicforum allows the users to communicate specifically aboutthe RI.Publicly readable/writable issue trackerPublicly accessible documentarchiveThe transparency checklist by each JSR is explained in the tablebelow.Many of our spec leads have gone beyond this in their outreach tothe community with blogs, talks, chats, and more. The Java EE 7Expert Group recently concluded a publicsurvey seeking community input to define key areas in theplatform such as which specifications should be included in the WebProfile, should CDI be enabled by default, expanded use of @Stereotype,and expansions of Interceptors to all Java EE components. Over 1100respondents voted, make their voices heard, and help decide thedirection of the platform.The table below provides:Public website for each specification in Java EE 7. All of ourJSRs that are part of the Java EE 7 Platform are being run inthe open, using java.net projects.  These JSRs, and linksto their respective projects are listed on the homepage of the Java EE 7 Platform JSR and in the table below.Each page has publicly viewable Expert Group mailing lists asUsers observer lists. The Users lists receive copies of allexpert group emails, as well as providing users the ability topost feedback and engage in discussions with each other and withexpert group members. All lists have publicly viewable archiveson the java.net project sites. Similarly, all projects have publicly accessible download areas,and JIRA issue trackers where bugs and suggestions for newfeatures can be posted, and which also serve as another means ofdiscussion with EG members. The schedules and interim drafts ofthe specification were posted on the main project page andpublicly visible Downloads area.Transparency Checklist columns shows the status of differentJSRs meeting the transparency requirements of JCP 2.8.Community Participation represents the increase in communityparticipation above and beyond the core Expert Group for eachSpecification. As you can see the participation from thecommunity outside the Expert Group is pretty significant and hasworked really well.To encourage further community participation, different JavaEE 7 Expert Groups defined specific areas to provide feedbackusing Adopt-a-JSR. We sawtremendous success with the effort with several JUGs joining theeffort. The last column lists different JUGs that have adopted aparticular JSR. In several cases, JUGs have adopted multipleJSRs.Specification / JSR TransparencyChecklistCommunityParticipationAdopt-a-JSR ABCDEFGHConcurrency(JSR 236) ✓✓ ✓ ✓ ✓ ✓ ✓ ✓ ~250%JPA(JSR 338)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~250%Chennai JUGHyderabad JUGJAX-RS(JSR 339)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~350%CE JUGIndonesia JUGLJCMadrid JUGMorocco JUGPeru JUGSouJavaServlet(JSR 340)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~350%EL(JSR 341)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~125%Java EE 7(JSR 342)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~600%LJCJMS(JSR 343)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~500%FASO JUGIndonesia JUGLJCPeru JUGJSF2.2 (JSR 344)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~200%CE JUGChennai JUGCologne JUGHyderabad JUGSouJava EJB(JSR 345)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~300%SouJava Campinas JUGCDI(JSR 346)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ Only public forumChennai JUGHyderabad JUGIndonesia JUGLJC BeanValidation (JSR 349)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ Only public forumSouJavaBatch(JSR 352)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~750%Chennai JUGLJC, SouJavaJSON(JSR 353)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~650%CE JUGCongo JUGLJCMbale JUGMorocco JUGPeru JUGSouJavaToronto JUGWebSocket(JSR 356)✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ~400%BeJUGLJCChennai JUGMorocco JUGCEJUGNY SIG The map below shows geographical coordinates for different JUGsparticipating in the Adopt-a-JSR effort for Java EE 7:View Java EE 7 Adopt-a-JSR Mapsin a larger map Specific contributions from Adopt-a-JSR effort:London Java Community (LJC) organized a WebSocketand JSON Hack Day. The event was sold out within 2 hoursand had 17 people on the waiting list. The event started with apresentation on explaining the APIs in Java API for WebSocket(JSR 353) and Java API for JSON Processing (JSR 353). Theattendees designed a Market Ticker application. All the presentationmaterial and source codewas shared publicly. LJC also created projects (cdiex-palindrom-jsfand cdiex-datastore)to test CDI 1.1 specification.Chennai JUG is building a multi-player game that can be playedacross the Internet. The application uses Java API for WebSocket1.0 (JSR 356), Java API for JSON Processing 1.0 (JSR 353), JavaPersistence API 2.1 (JSR 338), JavaServer Faces 2.2 (JSR 344)and Batch Applications for Java Platform (JSR 352) and/orEnterprise JavaBeans 3.2 (JSR 345) and so provide a holisticexperience of building a Java EE 7 application. The energeticJUG meets regularly using G+ hangouts and in the neighborhoodcoffee shops to coordinate. And then they go hacking theapplication on github. There are 5 developers that are regularly contributing to theapplication and the JUG plans to incorporate several othertechnologies as part of an ongoing effort.Morocco JUGwill be presenting on Java EE 7, WebSocket, and JSON at JavaDeveloper Conference, Cairo, Egypt.Cologne JUG had a meetup on about JSF 2.2and another one on CDI 1.1(video).BeJUG has adopted JSR 356 have planned a hackathonon Mar 6th. They plan to build a cross-browser Tic-Tac-Toeapplication using JSR 356. One of the JUG members is on its wayto become a committer in Tyrus- the Reference Implementation for JSR 356.Ceara JUG has planned a set of presentationson Mar 9 by on JAX-RS 2.0 (JSR 339), Java API for JSONProcessing (JSR 353), JavaServer Faces 2.2 (JSR 344), and JavaAPI for WebSocket (JSR 356).San Francisco JUG organized a Java EE 7 andWebSocket session and planning a session on JAX-RS 2.0.SouJava is contributing by adding new features from JSF 2.2 toScrumToys.Several other JUGs are doing an outstanding work and contributingtowards making Java EE 7 as the best release ever. All these effortstruly indicate that Java EE 7 is getting grass roots participationfrom the global community. This truly allows early feedback on thespecification and implementation from the end user and developerswho will eventually use these APIs. Overall this leads to a higherquality deliverables and will hopefully eventually lead to a fasteradoption as well.Even though many of the JSRs have gone through Public Review Ballotand others are in progress, its never too late to contribute. So howdo you contribute ? Just follow this three step process:Join a JUG: If you do not participate in your localJava User Group, then find yourlocal JUG and participate. There are several alreadyactive JUGs around the world. If one does not exist in yourneighborhood, now is your time to shine as a leader and startone.Participate in Adopt-a-JSR: Encourage JUG members toparticipate in the global Adopt-a-JSReffort. Several JUGs are already participating andcontributing very effectively.Share the joy: Pick any of the Java EE7 JSRs that are particularly interesting, download GlassFish4 promoted builds, read javadocs, build a sampleapplication, provide feedback to the Expert Group, and share thejoy!Adopt-a-JSR for Java EE 7: Getting Started provide moredetails on how your JUGs can contribute effectively.Java EE 7 JSRs are truly operating in a fully transparent manner andtook community participation to a new level. We are always ready forfeedback!

Ever since the launch of Java EE 7 and its component JSRs, Oracle has been very committed to a high level of transparency for all of the JSRs under the Java EE 7 umbrella. We're so excited thatincreas...

General

WebSocket Java Client API in GlassFish 4 (TOTD #208)

The WebSocket API byW3C defines an API that enables Web pages to use the WebSocketprotocol for two-way communication with a remote host. Java API forWebSocket (JSR 356)has added an ability to invoke a WebSocket endpoint from a Javaapplication. This Tip Of The Day(TOTD) will explain how you can use that API for invoking aWebSocket endpoint.JSR 356 introduces a class-level annotation @WebSocketClientthat converts a POJO into a WebSocket client. The usual lifecycleannotations such as @WebSocketOpen, @WebSocketClose,@WebSocketError, and @WebSocketMessagecan be specified on methods.@WebSocketClientpublic class MyClientEndpoint { @WebSocketOpen public void onOpen(Session session) { System.out.println("Connected to endpoint: " + session.getRemote()); try { String name = "Duke"; System.out.println("Sending message to endpoint: " + name); session.getRemote().sendString(name); } catch (IOException ex) { Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex); } } @WebSocketMessage public void processMessage(String message) { System.out.println("Received message in client: " + message); Client.messageLatch.countDown(); }}This code sends a message to the connected WebSocket endpoint fromthe onOpen method and prints the message when it comesback. This endpoint is bootstrapped using a separate class:public class Client { final static CountDownLatch messageLatch = new CountDownLatch(1); public static void main(String[] args) { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); String uri = "ws://echo.websocket.org:80/"; System.out.println("Connecting to " + uri); container.connectToServer(MyClientEndpoint.class, URI.create(uri)); messageLatch.await(100, TimeUnit.SECONDS); } catch (DeploymentException | InterruptedException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }}Note that a CountDownLatch is used to ensure thatthere is enough time for the client to connect to the endpoint. Thelatch counts down in MyClientEndpoint.processMessageonce the echo message is received from the endpoint.The source code can be downloadedhere, connects to a remote WebSocket endpoint, and displaysthe output on the console.The Maven dependency for now are specified as:<dependencies> <dependency> <groupId>org.glassfish.tyrus</groupId> <artifactId>tyrus-client</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.glassfish.tyrus</groupId> <artifactId>tyrus-container-grizzly</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>Hopefully these could be specified as javaxdependencies only!The latest specification draft and javadocs can be downloadedhere. Share your feedback at users@websocket-spec.java.net(for the specification) or users@tyrus.java.net(for the implenentation).

The WebSocket API by W3C defines an API that enables Web pages to use the WebSocket protocol for two-way communication with a remote host. Java API for WebSocket (JSR 356)has added an ability to...

General

JsonParser and JsonReader - Streaming and Object Readers in Java API for JSON Processing (TOTD #206)

JsonReader reads a JSON object or array from an inputsource. This provides DOM access to the JSON structure. JsonParser provides forward, ready-only access to JSONdata in a streaming way. The parser can be created from InputStreamand Reader. A sample code looks like:JsonParser jsonParser = Json.createParser(newStringReader(YOUR_STRING_HERE));Here is a table with code fragments for parsing some common JSONusing Object Model and events generated from Streaming API:JSON Object Model API Events from Streaming API { }JsonReader jsonReader =     new JsonReader(new StringReader("{}"));JsonObject json = jsonReader.readObject(); {START_OBJECT }END_OBJECT{  "apple":"red",  "banana":"yellow"}jsonReader =     new JsonReader(new StringReader(...));json = jsonReader.readObject();{START_OBJECT  "apple"KEY_NAME:"red"VALUE_STRING,  "banana"KEY_NAME:"yellow"VALUE_STRING}[  { "apple":"red" },  { "banana":"yellow" }]jsonReader =     new JsonReader(new StringReader(...));JsonArray jsonArr = jsonReader.readArray();[START_ARRAY  {START_OBJECT "apple"KEY_NAME:"red"VALUE_STRING}END_OBJECT,  {START_OBJECT "banana"KEY_NAME:"yellow"VALUE_STRING}END_OBJECT]END_ARRAY{  "title":"The Matrix",  "year":1999,  "cast":[    "Keanu Reaves",    "Laurence Fishburne",    "Carrie-Anne Moss"  ]}jsonReader =     new JsonReader(new StringReader(...));json = jsonReader.readObject();{START_OBJECT  "title"KEY_NAME:"The Matrix"VALUE_STRING,  "year"KEY_NAME:1999VALUE_NUMBER,  "cast"KEY_NAME:[START_ARRAY    "Keanu Reaves"VALUE_STRING,    "Laurence Fishburne"VALUE_STRING,    "Carrie-Anne Moss"VALUE_STRING  ]END_ARRAY}END_OBJECT The source code for this sample can be downloadedhere, try it with GlassFish4 b76 or later.Note, GlassFish b76 has PublicReview version of the APIs. But the APIshave evolved since then and an integration is planned in thenext few days. So if you are using an older build, the sample codemay not work. I'll update the sample code once the bits areintegrated.Here are some more links for you to read further:PublicReview javadocLatestjavadocReference Implemenation: jsonp.java.net

JsonReader reads a JSON object or array from an input source. This provides DOM access to the JSON structure.JsonParser provides forward, ready-only access to JSONdata in a streaming way. The parser...

General

JsonGenerator and JsonObjectBuilder - Streaming and Object API in Java API for JSON Processing (TOTD #205)

Java API for JSON Processing (JSR 353) cleared Public Reviewunanimously and is on its way to to standardization. There isstill Proposed Final Draft and the final vote to come. As per the JavaEE7 schedule, the specification will be final on 4/15/2013.The implementation is already integrated in GlassFish4builds.The API provides an Object Model (like DOM for XML) and StreamingAPI (like StAX for XML) to parse and generate JSON structure. Hereis a table that provide code fragments for generating some commonJSON:JSON Object Model API Streaming API { }JsonObject jsonObject =      new JsonObjectBuilder().build();new JsonWriter(System.out)     .writeObject(jsonObject);JsonGeneratorFactory factory =      Json.createGeneratorFactory();JsonGenerator gen =     factory.createGenerator(System.out);gen.writeStartObject().writeEnd();{  "apple":"red",  "banana":"yellow"}new JsonObjectBuilder()  .add("apple", "red")  .add("banana", "yellow").build();gen.writeStartObject()     .write("apple", "red")     .write("banana","yellow")   .writeEnd();[  { "apple":"red" },  { "banana":"yellow" }]JsonArray jsonArray = newJsonArrayBuilder()  .add(new JsonObjectBuilder()         .add("apple","red"))  .add(new JsonObjectBuilder()         .add("banana","yellow"))  .build();gen.writeStartArray()     .writeStartObject()      .write("apple", "red")     .writeEnd()     .writeStartObject()      .write("banana", "yellow")     .writeEnd().writeEnd();{  "title":"The Matrix",  "year":1999,  "cast":[    "Keanu Reaves",    "Laurence Fishburne",    "Carrie-Anne Moss"  ]}new newJsonObjectBuilder()  .add("title", "The Matrix")  .add("year", 1999)  .add("cast", new JsonArrayBuilder()  .add("Keanu Reaves")  .add("Laurence Fishburne")  .add("Carrie-Anne Moss")).build();gen.writeStartObject()     .write("title", "TheMatrix")     .write("year", 1999)    .writeStartArray("cast")      .write("Keanu Reaves")      .write("Laurence Fishburne")      .write("Carrie-Anne Moss")     .writeEnd()   .writeEnd();The source code for this sample can be downloadedhere, try it with GlassFish4b76 or later.Here are some more links for you to read further:PublicReviewjavadocLatestjavadocReference Implemenation: jsonp.java.net

Java API for JSON Processing (href="http://jcp.org/en/jsr/detail?id=353">JSR 353) href="http://jcp.org/en/jsr/results?id=5413">cleared Public Review unanimously and is on its way to to...

General

@WebSocketClient in GlassFish 4 (TOTD #204)

Tyrus is the ReferenceImplementation for Java API for WebSocket (JSR 356) and is alreadyintegrated in GlassFish4. The implementation is rapidly evolving and and addingsupport for different features already defined in the latestversion of the specification.The latest integration in GlassFish added support for creatingJava-based WebSocket clients.Any POJO can be made a WebSocket client by adding @WebSocketClient.A inbound message is received in a method annotated with @WebSocketMessage.Any method can be designated as lifecycle method by specifying @WebSocketOpen,@WebSocketClose, @WebSocketError. Here isa simple sample:@WebSocketClientpublic class MyClient { @WebSocketOpen public void onOpen(Session session) { System.out.println("Connected to endpoint: " + session.getRemote()); try { session.getRemote().sendString("Duke"); } catch (IOException ex) { Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex); } } @WebSocketMessage public void processMessage(String message, Session session) { System.out.println(getClass().getName() + ": " + message); }}In this code, a message is sent to the connected WebSocket endpointwhenever the connection is initiated. An inbound message (comingfrom the server) is processed using processMessagemethod.The endpoint code is pretty trivial:@WebSocketEndpoint(value="/websocket", configuration=DefaultServerConfiguration.class)public class MyEndpoint { @WebSocketMessage public String sayHello(String name) { System.out.println(getClass().getName() + ": " + name); return "Hello " + name; } }The endpoint has a single method that receives the payload, appendsa string and returns back as the response. Even though server isreturning the response right away, the client views this as twoseparate messages, one outbound and the other one inbound. So anymessage-exchange-pattern such as request/response need to bespecifically built using the application code. The configurationattribute, in this case, is optional and will be fixed in asubsequent release of Tyrus.The client can bootstrap using Java SE or Java EE components as:WebSocketContainer container = ContainerProvider.getWebSocketContainer();String uri = "ws://localhost:8080" + request.getContextPath() + "/websocket";container.connectToServer(MyClient.class, URI.create(uri));The complete source code used in this Tip Of TheDay (TOTD) is availablehere. It will run on the latest checkedout version of GlassFish workspace, not a promoted build yet(bleeding edge eh ;-)Please provide feedback on users@tyrus.java.net.How are you going to use Java-based WebSocket client in yourapplications ?Here are other Java EE 7 entries published on this blog so far:Create ManagedExecutorService,ManagedScheduledExecutorService, ManagedThreadFactory,ContextService in GlassFish 4 build 74 (TOTD#203)Resource Library Contracts in JSF 2.2 (TOTD#202)Java EE 7 Maven Archetype - Available in NetBeans (TOTD#201)Java EE 7 and NetBeans IDE - Early Support Available (TOTD#199)JSF 2.2 FacesFlow - @FlowScoped, #{flowScope}, @FlowDefinition(TOTD#198)Java EE 7 Maven Application (TOTD#197)Default Data Source in Java EE 7: Lesser XML and More Defaults(TOTD#196)JPA 2.1 Implementation - EclipseLink M6 integrated inGlassFish 4 (TOTD#195)JAX-RS Client API and GlassFish 4 - Logging HTTP Messages (TOTD#194)JAX-RS Custom Entity Providers (TOTD#193)Batch Applications in Java EE 7 (TOTD#192)SimpleJMS 2.0 Sample (TOTD#191)What'sNewin Servlet 3.1 ?ConcurrencyUtilitiesfor Java EE (JSR 236)CollaborativeWhiteboard using WebSocket in GlassFish 4 (TOTD#189)Non-blockingI/O using Servlet 3.1 (TOTD#188)What'sNewin EJB 3.2 ?JPA2.1 Schema Generation (TOTD#187)WebSocketApplicationsusing Java (JSR 356)Jersey2 in GlassFish 4 (TOTD#182)WebSocketand Java EE 7 (TOTD#181)JavaAPIfor JSON Processing (JSR 353)JMS2.0Early Draft (JSR 343)

Tyrus is the Reference Implementation for Java API for WebSocket (JSR 356) and is already integrated in href="http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/latest-glassfish.zip">GlassFish 4....

General

Create ManagedExecutorService, ManagedScheduledExecutorService, ManagedThreadFactory, ContextService in GlassFish 4 build 74 (TOTD #203)

Latest GlassFish4 promoted build (74at this time) has the first cut of ConcurrencyUtilities for Java EE (JSR 236)implementation integrated. An earlierblog provided an overview of the specification, lets see whatcan be actually done with this build.This build introduce new commands to create ManagedExecutorService,ManagedScheduledExecutorService, ManagedThreadFactory,and ContextService.A simple command execution as:asadmin create-managed-executor-service concurrent/myExecutorManaged executor service concurrent/myExecutor created successfully.Command create-managed-executor-service executed successfully.creates the configuration for a default ManagedExecutorService.Adding --help shows more details about the command:create-managed-executor-service    [--enabled=true]    [--contextinfo=contextinfo]    [--threadpriority=5]    [--longrunningtasks=false]    [--hungafterseconds=hungafterseconds]    [--corepoolsize=0]    [--maximumpoolsize=2147483647]    [--keepaliveseconds=60]    [--threadlifetimeseconds=0]    [--taskqueuecapacity=2147483647]    [--description=description]    [--property=property]    [--target=target]    jndi_nameThe created executor can then be injected into a Java EE component(say Servlet) as:@Resource(name = "concurrent/myExecutor")ManagedExecutorService executor;or looked up using JNDI as:InitialContext ctx = new InitialContext();ManagedExecutorService executor = (ManagedExecutorService) ctx.lookup("concurrent/myExecutor");A task can be defined as:public class MyRunnableTask implements Runnable { private int id; public MyRunnableTask(int id) { this.id = id; } @Override public void run() { try { System.out.format("%d (runnable): starting", id); System.out.format("%d (runnable): sleeping 2 seconds", id); Thread.sleep(2000); System.out.format("%d (runnable): complete", id); } catch (InterruptedException ex) { Logger.getLogger(TestResourceServlet.class.getName()).log(Level.SEVERE, null, ex); } }}Task can be submitted as:Future<?> f = executor.submit(new MyRunnableTask(1));ORexecutor.execute(new MyRunnableTask(2));A task may also be defined as:public class MyCallableTask implements Callable<Product> { private int id; public MyCallableTask(int id) { this.id = id; } @Override public Product call() { try { System.out.format("%d (callable): starting", id); System.out.format("%d (callable): sleeping 2 seconds", id); Thread.sleep(2000); System.out.format("%d (callable): complete", id); } catch (InterruptedException ex) { Logger.getLogger(TestResourceServlet.class.getName()).log(Level.SEVERE, null, ex); } return new Product(id); }}where Product is a domain-specific class. In thiscase, the task is submited for execution as:Future<Product> f2 = executor.submit(new MyCallableTask(3));A ManagedScheduledExecutorService can be created as:asadmin create-managed-scheduled-executor-service concurrent/myScheduledExecutorManaged scheduled executor service concurrent/myScheduledExecutor created successfully.Command create-managed-scheduled-executor-service executed successfully.A ManagedThreadFactory can be created as:asadmin create-managed-thread-factory concurrent/myThreadFactoryManaged thread factory concurrent/myThreadFactory created successfully.Command create-managed-thread-factory executed successfully.A ContextService can be created as:asadmin create-context-service concurrent/myContextServiceContext service concurrent/myContextService created successfully.Command create-context-service executed successfully.Note, this is the first integration and some of the options may notwork. But you can definitely start playing around with basic stuffnow.The complete source code used in this Tip Of TheDay (TOTD) is availablehere and will run on GlassFish4 b74.

Latest href="http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/latest-glassfish.zip">GlassFish 4 promoted build (href="http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/glassfish-4.0-b74....

General

Resource Library Contracts in JSF2.2 (TOTD #202)

JavaServer Faces 2 introduced Facelets as the default ViewDeclaration Language. Facelets allows to create templates usingXHTML and CSS that can be then used to provide a consistentlook-and-feel across different pages of an application. JSF 2.2defines Resource Library Contracts that allow facelet templates tobe applied to an entire application in a reusable andinterchangeable manner. This Tip Of The Day (TOTD) will explain howyou can leverage them in your web application.The complete source code for this sample can be downloadedhere. This will run on GlassFish build 72 + latestJSF2.2.0 SNAPSHOT copied over"glassfish3/glassfish/modules/javax.faces.jar" file.Consider the following WAR file:index.xhtmluser/index.xhtmlcontracts/blue/layout.csscontracts/blue/template.xhtmlcontracts/redcontracts/red/layout.csscontracts/red/template.xhtmlWEB-INF/faces-config.xmlThe application also has two pages - "index.xhtml" and"user/index.xhtml". All contracts reside in the "contracts"directory of the WAR. All templates and resources for a contract arein their own directory. For example, the structure above has twodefined contracts "blue" and "red". Each contract has a"template.xhtml" and a CSS. Each template is called as "declaredtemplate". The "template.xhtml" has <ui:insert> tags called as"declared insertion points". CSS and other resources bundled in thedirectory are "declared resources". The "declared template","declared insertion points", and "declared resources" together makethe definition of the resource library contract. A template clientneeds to know the value of all three in order to use the contract.In our case, templates have similar "ui:insert" sections andtemplate clients will accordingly have "ui:define" sections. Thedifference will primarily be in the CSS. "index.xhtml" will refer tothe template as:<ui:composition template="/template.xhtml"> <ui:define name="content"> . . . </ui:define></ui:composition>The usage of the contracts is defined in "faces-config.xml" as:<application> <resource-library-contracts> <contract-mapping> <url-pattern>/user/*</url-pattern> <contracts>blue</contracts> </contract-mapping> <contract-mapping> <url-pattern>*</url-pattern> <contracts>red</contracts> </contract-mapping> </resource-library-contracts></application>A contract is applied based upon the URL pattern invoked. Based uponthe configuration specified here, "red" contract will be applied to"faces/index.xhtml" and "red" contract will be applied to"faces/user/index.xhtml". The template of the page can be changed dynamically as well. Forexample consider "index.xhtml" is updated as:<f:view contracts="#{contractsBean.contract}"> <ui:composition template="/template.xhtml"> <ui:define name="content"> <a href="#{facesContext.externalContext.requestContextPath}/faces/user/index.xhtml">Go to</a> other contract <p/> Look at WEB-INF/faces-config.xml for contract configuration. <p/><p/> Choose a template:<br/> <h:form> <h:selectOneRadio value="#{contractsBean.contract}" layout="pageDirection" required="true"> <f:selectItem itemValue="red" itemLabel="red"/> <f:selectItem itemValue="blue" itemLabel="blue"/> </h:selectOneRadio> <h:commandButton value="Apply" action="index" /> </h:form> </ui:define> </ui:composition></f:view>The "ui:composition" is included in "f:view". An additional"contracts" attribute can bind to an EL. The value of this EL ispopulated from the radio button in the newly added form. Now you canchoose a radio button, click on the "Apply" button and the newtemplate will be applied to the page. The bean is very trivial:@Named@SessionScopedpublic class ContractsBean implements Serializable { String contract = "red"; public String getContract() { return contract; } public void setContract(String contract) { this.contract = contract; }}This is a very powerful feature. Imagine providing differentlook-and-feel for your website and letting the user choose them, funeh ?Contracts may be packaged as a JAR file. Such a JAR file maybebundled in "WEB-INF/lib" directory. Read section 2.7 for moredetails about the packaging requirement and a marker file thatidentifies the JAR to contain a contract.In the specification ... Section 10.1.3 provide background on the feature.Section 2.7 provide formal definition of the feature.Section 11.4.2.1 defines how the contracts are identifiedduring application startup.Create templates as JAR files and reuse them across differentapplications, enjoy!

JavaServer Faces 2 introduced Facelets as the default View Declaration Language. Facelets allows to create templates using XHTML and CSS that can be then used to provide a consistentlook-and-feel...

General

Jfokus 2013 Trip Report - A Magnificent Spectacle

This was my third consecutive year (2012,2011)at Jfokus and the organizing committee, and Mattias Karlsson inparticular, continue to amaze me every year! As one of my colleaguementioned, it truly has become a "magnificent spectacle".With the conference sold out 2 weeks before the official start, 1550attendees from 20+ countries were delighted by a barrage ofinternational speakers. This was the biggest Jfokus ever and the barhas always gone higher from the previous years.The conference kickstarted with a guided tour of Old Town Stockholmand was a good way to get familiar with history of the city. The conference had hands-on lab on the first day and technicalsessions, BoFs, HackerGarten,NightHacking, Swedish massage by Mejsla andother activities on day 2 and 3. Even though the conference hadseveral tracks but the best track is always the "hallway track"which gives you the unique opportunity to engage with otherattendees of the conference.Markus and I delivered a lab on "DevelopingJAX-RS Web Applications Utilizing Server-sent Events andWebSockets". Geertjan also showed up at the lab and helped outwith general NetBeans questions. The lab guide is availableand the complete source code can be downloaded here.Note, the lab works on GlassFish4.0 build 57 for now because of the pending bugs in SSEimplementation in Jersey.The last 45 minutes of the lab had a different section covering someother Java EE 7 technologies. The lab guide is available at bit.ly/javaee7-hol (PDF) andthe starting code is available at bit.ly/javaee7-hol-code(ZIP). For now, this particular lab covers:JavaEE 7 Maven CoordinatesDefaultDataSourceJPA2.1 Schema GenerationWebSocket- Endpoint and JavaScript clientJSF2.2 Faces FlowThis lab is a work in progress and a more comprehensive featureset will be integrated and shared at future conferences (yes,several are already planned!). Let me know if you'll be interestedin reviewing the contents and providing feedback. Here are some pics from the lab session:The conference also had its first #GeekRun. 7 of us ran in sub-zerotemperature in the dark around the island and it was a greatexperience!Here is the running route:The evening concluded with an outstanding speakers' dinner at F12. The hospitality of therestaurant, warmth of the Jfokus events team, and company of some ofthe finest geeks in the world made the evening memorable. Some picsfrom the dinner ...I delivered a session on TheJava EE 7 Platform: Productivity++ and Embracing HTML5. Therewere about 100+ attendees for the 9am session. It gave a quickoverview of the features coming in Java EE 7:Java API for WebSocketJava API for JSON ProcessingConcurrency Utilities for Java EEBatch Applications for Java PlatformJAX-RS 2.0JMS 2And several other technologies which are getting an update. Thecomplete slides are available: The session also showed a quick demo of the latest NetBeansbuild supporting JavaEE 7.In Howto participate in the future of Java, I talkd about howseveral JUGs are contributing to Adopt-a-JSR effortsaround Java EE 7. There are 19 JUGs from around the world thatare participating in this effort. What is your JUG waiting for ?Join the momentum now!Here are some more pictures from the conference: The conference collected feedback for each talk using green, red,and yellow cards, a concept firstfound in Oredev. As explained in the opening keynote, the ruleis getting green cards is good, yelllow card means so so and redcard means the speaker is not coming back to the conference. Hereare the cards that I received after my talk on Java EE 7:I've heard the rumor that Nordic conferences don't like to repeatspeakers for more than 2-3 years in a row. This was my third yearbut hey, the cards are all green. I'm keeping my fingers crossed fornext year ;-)Anyway, congratulations once again Mattias and team for a job verywell done!And the complete photo album:

This was my third consecutive year (href="https://blogs.oracle.com/arungupta/entry/jfokus_2012_trip_report">2012,href="https://blogs.oracle.com/arungupta/entry/jfokus_2011_day_3_trip">2011)at Jfokus...

General

Java EE 7 Maven Archetype - Available in NetBeans (TOTD #201)

Want to create a Java EE 7 application using Maven ?mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes-DarchetypeArtifactId=webapp-javaee7-DarchetypeVersion=0.1-SNAPSHOT-DarchetypeRepository=https://nexus.codehaus.org/content/repositories/snapshots/-DgroupId=org.glassfish -DartifactId=javaee7-sample-Dversion=1.0-SNAPSHOT -Dpackage=org.glassfish.javaee7-sample-Darchetype.interactive=false --batch-mode --update-snapshotsarchetype:generate[INFO] Scanning for projects...Downloading:http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xmlDownloading:http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xmlDownloaded:http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml(11 KB at 42.6 KB/sec)Downloaded:http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml(22 KB at 65.6 KB/sec)Downloading:http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xmlDownloaded:http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xml(701 B at 4.3 KB/sec)[INFO]                                                                        [INFO]------------------------------------------------------------------------[INFO] Building Maven Stub Project (No POM) 1[INFO]------------------------------------------------------------------------Downloading:http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xmlDownloading:http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xmlDownloaded:http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml(11 KB at 64.9 KB/sec)Downloaded:http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml(22 KB at 77.8 KB/sec)Downloading:http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xmlDownloaded:http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-archetype-plugin/maven-metadata.xml(701 B at 3.1 KB/sec)[INFO] [INFO] >>> maven-archetype-plugin:2.2:generate(default-cli) @ standalone-pom >>>[INFO] [INFO] <<< maven-archetype-plugin:2.2:generate(default-cli) @ standalone-pom <<<[INFO] [INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @standalone-pom ---[INFO] Generating project in Batch mode[INFO] Archetype defined by propertiesDownloading:https://nexus.codehaus.org/content/repositories/snapshots/org/codehaus/mojo/archetypes/webapp-javaee7/0.1-SNAPSHOT/maven-metadata.xmlDownloaded:https://nexus.codehaus.org/content/repositories/snapshots/org/codehaus/mojo/archetypes/webapp-javaee7/0.1-SNAPSHOT/maven-metadata.xml(786 B at 0.5 KB/sec)Downloading:https://nexus.codehaus.org/content/repositories/snapshots/org/codehaus/mojo/archetypes/webapp-javaee7/0.1-SNAPSHOT/maven-metadata.xmlDownloaded:https://nexus.codehaus.org/content/repositories/snapshots/org/codehaus/mojo/archetypes/webapp-javaee7/0.1-SNAPSHOT/maven-metadata.xml(786 B at 2.0 KB/sec)[INFO]----------------------------------------------------------------------------[INFO] Using following parameters for creating project fromArchetype: webapp-javaee7:0.1-SNAPSHOT[INFO]----------------------------------------------------------------------------[INFO] Parameter: groupId, Value: org.glassfish[INFO] Parameter: artifactId, Value: javaee7-sample[INFO] Parameter: version, Value: 1.0-SNAPSHOT[INFO] Parameter: package, Value: org.glassfish.javaee7-sample[INFO] Parameter: packageInPathFormat, Value:org/glassfish/javaee7-sample[INFO] Parameter: package, Value: org.glassfish.javaee7-sample[INFO] Parameter: version, Value: 1.0-SNAPSHOT[INFO] Parameter: groupId, Value: org.glassfish[INFO] Parameter: artifactId, Value: javaee7-sample[INFO] project created from Archetype in dir:/Users/arungup/code/workspaces/tmp/javaee7-sample[INFO]------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO]------------------------------------------------------------------------[INFO] Total time: 4.703s[INFO] Finished at: Sat Feb 02 07:31:54 EET 2013[INFO] Final Memory: 11M/125M[INFO]------------------------------------------------------------------------That's it!NetBeansDevelopment Builds allows to create a Maven-based Java EE 7web application now. wiki.netbeans.org/JavaEE7provide a complete list of planned features. TOTD#199 provide some more details on the features currentlyworking. Of course, this application will get deployed to GlassFish4.

Want to create a Java EE 7 application using Maven ?mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee7 -DarchetypeVersion=0.1-SNAPSHOT-DarchetypeRepository=https:...

General

Java EE 7 and NetBeans IDE - Early Support Available (TOTD #199)

NetBeans IDE provides the bestout-of-the-box experience for Java EE development, deployment, anddebugging. Earlybuilds of NetBeans have already started providing support forJava EE 7 features such asRegistering GlassFish 4Creating Java EE 7 applicationWizard for JAX-RS 2 Filters/InterceptorsInitial support for Faces FlowLoading templates from a resource libraryNon-persistent EJB timers in Web profileWizard for WebSocket endpointswiki.netbeans.org/JavaEE7provide a complete list of features slated for the release and thebuilds can be downloaded from bertram2.netbeans.org:8080/job/web-main-javaee7.Here are some snapshots of the work completed so far.Creating a Java EE 7 Web application and using GlassFish 4serverCreating a WebSocket endpointWizard for creating WebSocket endpointThe generated code looks like:@WebSocketEndpoint("/endpoint")public class NewWSEndpoint { @WebSocketMessage public String onMessage(String message) { return null; } }Creating a JAX-RS 2 FilterWizard for creating a JAX-RS 2 FilterBy default it is a server-side filter but can be made client-sidefilter too.Wizard for creating a JAX-RS 2 InterceptorCreating a RESTful Java Client using JAX-RS 2 Client APIsWizard for creating a JAX-RS 2 ClientThis is a very early work-in-progress so any feedback is welcome.Download GlassFish4.0 promoted build, register it with NetBeans IDE and take itfor a test drive!

NetBeans IDE provides the best out-of-the-box experience for Java EE development, deployment, and debugging. href="http://bertram2.netbeans.org:8080/job/web-main-javaee7/">Early builds of NetBeans hav...

General

JSF 2.2 Faces Flow - @FlowScoped, #{flowScope}, @FlowDefinition (TOTD #198)

JavaServer Faces 2.2 is more evolutionary than it is revolutionary.This is by design as JSF 2.0 added a whole bunch of new features aspart of the Java EE 6 platform. The Preface 1 from the JSF2.2 Public Review specification provides a list of changesbetween JSF 2.1 and 2.2. There are several changes coming in JSF 2.2but the bigticket items are:Faces FlowResource Library ContractHTML5 Friendly MarkupThis Tip Of The Day (TOTD) willexplain FacesFlow. Section 7.5 and 11.4.3 in the specification introducethe feature.Faces Flow provides an encapsulation of related views/pages with anapplication defined entry and exit points. For example, a check outcart can consist of cart page, credit card details page, shippingaddress page, and confirmation page. All these pages, along withrequired resources and beans, can be packaged together as a modulewhich can then be reused in other applications. Each flow has a well-defined entry and exit point that have beenassigned some application specific meaning by the developer. Usuallythe objects in a faces flow are designed to allow the user toaccomplish a task that requires input over a number of differentviews. In our case, the navigation between pages for selectingitems, entering shipping address, credit card details, andconfirmation page would make a flow. All the pages and objects thatdeal with the checking out process can be composed as modules. Anapplication thus become a collection of flows instead of just views.It takes the best part of other flow-based technologies such as ADFTask Flow, Spring Web Flow, and Apace MyFaces CODI and standardizesin JSF 2.2. What is the need ? Imagine a multi-page shopping cart with one page for selecting theitems, a second page for shipping options, a third page for enteringcredit card details, and a fourth page for final confirmation.Managed Beans can be used to capture the data, session scopevariables pass information between pages, button clicks can be usedto invoke the business logic in backing EJBs, and (conditional)navigation rules can be defined to go from one page to another.There are a few issues with this approach:This flow of sequence will typically be part of a biggerapplication. However an application, typically with severalpages, is one large flow and everything is visible with nological partitioning.The flow of pages or views cannot be encapsulated as a logicalunit and thus cannot be reused, e.g. incorporated into anotherbigger flow easily.The lowest logical granularity is a page. The only way toinvoke application logic is to tie it to a UI componentactivated by the user in a page. Business logic cannot beinvoked without any user initiated action.Same flow cannot be opened in multiple windows because sessionscoped variables are used to pass information between pages. CDIdefines @ConversationScoped but that is only partof the solution.There is no scope defined that can span multiple pages butless than a session.Faces Flow provide a solution to the issues mentioned above.What's new in JSF 2.2 for flows ?The flow of application is no longer restricted to flow betweenpages but instead defined as flow between "nodes". There are fivedifferent types of nodes:View: Any JSF page in the applicationMethod Call: Invoke application logic from flow graph via anELSwitch: Navigation decisions in the flow graph based onboolean ELFlow Call: Call another flow with parameters and receivereturn valuesFlow Return: Return to the calling flowThe nodes define the entry and exit points of a flow.Two new annotations are introduced:@FlowScoped is a CDI scope that defines the scopeof bean in the specified flow. This enables automaticactivation/passivation of the bean when the scope isentered/exited.@FlowDefinition is a class level annotation thatallows the flow definition to be defined using the fluent FlowBuilderAPI.A new EL object, #{flowScope}, for flow local storageis also introduced. This maps to facesContext.getApplication().getFlowHandler().getCurrentFlowScope().How are flows packaged ?Flows can be packaged in JAR files or in directories.JAR packaging requires flows to be explicitly declared in META-INF/faces-config.xmlin the JAR file. Flow nodes are packaged in META-INF/flows/<flowname>where <flowname> is a JAR directory entry whosename is identical to that of a flow id in the corresponding faces-config.xml.@FlowScoped and @FlowDefinition beansmust be packaged in the JAR file and accompanied by META-INF/beans.xml.A sample JAR file looks like:META-INF/faces-config.xmlMETA-INF/flows/flow1/entry.xhtmlMETA-INF/flows/flow1/next.xhtmlMETA-INF/flows/flow1/end.xhtmlMETA-INF/flows/flow2/start.xhtmlMETA-INF/flows/flow2/next.xhtmlMETA-INF/flows/flow2/end.xhtmlMETA-INF/beans.xmlorg/glassfish/sample/MyFlow1Bean.classorg/glassfish/sample/MyFlow2Bean.classorg/glassfish/sample/MyFlowDefintion.classFlows packaged in directories use convention-over-configuration. Theconventions are:Every View Declaration Language file in that directory is aview node of that flow.The start node of the flow is the view whose name is the sameas the name of the flow.Navigation among any of the views in the directory isconsidered to be within the flow.Navigation to a view outside of that directory is consideredto be an exit of the flow.Optional <flowname>-flow.xml thatrepresents the flow definition. The rules in this file overridesthe conventions described above.A sample directory looks like:flow1/flow1.xhtmlflow1/flow1a.xhtmlflow1/flow1b.xhtmlflow2/flow2-flow.xmlflow2/flow2.xhtmlflow2/flow2a.xhtmlflow2/flow2b.xhtmlWEB-INF/... Show me the code!Lets try a sample now!The source code for the two samples explained below can be downloadedhere. A complete explanation of the sample including the codewalk-through is shown in the video:This will run on GlassFish4.0 b72. For now, you'll need to replace glassfish/modules/javax.faces.jarwith javax.faces-2.2.0-SNAPSHOT.jarand replacing glassfish/modules/javax.el.jar with javax-el-3.0-b03.jar.This JARs will soon be integrated in the GlassFish build. Ah, thejoys of bleeding edge development!

JavaServer Faces 2.2 is more evolutionary than it is revolutionary. This is by design as JSF 2.0 added a whole bunch of new features as part of the Java EE 6 platform. The Preface 1 from the href="htt...

General

Java EE 7 Maven Application (TOTD #197)

Did you know that Java EE 7 APIs are now published in maven ?The complete set of coordinates are describedhere. So how do you build a simple Java EE 7 mavenapplication ?Generate the ususal Java EE 6 maven application as:mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes-DarchetypeArtifactId=webapp-javaee6 -DarchetypeVersion=1.5-DarchetypeRepository=http://repo.maven.apache.org/maven2-DgroupId=org.glassfish -DartifactId=hello-javaee7-Dversion=1.0-SNAPSHOT -Dpackage=org.glassfish.hellojavaee7-Darchetype.interactive=false --batch-mode archetype:generateIn the generated pom.xml, replace<dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency></dependencies>with<repositories> <repository> <id>Java EE 7</id> <url>https://maven.java.net/content/groups/promoted/</url> </repository> </repositories><dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0-b72</version> </dependency> </dependencies>Notice, there is a new <version> of dependency for each GlassFish4 promoted build. This may be simplified in the comingbuilds.The <artifactId> can be changed to javaee-web-apiif your application requires Java EE 7 Web Profile API only.And now all Java EE 7 APIs so far integrated in GlassFish areavailable in your application.You can also include specific API JAR files explicitly in yourproject directly. The latest APIs are available in the format:Java EE 7 Full Platform: http://download.java.net/glassfish/4.0/promoted/javaee-api-7.0-b72.jarJava EE 7 Web Profile: http://download.java.net/glassfish/4.0/promoted/javaee-web-api-7.0-b72.jarCorresponding javadocs: http://download.java.net/glassfish/4.0/promoted/javaee-web-api-7.0-b72-javadoc.jarIn general, you can replace "b72" in the URL with the latestpromoted build number to get the latest artifacts. A simplifiedURL for the latest set of these artifacts is in the works!What next ? Maven archetype and support in NetBeanscoming soon!

Did you know that Java EE 7 APIs are now published in maven ? The complete set of coordinates are href="https://wikis.oracle.com/display/GlassFish/Java+EE+7+Maven+Coordinates">described here. So how...

General

Default DataSource in Java EE 7: Lesser XML and More Defaults (TOTD #196)

Section E.5.5.20 in the JavaEE 7 Platform specification defines a new Default Data Sourcethat must be provided by a Java EE 7-compliant runtime. Thispre-configured data source can be used by application for accessingthe associated database. It is accessible to the application underthe JNDI name:java:comp/DefaultDataSourceThis can be accessed in the application as:@Resource(name="myDataSource", lookup="java:comp/DefaultDataSource")DataSource myDS;If the binding is not specified, the mapping of the reference willdefault to this default data source. So the above fragment isequivalent to:@Resource(name="myDataSource")DataSource myDS;Section 8.2.1.5 in the JPA2.1 specification says If neither jta-data-source and non-jta-data-sourceelements are specified, the deployer must specify a JTA datasource at deployment or a JTA data source must be provided bythe container, and a JTA EntityManagerFactory will be createdto correspond to it. Per.bookThis means a Java EE 7 application can have the followingpersistence.xml:<?xml version="1.0" encoding="UTF-8"?><persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="myPU" transaction-type="JTA"> <jta-data-source>java:comp/DefaultDataSource</jta-data-source> </persistence-unit></persistence>This is semantically equivalent to:<?xml version="1.0" encoding="UTF-8"?><persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="movieplex7PU" transaction-type="JTA"/></persistence>Notice, no jta-data-source.In both cases, the default data source will be provisioned andavailable to the application. In GlassFish 4, this is bound to theJDBC resource jdbc/__default.And this can be verified by giving the command:./bin/asadmin list-jdbc-resourcesjdbc/samplejdbc/__TimerPooljdbc/__defaultCommand list-jdbc-resources executed successfully.Lesser XML and more defaults makes Java EE 7 more lightweight anduser friendly!Download GlassFish4.0 promoted build and try it today!

Section E.5.5.20 in the href="http://download.oracle.com/otndocs/jcp/java_ee-7-pr-spec/index.html">Java EE 7 Platform specification defines a new Default Data Sourcethat must be provided by a Java...

General

JPA 2.1 Implementation - EclipseLink M6 integrated in GlassFish 4 (TOTD #195)

As TOTD#187 explained, one of the new features in JPA 2.1 is SchemaGeneration. It refers to generation of database artifacts liketables, indexes, and constraints in a database schema. Read TOTD#187 for more details. This Tip Of TheDay (TOTD) will explain how to use this feature in GlassFish4.JPA 2.1 is implemented in EclipseLink and the statusshows that a decent progress is made. EclipseLinkMilestone builds shows the dates when milestones are released.It typically takes a few days for the milestone to be integrated inGlassFish 4 after the release.How do you know which milestone is integrated in GlassFish 4 ?Issue the following commmand in glassfish/modulesdirectory:unzip -p org.eclipse.persistence.core.jar META-INF/MANIFEST.MF | grep Bundle-Versionto see an output as:Bundle-Version: 2.5.0.v20130110-d839ca4If we break the version string then it shows this is version 2.5.0and dated 20130110 in the format YYYYMMDD, that would be Jan 10,2013. Based upon the milestonerelease dates, this indicates M6 is integrated.I tried this with the latestnightly build (dated Jan 18). By the time you read this blog,a newer version may be integrated and so the version string may lookdifferent.Now lets see this in action!The sample code explained below can be downloadedhere and run on GlassFish4 1/17 nightly. A promoted build after this nightly shouldwork too.Create an Entity class as:@Entity@Table@NamedQueries({ @NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e")})public class Employee implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(length=40) private String name;This is a simple Employee entity that has two fields idand name. A trivial @NamedQuery isdefined to retrieve the list of employees.The associated persistence.xml looks like:<?xml version="1.0" encoding="UTF-8"?><persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="MyPU" transaction-type="JTA"> <jta-data-source>jdbc/sample</jta-data-source> <properties> <property name="javax.persistence.schema-generation-action" value="drop-and-create"/> <property name="javax.persistence.schema-generation-target" value="database"/> <property name="eclipselink.deploy-on-startup" value="true"/> </properties> </persistence-unit></persistence>Other than the usual elements like <persistence-unit>and <jta-data-source>, the newly introducedproperties - javax.persistence.schema-generation-actionand javax.persistence.schema-generation-target definethe action and target for the schema generation. The action is todrop and create the tables. The target defines to perform the actionin the database. These properties control the behavior of schemageneration and their meaning is defined in TOTD#187. Notice, the third property is EclipseLink specific andis specified to eagerly initialize the Persistence Unit. This willensure that the schema is generated during the applicationdeployment itself. Otherwise it is generated when the PU is firstaccessed.This will generate the table in the database defined by jdbc/sampleJDBC resource. This resource is pre-defined for JavaDB that isalready bundled with GlassFish 4.After this, you can write a simple EJB as:@Statelesspublic class EmployeeBean { @PersistenceContext EntityManager em; public void persist(Employee e) { em.persist(e); } public List<Employee> get() { return em.createNamedQuery("Employee.findAll", Employee.class).getResultList(); }}And invoke it from a Servlet as:for (int i=0; i<5; i++) { bean.persist(new Employee("Name" + i));}for (Employee e : bean.get()) { out.println(e.getName() + "<br>");}A different set of properties may be specified as:<properties> <property name="javax.persistence.schema-generation-action" value="drop-and-create"/> <property name="javax.persistence.schema-generation-target" value="scripts"/> <property name="javax.persistence.ddl-create-script-target" value="createfoo.sql"/> <property name="javax.persistence.ddl-drop-script-target" value="dropfoo.sql"/> <property name="eclipselink.deploy-on-startup" value="true"/> <property name="eclipselink.application-location" value="/tmp"/></properties>These properties specify the action as"drop-and-create", i.e. drop and create the tables. The targetspecifies the the action to be performed in a script. The *.script-targetproperty specifies the name of the files for create and drop DDL.The following scripts are generated:more /tmp/createfoo.sql CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(40), PRIMARY KEY (ID))CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)more /tmp/dropfoo.sql DROP TABLE EMPLOYEEDELETE FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN'By default, the scripts are generated in glassfish/domains/domain1directory. In this case, an EclipseLink-specific property toidentify the base location of the generated files is specified.As TOTD#187 explains, you can bundle DDL and DML scripts to generateand populate the database. Are you ready to test drive JPA 2.1 implementedusing EclipseLink2.5 in GlassFish 4?JPA2.1 Public Review specification has been available for a fewdays now. The Appendix A in the specification provide revisionhistory in case you want to focus on the newly added featuresonly.  If you are a JUG member, you may consider adopting this JSRand providefeedback!

As href="https://blogs.oracle.com/arungupta/entry/jpa_2_1_schema_generation">TOTD #187 explained, one of the new features in JPA 2.1 is SchemaGeneration. It refers to generation of database...

General

JAX-RS Client API and GlassFish 4 - Logging HTTP messages (TOTD #194)

One of the main features added in JAX-RS 2 is Client API. This APIis used to access Web resources and provides integration with JAX-RSProviders. Without this API, the users need to use a low-levelHttpUrlConnection to access the REST endpoint.If the resource looks like:@Path("/fruit")public class MyResource { @GET public String get() {then, before this API, the endpoint can be accessed as:URL url = new URL("http://. . ./webresources/fruit");HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setDoInput(true);conn.setDoOutput(false);BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line;while ((line = br.readLine()) != null) {    //. . .}With this newly introduced API, the endpoint can be accessed as:Client client = ClientFactory.newClient();WebTarget target = client.target("http://. . ./webresources/fruit");String response = target.request().get(String.class);Client is the entry point to the Client API and is usedto build and execute client requests and consume responses returned.The default instance of Client can be obtained bycalling ClientFactory.newClient. Using this we cancreate a WebTarget by specifying URI of the webresource. These targets are then used to prepare client requestinvocation by specifying additional query or matrix parameters andresolving the URI template for different names. Finally, one of theHTTP methods is invoked on the prepared client.The fluency of the API hides the complexity but a betterunderstanding of the flow allows to write better code.All the classes introduced in the specification are available in javax.ws.rs.clientpackage.Lets take a look at a complete sample. The complete source code canbe downloadedhere.For a resource defined as:@Path("/fruit")public class MyResource { @GET public String get() { return Database.getAll(); } @GET @Path("{name}") public String get(@PathParam("name")String payload) { return Database.get(payload); } @POST public void post(String payload) { Database.add(payload); } @PUT public void put(String payload) { Database.add(payload); } @DELETE public void delete(String payload) { Database.delete(payload); }}A Client invoking all the HTTP methods look like:Client client = ClientFactory.newClient();WebTarget target = client.target("http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/webresources/fruit");// POSTtarget.request().post(Entity.text("apple"));// PUTtarget.request().put(Entity.text("banana"));// GET (all)String r = target.request().get(String.class);// GET (one)r = target.path("apple").request().get(String.class);// DELETEtarget.path("banana").request().delete();// GET (all)r = target.request().get(String.class);And here are the message dumps:INFO: 1 * LoggingFilter - Request received on thread http-listener-1(5)1 > POST http://localhost:8080/endpoint/webresources/fruit1 > Content-Type: text/plainappleINFO: 2 * LoggingFilter - Response received on thread http-listener-1(5)2 < 2042 < Date: Fri, 11 Jan 2013 22:21:23 GMT2 < Server: GlassFish Server Open Source Edition 4.02 < X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 4.0 Java/Oracle Corporation/1.7)INFO: 3 * LoggingFilter - Request received on thread http-listener-1(5)3 > PUT http://localhost:8080/endpoint/webresources/fruit3 > Content-Type: text/plainbananaINFO: 4 * LoggingFilter - Response received on thread http-listener-1(5)4 < 2044 < Date: Fri, 11 Jan 2013 22:21:23 GMT4 < Server: GlassFish Server Open Source Edition 4.04 < X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 4.0 Java/Oracle Corporation/1.7)INFO: 5 * LoggingFilter - Request received on thread http-listener-1(5)5 > GET http://localhost:8080/endpoint/webresources/fruitINFO: 6 * LoggingFilter - Response received on thread http-listener-1(5)6 < 2006 < Date: Fri, 11 Jan 2013 22:21:23 GMT6 < Content-Length: 156 < Content-Type: text/html6 < Server: GlassFish Server Open Source Edition 4.06 < X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 4.0 Java/Oracle Corporation/1.7)[apple, banana]INFO: 7 * LoggingFilter - Request received on thread http-listener-1(5)7 > GET http://localhost:8080/endpoint/webresources/fruit/appleINFO: 8 * LoggingFilter - Response received on thread http-listener-1(5)8 < 2008 < Date: Fri, 11 Jan 2013 22:21:23 GMT8 < Content-Length: 58 < Content-Type: text/html8 < Server: GlassFish Server Open Source Edition 4.08 < X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 4.0 Java/Oracle Corporation/1.7)appleINFO: 9 * LoggingFilter - Request received on thread http-listener-1(5)9 > DELETE http://localhost:8080/endpoint/webresources/fruit/bananaINFO: 10 * LoggingFilter - Response received on thread http-listener-1(5)10 < 20410 < Date: Fri, 11 Jan 2013 22:21:23 GMT10 < Server: GlassFish Server Open Source Edition 4.010 < X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 4.0 Java/Oracle Corporation/1.7)INFO: 11 * LoggingFilter - Request received on thread http-listener-1(5)11 > GET http://localhost:8080/endpoint/webresources/fruitINFO: 12 * LoggingFilter - Response received on thread http-listener-1(5)12 < 20012 < Date: Fri, 11 Jan 2013 22:21:23 GMT12 < Content-Length: 712 < Content-Type: text/html12 < Server: GlassFish Server Open Source Edition 4.012 < X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 4.0 Java/Oracle Corporation/1.7)[apple]This has been tested on GlassFish4 build 70 with the following dependencies:<dependency> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId> <version>2.0-m10</version> <type>jar</type> <scope>provided</scope></dependency><dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-common</artifactId> <version>2.0-m10</version> <type>jar</type></dependency>Here are some more pointers to follow:JAX-RS2Specification Public ReviewLatest status onspecification (jax-rs-spec.java.net)LatestJAX-RS2.0 JavadocsLatest status on Jersey(Reference Implementation of JAX-RS 2 - jersey.java.net)LatestJerseyAPI JavadocsLatestGlassFish4.0 Promoted BuildFollow @gf_jerseyProvide feedback on Jersey 2 to users@jersey.java.netand JAX-RS specification to users@jax-rs-spec.java.net.

One of the main features added in JAX-RS 2 is Client API. This API is used to access Web resources and provides integration with href="https://blogs.oracle.com/arungupta/entry/jax_rs_custom_entity_pro...

General

JAX-RS Custom Entity Providers (TOTD #193)

JAX-RS defines Entity Providers that supply mapping servicesbetween on-the-wire representations and their associated Java types.The entities, also known as "message payload" or "payload" representthe main part of an HTTP message. These are specified as methodparameters and return types of resource methods. Several standardJava types such as String, byte[], javax.xml.bind.JAXBElement,java.io.InputStream, java.io.File, andothers have a pre-defined mapping and is required by thespecification. Applications may provide their own mapping to customtypes using MessageBodyReader and MessageBodyWriterinterfaces. This allows to extend the JAX-RS runtime easily tosupport your own custom entity providers.The MessageBodyReader interface defines the contractfor a provider that supports the conversion of a stream to a Javatype. The MessageBodyWriter interface defines thecontract for a provider that supports the conversion of a Java typeto a stream. This Tip Of The Day(TOTD) will explain how to write these custom entity providers.Note, this functionality was defined in JAX-RS 1.0 as opposed toClient API, Client- and Server-side async, Hypermedia, and manyother features. The complete source code for this sample applicationcan be downloadedhere and will work on GlassFish4.0 b70.Here is a simple resource that returns name of the fruit based uponthe index passed as parameter:@Path("fruits")public class MyResource { private String[] response = { "apple", "banana", "mango" }; @POST public String getFruit(int index) { return response[index % 3]; }}This resource can be invoked using the newly introduced Client APIas:Client client = ClientFactory.newClient();WebTarget target = client.target("http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/webresources/fruits");String fruit = target .request() .post(Entity.text("1"), String.class);If we update the resource such that the indexparameter is passed as the following object:public class MyObject implements Serializable { public static final String MIME_TYPE = "application/myType"; private int index; public MyObject() { } public MyObject(int index) { this.index = index; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; }}Then the resource method would look like:@POST@Consumes(value=MyObject.MIME_TYPE)public String getFruit(MyObject mo) { return response[Integer.valueOf(mo.getIndex()) % 3];}The additional @Consumes annotation defines the mediatype that the method can accept. The following custom entityproviders are defined to support this custom type. The first one, MyReader,defines the conversion of on-the-wire representation to MyObjectJava type.@Provider@Consumes(MyObject.MIME_TYPE)public class MyReader implements MessageBodyReader<MyObject> { @Override public boolean isReadable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) { return MyObject.class.isAssignableFrom(type); } @Override public MyObject readFrom(Class<MyObject> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, String> mm, InputStream in) throws IOException, WebApplicationException { try { ObjectInputStream ois = new ObjectInputStream(in); return (MyObject)ois.readObject(); } catch (ClassNotFoundException ex) { Logger.getLogger(MyReader.class.getName()).log(Level.SEVERE, null, ex); } return null; }}The interface require two methods, isReadable and readFrom,to be implemented. The implementation has @Consumesannotation restricting the media type supported by this entityprovider.The second one, MyWriter, defines the conversion fromMyObject Java type to on-the-wire representation.@Provider@Produces(MyObject.MIME_TYPE)public class MyWriter implements MessageBodyWriter<MyObject> { @Override public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) { return MyObject.class.isAssignableFrom(type); } @Override public long getSize(MyObject t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) { // As of JAX-RS 2.0, the method has been deprecated and the // value returned by the method is ignored by a JAX-RS runtime. // All MessageBodyWriter implementations are advised to return -1 from // the method. return -1; } @Override public void writeTo(MyObject t, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException { ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(t); }}The interface require three methods isWriteable, getSize,writeTo to be implemented. The implementation ofgetSize method is recommended to return -1 as JAX-RS runtime isrequired to compute the actual Content-Length headervalue. The implementation has @Produces annotationrestricting the media type supported by this entity provider.The reader and writer entity providers are marked with @Providerand are thus automatically discovered at runtime on the server-side.But until JERSEY-1634is fixed, they need to be explicitly specified in the Applicationclass as:@ApplicationPath("webresources")public class MyApplication extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> resources = new java.util.HashSet<>(); resources.add(MyResource.class); resources.add(MyReader.class); resources.add(MyWriter.class); return resources; }}On the client-side, the providers need to be explicitly registeredas shown:Client client = ClientFactory.newClient();client .configuration() .register(MyReader.class) .register(MyWriter.class);String fruit = target .request() .post(Entity.entity(new MyObject(1), MyObject.MIME_TYPE), String.class);Notice, how invoking the endpoint requires to specify the media typeas part of post method invocation.The complete source code for this sample application can be downloadedhere and will work on GlassFish4.0 b70.Here are some more pointers to followJAX-RS2Specification Public ReviewLatest status onspecification (jax-rs-spec.java.net)LatestJAX-RS2.0 JavadocsLatest status on Jersey(Reference Implementation of JAX-RS 2 - jersey.java.net)LatestJerseyAPI JavadocsLatestGlassFish4.0 Promoted BuildFollow @gf_jerseyProvide feedback on Jersey 2 to users@jersey.java.netand JAX-RS specification to users@jax-rs-spec.java.net.

JAX-RS defines Entity Providers that supply mapping services between on-the-wire representations and their associated Java types. The entities, also known as "message payload" or "payload" representth...

General

Batch Applications in Java EE 7 - Undertanding JSR 352 Concepts: TOTD #192

Batch processing is execution of series of "jobs" that is suitablefor non-interactive, bulk-oriented and long-running tasks. Typicalexamples are end-of-month bank statement generation, end-of-day jobssuch as interest calculation, and ETL (extract-transform-load) in adata warehouse. These tasks are typically data or computationallyintensive, execute sequentially or in parallel, and may be initiatedthrough various invocation models, including ad-hoc, scheduled, andon-demand.JSR 352 willdefine a programming model for batch applications and a runtime forscheduling and executing jobs. This blog will explain the mainconcepts in JSR 352.The diagram below highlight the key concepts of a batch processingarchitecture.A Job is an instance that encapsulates an entire batchprocess. A job is typically put together using a JobSpecification Language and consists of multiple steps. TheJob Specification Language for JSR 352 is implemented with XMLand is referred as "Job XML".A Step is a domain object that encapsulates anindependent, sequential phase of a job. A step contains all ofthe information necessary to define and control the actual batchprocessing.JobOperator provides an interface to manage all aspectsof job processing, including operational commands, such asstart, restart, and stop, as well as job repository commands,such as retrieval of job and step executions.JobRepository holds information about jobs currentrunning and jobs that run in the past. JobOperator providesaccess to this repository.Reader-Processor-Writer pattern is the primary patternand is called as Chunk-oriented processing. Inthis, ItemReader reads one item at a time, ItemProcessorprocesses the item based upon the business logic, such ascalculate account balance and hands it to ItemWriter foraggregation. Once the 'chunk' number of items are aggregated,they are written out, and the transaction is committed.JSR 352 also defines roll-your-own batch pattern, called as Batchlet.This batch pattern is invoked once, runs to completion, andreturns an exit status. This pattern must implement and honor a"cancel" callback to enable operational termination of theBatchlet.A Job XML for a chunk-oriented processing may look like:<job id="myJob" xmlns="http://batch.jsr352/jsl"> <step id="myStep" > <chunk reader="MyItemReader" writer="MyItemWriter" processor="MyItemProcessor" buffer-size="5" checkpoint-policy="item" commit-interval="10" /> </step></job>The <job> has an "id" attribute that defines the logicalname of the job and is used for identification purposes. Each <job> can multiple <step>s where each<step> identifies a job step and it's characteristics.Each <step> has an "id" attribute that defines the logicalname of the job and is used for identification purposes. A <step> may have <chunk> or <batchlet>element, this <step> has a <chunk>. A <chunk>identifies a chunk type step and implements thereader-processor-writer pattern of batch. The "reader", "processor", and "writer" attributes specify theclass names of an item reader, processor, and writerrespectively."buffer-size" specifies number of items to read and bufferbefore writing. When enough items have been read to fill thebuffer, the buffer is emptied to a list and the configuredItemWriter is invoked with the list of items."checkpoint-policy" attribute specifies the checkpoint policythat governs commit behavior for this chunk. Valid values are"item", "time" and "custom". The "item" policy means chunk ischeckpointed after a specified number of items are processed.The "time" policy means the chunk is committed after a specifiedamount of time. The "custom" policy means the chunk ischeckpointed according to a checkpoint algorithm implementation.The default policy is "item"."commit-interval" specifies the commit interval for thespecified checkpointed policy. The unit meaning of thecommit-interval specifies depends on the specified checkpointpolicy. For "item" policy, commit-interval specifies a number ofitems. For "time" policy, commit- interval specifies a number ofseconds. The commit-interval attribute is ignored for "custom"policy.When the configured checkpoint policy directs it is time tocheckpoint, all the items read and processed so far are passedto the "writer".Here is a simple reader:@ItemReaderpublic class MyItemReader { private static int id; MyCheckPoint checkpoint = null; @Open void open(MyCheckPoint checkpoint) { this.checkpoint = checkpoint; System.out.println(getClass().getName() + ".open: " + checkpoint.getItemCount()); } @ReadItem MyBatchRecord read() { checkpoint.incrementByOne(); return new MyBatchRecord(++id); } @CheckpointInfo MyCheckPoint getCheckPoint() { return checkpoint; }}Methods marked with @Open, @ReadItem,and @CheckpointInfo are required.Here is a simple processor that rejects every other item:@ItemProcessorpublic class MyItemProcessor { @ProcessItem MyBatchRecord process(MyBatchRecord record) { return (record.getId() % 2 == 0) ? record : null; }}And here is a simple writer:@ItemWriterpublic class MyItemWriter { MyCheckPoint checkpoint = null; @Open void open(MyCheckPoint checkpoint) { this.checkpoint = checkpoint; System.out.println(getClass().getName() + ".open: " + checkpoint.getItemCount()); } @WriteItems void write(List<MyBatchRecord> list) { System.out.println("Writing the chunk..."); for (MyBatchRecord record : list) { System.out.println(record.getId()); } checkpoint.increment(list.size()); System.out.println("... done."); } @CheckpointInfo MyCheckPoint getCheckPoint() { return checkpoint; }}Finally a simple implementation of MyCheckpoint:public class MyCheckPoint { int itemCount; public int getItemCount() { return itemCount; } public void setItemCount(int itemCount) { this.itemCount = itemCount; } void incrementByOne() { itemCount++; } void increment(int size) { itemCount += size; }}Together, MyItemReader, MyItemWriter,MyItemProcessor, MyCheckPoint, and batch.xml,will read/process/write 5 items and commit when 10 such items havebeen processed.JSR 352specification defines several other concepts such as how JobXML can define sequencing of jobs, listeners to interpose on jobexecution, transaction management, and running jobs in partitionedand concurrent modes. Subsequent blog will explain some of thoseconcepts.A complete replay of JavaBatch for Cost-Optimized Business Efficiency from JavaOne2012 can be seenhere (click on CON4105_mp4_4105_001 in Media).Each feature will be added to the JSR subject to EG approval. Youcan share your feedback to public@jbatch.java.net.The APIs and implementation of JSR 352 are not integrated in GlassFish4 promoted builds yet. Here are some more references for you:JavaAPI for Batch Processing Public Review DownloadsSpecificationProject (jbatch.java.net)JSRExpert Group Discussion Archive (public@jbatch.java.net)JavaEE 7 Specification StatusHere are some other Java EE 7 primers published so far:SimpleJMS 2.0 Sample (TOTD #191)What'sNew in Servlet 3.1 ?ConcurrencyUtilities for Java EE (JSR 236)CollaborativeWhiteboard using WebSocket in GlassFish 4 (TOTD #189)Non-blockingI/O using Servlet 3.1 (TOTD #188)What'sNew in EJB 3.2 ?JPA2.1 Schema Generation (TOTD #187)WebSocketApplications using Java (JSR 356)Jersey2 in GlassFish 4 (TOTD #182)WebSocketand Java EE 7 (TOTD #181)JavaAPI for JSON Processing (JSR 353)JMS2.0 Early Draft (JSR 343)And of course, more on their way! Do you want to see any particularone first ?

Batch processing is execution of series of "jobs" that is suitable for non-interactive, bulk-oriented and long-running tasks. Typicalexamples are end-of-month bank statement generation,...

General

Simple JMS 2.0 Sample - @JMSDestinationDefinition and Synchronous Message Receive: TOTD #191

JMS2.0 Early Draft - Simplified API Sample Code explained some ofthe changes that are made in JMS 2.0 to "catch up" with all thechanges in the Java SE and EE platform over the past few years. Themain goals of JMS 2.0 are:Changes to improve ease-of-developmentClarification of relationship between JMS and other Java EEspecificationsDefinition of a new mandatory API to allow any JMS provider tobe integrated with any other Java EE Application ServerOther enhancements as requested by the communityThis Tip Of The Day (TOTD) willexplain a simple sample showing how to send a message and receive itsynchronously. The complete source code for the sample can be downloadedhere.This is a Stateless EJB that has a single method to send a message.@Statelesspublic class MessageSender { @Inject JMSContext context; @Resource(mappedName="java:global/jms/myQueue") Queue queue; public void sendMessage(String message) { context.createProducer().send(queue, message); }}In this code:JMSContext is a new interface introduced in thesimplified API in JMS 2.0. This combines in a single object thefunctionality of two separate objects from the JMS 1.1 API: a Connectionand a Session. A JMSContext may be injected in the Java EE weband EJB containers using the @Inject annotation. AJMSContext created in this way is described asbeing container-managed. A container-managed JMSContextwill be closed automatically by the container. Applicationsrunning in the Java EE web and EJB containers are not permittedto create more than one active session on a connection. Thisallows to combine them in a single object offering a simplerAPI. This is the recommended way for creating JMS context inJava EE applications.A JMSContext may be created by calling one of thecreateContext methods on a ConnectionFactory.A JMSContext that is created this way is describedas being application-managed. An application-managed JMSContextmust be closed when no longer needed by calling its closemethod. Applications running in a Java SE environment or in theJava EE application client container are permitted to createmultiple active sessions on the same connection. This allows thesame physical connection to be used in multiple threadssimultaneously. The createContext method isrecommended to create JMSContext in suchapplications.The Java EE Platform requires a preconfigured JMS ConnectionFactoryaccessible to the application under the JNDI name:java:comp/DefaultJMSConnectionFactoryThe annotation @JMSConnectionFactory may be usedto specify the JNDI lookup name of the ConnectionFactoryused to create the JMSContext as:@Inject@JMSConnectionFactory("java:comp/DefaultJMSConnectionFactory")JMSContext context;If no lookup name is specified or the @JMSConnectionFactoryis omitted then the platform default JMS connection factory willbe used. The above code fragment is equivalent to:@InjectJMSContext context;@Resource defines a dependency on a resourceneeded by the application. In this case, it specifies the JNDIname of the destination to which the message needs to be sent.When an application needs to send messages it uses the createProducermethod to create JMSProducer which providesmethods to configure and send messages. The various setPropertymethods are used to set property on the message being sent.There are several other methods like setPriority,setDeliveryDelay, and setTimeToLiveto set other quality-of-service attributes for the message beingsent.Messages may be sent synchronously or asynchronously.Synchronous messages are sent using one of the sendmethods. Asynchronous messages are sent using setAsyncmethod and assigning a CompletionListener. Whenthe message has been successfully sent the JMS provider invokesthe callback method onCompletion on the CompletionListenerobject. If the message is not sent for some reason or anacknowledgement from the remote JMS server is not received thenonException callback method is called. Anasynchronous send is not permitted in a Java EE application.This is a Stateless EJB that has a single method to receive themessage synchronously.@Statelesspublic class MessageReceiverSync { @Inject private JMSContext context; @Resource(mappedName="java:global/jms/myQueue") Queue myQueue; public String receiveMessage() { String message = context.createConsumer(myQueue).receiveBody(String.class, 1000); return "Received " + message; }}In this code:JMSContext referring to the preconfigured JMS ConnectionFactoryis injected by the container.@Resource defines a dependency on the JMSdestination on which the message is received.When an application needs to receive messages it uses one ofthe several createConsumer or createDurableConsumermethods to create a JMSConsumer. createConsumercreates a non-durable subscription on the specified destination.This means that a client will only see the messages published onthe destination when the subscriber is active. If the subscriberis not active, it is missing messages published on thedestination. createDurableConsumer creates anunshared durable subscription of a specified topic and creates aconsumer on that subscription. This allows the subscriber willreceive all messages published on a topic, including the onespublished when there is no active consumer associated with it.The JMS provider retains a record of this durable subscriptionand ensures that all messages from the topic's publishers areretained until they are delivered to, and acknowledged by, aconsumer on this durable subscription or until they haveexpired.A JMSConsumer provides methods to receive messageseither synchronously or asynchronously. receivemethods are used for synchronous delivery of the messages. A MessageListenerobject may be registered with the client for asynchronousdelivery of the messages. onMessage method of theMessageListener object are called as messages arereceived. Asynchronous delivery of messages will not work untilMQ-264 isfixed.Next is a Servlet that ties all the pieces together. It defines theJMS Destination and send and receive the message using thepreviously defined EJBs.@JMSDestinationDefinition(name = "java:global/jms/myQueue", resourceAdapterName = "jmsra", className = "javax.jms.Queue", destinationName="queue1234", description="My Queue")@WebServlet(urlPatterns = {"/TestServlet"})public class TestServlet extends HttpServlet { @EJB MessageSender sender; @EJB MessageReceiverSync receiver; void doGet(HttpServletRequest request, HttpServletResponse response) { . . . String m = "Hello there"; sender.sendMessage(m); out.format("Message sent: %1$s.<br>", m); out.println("Receiving message...<br>"); String message = receiver.receiveMessage(); out.println("Message received: " + message); . . . }In this code:@JMSDestinationDefinition defines the JMS destination. The nameattribute defines the JNDI name of the destination beingdefined, destinationName attribute defines thename of the queue or topic, and classNameattribute defines the JMS destination implementation class name.doGet method uses the injected EJBs to send andreceive the message.The complete source code for the sample can be downloadedhere. "mvn package" and deploy the generated WAR file.Download GlassFish4 build 68 onwards and try this sample today!The latest progress on JMS 2.0 can be tracked at:jms-spec.java.netJSR 343 EG archive at jsr343-expertsDiscussion at users@jms-specJSR 343LatestSpecificationLatest Javadocs (download,online)Help us make JMS 2.0 better, simpler, easier to use. Join users@jms-specand contribute!

href="https://blogs.oracle.com/arungupta/entry/jms_2_0_early_draft">JMS 2.0 Early Draft - Simplified API Sample Code explained some of the changes that are made in JMS 2.0 to "catch up" with all thech...

General

Adopt-a-JSR for Java EE 7 - Getting Started

Adopt-a-JSRis an initiative started by JUG leaders to encourage JUG members toget involved in a JSR, in order to increase grass rootsparticipation. This allows JUG members to provide early feedback tospecifications before they are finalized in the JCP. The standardsin turn become more complete and developer-friendly after gettingfeedback from a wide variety of audience. adoptajsr.orgprovide more details about the logistics and benefits for you andyour JUG. A similar activity was conducted for OpenJDKas well. MarkusEisele also provide a great introduction to the program (inGerman).Java EE 7 (JSR 342)is scheduled to go final in Q2 2013. There are several new JSRs thatare getting included in the platform (e.g. WebSocket, JSON, andBatch), a few existing ones are getting an overhaul (e.g. JAX-RS 2and JMS 2), and several other getting minor updates (e.g. JPA 2.1and Servlets 3.1). Each Java EE 7 JSR can leverage your expertiseand would love your JUG to adopt a JSR.What does it mean to adopt a JSR ?Your JUG is going to identify a particular JSR, or multipleJSRs, that is of interest to the JUG members. This is mostlydone by polling/discussing on your local JUG members list.Your JUG will download and review the specification(s) andjavadocs for clarity and completeness. The complete set of JavaEE 7 specifications, their download links, and EG archives are listedhere. glassfish.org/adoptajsrprovide specific areas where different specification leads arelooking for feedback.Your JUG can then think of a sample application that can bebuilt using the chosen specification(s). An existing use case(from work or a personal hobby project) may be chosen to beimplemented instead. This is where your creativity anduniqueness comes into play.Most of the implementations are already integrated in GlassFish 4and others will be integrated soon. You can also explore integrationof multiple technologies and provide feedback on the simplicity andease-of-use of the programming model. Especially look forintegration with existing Java EE technologies and see if you findany discrepancies. Report any missing features that may be includedin future release of the specification.The most important part is to provide feedback by filing bugs on thecorrespondingspec or RI project. Any thing that is not clear either in thespec or implementation should be filed as a bug. This is what willensure that specification and implementation leads are getting therequired feedback and improving the quality of the final deliverableof the JSR.How do I get started ?A simple way to get started can be achieved by following S.M.A.R.T.as explained below.SpecificIdentify who all will be involved ? Whatwould you like to accomplish ? For example, even thoughbuilding a sample app will provide real-world validity ofthe API but because of time constraints you may identifythat reviewing the specification and javadocs only can beaccomplished. Establish a time frame by which the activitiesneed to be complete. MeasurableDefine a success for metrics. For example,this could be the number of bugs filed. Remember, quality ofbugs is more important that quantity of bugs. Define yourend goal, for example, reviewing 4 chapters of thespecification or completing the sample application. Create adashboard that will highlight your JUG's contribution tothis effort.AttainableMake sure JUG members understand the timecommitment required for providing feedback. This can varybased upon the level of involvement (any is good!) and thenumber of specifications picked. adoptajsr.orgdefines different categories of involvement. Once again, anylevel of involvement is good. Just reviewing a chapter, asection, or javadocs for your usecase is helpful.RelevantPick JSRs that JUG members are willing andable to work. If the JUG members are not interested thenthey might loose motivation half-way through. The "able"part is tricky as you can always stretch yourself and learna new skill ;-)Time-boundDefine a time table of activities withclearly defined tasks. A tentative time table may look like:Dec 25: Discuss and agree upon the specifications with JUGJan 1: Start Adopt-a-JSR for Java EE 7Jan 15: Initial spec reading complete. Keep thinking throughthe application that will be implemented.Jan 22: Early design of the sample application is readyJan 29: JUG members agree upon the applicationNext 4 weeks: Implement the applicationOf course, you'll need to alter this based upon yourcommitment. Maintaining an activity dashboard will help youmonitor and track the progress.Make sure to keep filing bugs through out the process!12 JUGs from around the world (SouJava, CampinasJUG, Chennai JUG, London JavaCommunity, BeJUG,Morocco JUG, Peru JUG, Indonesia JUG, CongoJUG, Silicon ValleyJUG, MadridJUG, and HoustonJUG) have already adopted one of the Java EE 7 JSRs. I'malready helping some JUGs bootstrap and would love to help your JUGtoo.What are you waiting for ?

Adopt-a-JSR is an initiative started by JUG leaders to encourage JUG members to get involved in a JSR, in order to increase grass rootsparticipation. This allows JUG members to provide early...

General

What's new in Servlet 3.1 ? - Java EE 7 moving forward

Servlet 3.0 was released as part of Java EE 6 and made huge changesfocused at ease-of-use. The idea was to leverage the latest languagefeatures such as annotations and generics and modernize how Servletscan be written. The web.xml was made as optional as possible. Servet3.1 (JSR 340),scheduled to be part of Java EE 7, is an incremental releasefocusing on couple of key features and some clarifications in thespecification.The main features of Servlet 3.1 are explained below:Non-blocking I/O - Servlet 3.0 allowed asynchronous requestprocessing but only traditional I/O was permitted. This canrestrict scalability of your applications. Non-blocking I/Oallow to build scalable applications. TOTD#188 provide more details about how non-blocking I/O canbe done using Servlet 3.1.HTTP protocol upgrade mechanism - Section14.42 in the HTTP 1.1 specification (RFC 2616)defines an upgrade mechanism that allows to transition from HTTP1.1 to some other, incompatible protocol. The capabilities andnature of the application-layer communication after the protocolchange is entirely dependent upon the new protocol chosen. Afteran upgrade is negotiated between the client and the server, thesubsequent requests use the new chosen protocol for messageexchanges. A typical example is how WebSocket protocol isupgraded from HTTP as described in OpeningHandshake section of RFC 6455.The decision to upgrade is made in Servlet.servicemethod. This is achieved by adding a new method: HttpServletRequest.upgradeand two new interfaces: javax.servlet.http.HttpUpgradeHandlerand javax.servlet.http.WebConnection.TyrusHttpUpgradeHandler shows how WebSocket protocolupgrade is done in Tyrus(Reference Implementation for Java API for WebSocket).Security enhancementsApplying run-as security roles to #init and #destroy methodsSessionfixation attack by adding HttpServletRequest.changeSessionIdand a new interface HttpSessionIdListener. Youcan listen for any session id changes using these methods.Default security semantic for non-specified HTTP method in <security-constraint>Clarifying the semantics if a parameter is specified in theURI and payloadMiscellaneousServletResponse.reset clears any data thatexists in the buffer as well as the status code, headers. Inaddition, Servlet 3.1 will also clears the state of calling getServletOutputStreamor getWriter.ServletResponse.setCharacterEncoding: Sets thecharacter encoding (MIME charset) of the response being sentto the client, for example, to UTF-8.Relative protocol URL can be specified in HttpServletResponse.sendRedirect.This will allow a URL to be specified without a scheme. Thatmeans instead of specifying"http://anotherhost.com/foo/bar.jsp" as a redirect address,"//anotherhost.com/foo/bar.jsp" can be specified. In this casethe scheme of the corresponding request will be used.Clarification in HttpServletRequest.getPartand .getParts without multipart configuration.Clarification that ServletContainerInitializeris independent of metadata-complete and isinstantiated per web application.A complete replay of What'sNew in Servlet 3.1: An Overview from JavaOne 2012 can be seenhere (click on CON6793_mp4_6793_001 in Media).Each feature will be added to the JSR subject to EG approval. Youcan share your feedback to users@servlet-spec.java.net.Here are some more references for you:Servlet3.1 Public Review Candidate DownloadsServlet3.1 PR Candidate SpecServlet3.1 PR Candidate JavadocsServletSpecification ProjectJSRExpert Group Discussion ArchiveJavaEE 7 Specification StatusSeveral features have already been integrated in GlassFish4 Promoted Builds. Have you tried any of them ?Here are some other Java EE 7 primers published so far:ConcurrencyUtilities for Java EE (JSR 236)CollaborativeWhiteboard using WebSocket in GlassFish 4 (TOTD #189)Non-blockingI/O using Servlet 3.1 (TOTD #188)What'sNew in EJB 3.2 ?JPA2.1 Schema Generation (TOTD #187)WebSocketApplications using Java (JSR 356)Jersey2 in GlassFish 4 (TOTD #182)WebSocketand Java EE 7 (TOTD #181)JavaAPI for JSON Processing (JSR 353)JMS2.0 Early Draft (JSR 343)And of course, more on their way! Do you want to see any particularone first ?

Servlet 3.0 was released as part of Java EE 6 and made huge changes focused at ease-of-use. The idea was to leverage the latest languagefeatures such as annotations and generics and modernize...

General

WebSocket Samples in GlassFish 4 build 66 - javax.websocket.* package: TOTD #190

This blog has published a few blogs on using JSR 356 ReferenceImplementation (Tyrus) integrated in GlassFish 4promoted builds.TOTD#183: Getting Started with WebSocket in GlassFishTOTD#184: Logging WebSocket Frames using Chrome DeveloperTools, Net-internals and WiresharkTOTD#185: Processing Text and Binary (Blob, ArrayBuffer,ArrayBufferView) Payload in WebSocketTOTD#186: Custom Text and Binary Payloads using WebSocketTOTD#189: Collaborative Whiteboard using WebSocket inGlassFish 4The earlier blogs created a WebSocket endpoint as:import javax.net.websocket.annotations.WebSocketEndpoint;@WebSocketEndpoint("websocket")public class MyEndpoint { . . .Based upon the discussionin JSR 356 EG, the package names have changed to javax.websocket.*.So the updated endpoint definition will look like:import javax.websocket.WebSocketEndpoint;@WebSocketEndpoint("websocket")public class MyEndpoint { . . .The POM dependency is:<dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.0-b09</version> </dependency>And if you are using GlassFish4 build 66, then you also need to provide a dummyEndpointFactory implementation as:import javax.websocket.WebSocketEndpoint;@WebSocketEndpoint(value="websocket", factory=MyEndpoint.DummyEndpointFactory.class)public class MyEndpoint { . . .   class DummyEndpointFactory implements EndpointFactory {    @Override public Object createEndpoint() { return null; }  }}This is only interim and will be cleaned up in subsequent builds.But I've seen couple of complaints about this already and so thisdeserves a short blog.Have you been tracking the latest Java EE 7 implementations in GlassFish4 promoted builds ?

This blog has published a few blogs on using JSR 356 Reference Implementation (Tyrus) integrated in href="http://download.java.net/glassfish/4.0/promoted">GlassFish 4 promoted builds. href="https://blo...

Running

JavaOne Latin America 2012 is a wrap!

Third JavaOne in Latin America (2010,2011)is now a wrap!Like lastyear, the event started with a Geek Bike Ride. I could notattend the bike ride because of pre-planned activities but heardlots of goodcomments about it afterwards. This is a great way to engagewith JavaOne attendees in an informal setting. I highly recommendyou joining next time!JavaOneBlog provides a a great coverage for the opening keynotes. Italked about all the great set of functionality that is coming inthe Java EE 7 Platform. Also shared the details on how Java EE 7JSRs are willing to take help from the Adopt-a-JSR program.glassfish.org/adoptajsrbridges the gap between JUGs willing to participate and looking forareas on where to help. The different specification leads haveidentified areas on where they are looking for feedback. So if youare JUG is interested in picking a JSR, I recommend to take a lookat glassfish.org/adoptajsrand jump on the bandwagon. The main attraction for the Tuesday evening was the GlassFish Party.The party was packed with Latin American JUG leaders, execs fromOracle, and local community members. Free flowing food andbeer/caipirinhas acted as great lubricant for great conversations.Some of them were considering the migration from Spring -> JavaEE 6 and replacing their primary app server with GlassFish. Locaweb, a localhosting provider sponsored a round of beer at the party as well.They are planning to come with Java EE hosting next year andGlassFish would be a logical choice for them ;)I heard lots of positive feedback about the party afterwards. Manythanks to Bruno Borges for organizing a great party!Check out some more funpictures of the party!Next day, I gave a presentation on "The Java EE 7 Platform:Productivity and HTML 5" and the slides are now available: With so much new content coming in the plaform:Java Caching API (JSR 107)Concurrency Utilities for Java EE (JSR 236)Batch Applications for the Java Platform (JSR 352)Java API for JSON (JSR 353)Java API for WebSocket (JSR 356)And JAX-RS 2.0 (JSR339) and JMS 2.0 (JSR 343) gettingmajor updates, there is definitely lot of excitement that wasevident amongst the attendees. The talk was delivered in thebiggest hall and had about 200 attendees.Also spent a lot of time talking to folks at the OTN Lounge.The JUG leaders appreciation dinner in the evening had its usualshare of fun.Day 3 started with a session on "Building HTML5 WebSocket Apps inJava". The slides are now available: The room was packed with about 150 attendees and there was goodinteraction in the room as well. A collaborativewhiteboard built using WebSocket was very well received. Thefollowing tweets made it more worthwhile:A WebSocket speek, by @ArunGupta, was worth every hour lost intransit. #JavaOneBrasil2012, #JavaOneBr@arungupta awesome presentation about WebSockets :)The session was immediately followed by the hands-on lab "DevelopingJAX-RS Web Applications Utilizing Server-Sent Events and WebSocket".The lab covers JAX-RS 2.0, Jersey-specific features such asServer-Sent Events, and a WebSocket endpoint using JSR 356. Thecomplete self-paced lab guide can be downloadedfrom here.The lab was planned for 2 hours but several folks finished theentire exercise in about 75 mins. The wonderfully written labmaterial and an added incentive of JavaEE 6 Pocket Guide did the trick ;-)I also spoke at "The Java Community Process: How You Can Make aPositive Difference". It was really great to see several JUG leaderstalking about Adopt-a-JSR program and other activities thatattendees can do to participate in the JCP. I shared details about Adopt a Java EE 7 JSR aswell.The community keynote in the evening was looking fun but I had toleave in between to go through the peak Sao Paulo traffic time :)Enjoy the complete set of pictures in the album:

Third JavaOne in Latin America (href="https://blogs.oracle.com/arungupta/entry/javaone_latin_america_2010_is">2010,href="https://blogs.oracle.com/arungupta/entry/javaone_latin_america_2011_pictures">2...

General

Concurrency Utilities for Java EE Early Draft (JSR 236)

Concurrency Utilities for Java EE is being worked as JSR 236 and hasreleased an EarlyDraft. It provides concurrency capabilities to Java EEapplication components without compromising container integrity.Simple (common) and advanced concurrency patterns are easilysupported without sacrificing usability.Using Java SE concurrency utilities such as java.util.concurrentAPI, java.lang.Thread and java.util.Timerin a Java EE application component such as EJB or Servlet areproblematic since the container and server have no knowledge ofthese resources. The JSR 236 enables concurrency largely byextending the Concurrency Utilities API developed under JSR-166.This also allows a consistency between Java SE and Java EEconcurrency programming model. The threads so spawned are providedand managed by the container.There are four main programming interfaces available:ManagedExecutorServiceManagedScheduledExecutorServiceContextServiceManagedThreadFactoryManagedExecutorService is a managed version of java.util.concurrent.ExecutorService.The implementations of this interface are provided by thecontainer and accessible using JNDI reference:<resource-env-ref>  <resource-env-ref-name>    concurrent/BatchExecutor  </resource-env-ref-name>  <resource-env-ref-type>    javax.enterprise.concurrent.ManagedExecutorService  </resource-env-ref-type><resource-env-ref>and available as:@Resource(name="concurrent/BatchExecutor")ManagedExecutorService executor;Its recommended to bind the JNDI references in the java:comp/env/concurrentsubcontext. The asynchronous tasks that need to be executed need to implementjava.lang.Runnable or java.util.concurrent.Callableinterface as:public class MyTask implements Runnable { public void run() { // business logic goes here }}ORpublic class MyTask2 implements Callable<Date> {  public Date call() { // business logic goes here   }}The task is then submitted to the executor using one of the submitmethod that return a Future instance. The Futurerepresents the result of the task and can also be used to check ifthe task is complete or wait for its completion.Future<String> future = executor.submit(new MyTask(), String.class);. . .String result = future.get();The task would run on a separate thread provided and managed bythe container.Another example to submit tasks is:class MyTask implements Callable<Long> { . . . }class MyTask2 implements Callable<Date> { . . . }ArrayList<Callable> tasks = new ArrayList<();tasks.add(new MyTask());tasks.add(new MyTask2());List<Future<Object>> result = executor.invokeAll(tasks);The ManagedExecutorService may be configured fordifferent properties such as:Hung Task Threshold: Time in milliseconds that a taskcan execute before it is considered hungPool InfoCore Size: Number of threads to keep aliveMaximum Size: Maximum number of threads allowed inthe poolKeep Alive: Time to allow threads to remain idle when# of threads > Core SizeWork Queue Capacity: # of tasks that can be stored ininbound bufferThread Use: Application intend to run short vslong-running tasks, accordingly pooled or daemon threads arepickedThe specification does not mandate any configuration attributes.The above mentioned properties are only examples and may not besupported by all application servers.ManagedScheduledExecutorService adds delay andperiodic task running capabilities to ManagedExecutorService.The implementations of this interface are provided by thecontainer and accessible using JNDI reference:<resource-env-ref>  <resource-env-ref-name>    concurrent/BatchExecutor  </resource-env-ref-name>  <resource-env-ref-type>    javax.enterprise.concurrent.ManagedExecutorService  </resource-env-ref-type><resource-env-ref>and available as:@Resource(name="concurrent/timedExecutor")ManagedExecutorService executor;And then the tasks are submitted using submit, invokeXXXor scheduleXXX methods.ScheduledFuture<?> future = executor.schedule(new MyTask(), 5, TimeUnit.SECONDS);This will create and execute a one-shot action that becomesenabled after 5 seconds of delay.More control is possible using one of the newly added methods:MyTaskListener implements ManagedTaskListener {  public void taskStarting(...) { . . . }  public void taskSubmitted(...) { . . . }  public void taskDone(...) { . . . }  public void taskAborted(...) { . . . }}ScheduledFuture<?> future = executor.schedule(new MyTask(), 5, TimeUnit.SECONDS, new MyTaskListener());Here, ManagedTaskListener is used to monitor thestate of a task's future.ManagedThreadFactory provides a method for creatingthreads for execution in a managed environment. A simple usage is:@Resource(name="concurrent/myThreadFactory")ManagedThreadFactory factory;. . .Thread thread = factory.newThread(new Runnable() { . . . });concurrent/myThreadFactory is a JNDI resource.There is lot of interesting content in the EarlyDraft, download it, and read yourself. The implementationwill be made available soon and also be integrated in GlassFish 4as well.Some references for further exploration ...JavadocEarlyDraft Specificationconcurrency-ee-spec.java.netusers@concurrency-ee-spec.java.net

Concurrency Utilities for Java EE is being worked as href="http://jcp.org/en/jsr/detail?id=236">JSR 236 and has released an href="http://jcp.org/aboutJava/communityprocess/edr/jsr236/index.html">Early...

General

Collaborative Whiteboard using WebSocket in GlassFish 4 - Text/JSON and Binary/ArrayBuffer Data Transfer (TOTD #189)

This blog has published a few blogs on using JSR 356 ReferenceImplementation (Tyrus) as its integrated in GlassFish 4promoted builds.TOTD#183: Getting Started with WebSocket in GlassFishTOTD#184: Logging WebSocket Frames using Chrome DeveloperTools, Net-internals and WiresharkTOTD#185: Processing Text and Binary (Blob, ArrayBuffer,ArrayBufferView) Payload in WebSocketTOTD#186: Custom Text and Binary Payloads using WebSocketOne of the typical usecase for WebSocket is online collaborativegames. This Tip Of The Day (TOTD)explains a sample that can be used to build such games easily.The application is a collaborative whiteboard where different shapescan be drawn in multiple colors. The shapes drawn on one browser areautomatically drawn on all other peer browsers that are connected tothe same endpoint. The shape, color, and coordinates of the imageare transfered using a JSON structure. A browser may opt-out ofsharing the figures. Alternatively any browser can send a snapshotof their existing whiteboard to all other browsers. Take a look atthis video to understand how the application work and the underlyingcode.The Java API for WebSocket has evolved since this sample was first created. Here is the source code corresponding to different builds of GlassFish:GlassFish4 4 BuildSource Code66here74here76here78here84hereThe code in the application is explained below.The web page (index.jsp) has a HTML5Canvas as shown:<canvas id="myCanvas" width="150" height="150" style="border:1px solid #000000;"></canvas>And some radio buttons to choose the color and shape. By default,the shape, color, and coordinates of any figure drawn on the canvasare put in a JSON structure and sent as a message to the WebSocketendpoint. The JSON structure looks like:{ "shape": "square", "color": "#FF0000", "coords": { "x": 31.59999942779541, "y": 49.91999053955078 }} The endpoint definition looks like:@WebSocketEndpoint(value = "websocket",encoders = {FigureDecoderEncoder.class},decoders = {FigureDecoderEncoder.class})public class Whiteboard {As you can see, the endpoint has decoder and encoder registered thatdecodes JSON to a Figure (a POJO class) and vice versa respectively.The decode method looks like:public Figure decode(String string) throws DecodeException { try { JSONObject jsonObject = new JSONObject(string); return new Figure(jsonObject); } catch (JSONException ex) { throw new DecodeException("Error parsing JSON", ex.getMessage(), ex.fillInStackTrace()); }}And the encode method looks like:public String encode(Figure figure) throws EncodeException { return figure.getJson().toString();}FigureDecoderEncoder implements both decoder and encoderfunctionality but thats purely for convenience. But the recommendeddesign pattern is to keep them in separate classes. In certaincases, you may even need only one of them.On the client-side, the Canvas is initialized as:var canvas = document.getElementById("myCanvas");var context = canvas.getContext("2d");canvas.addEventListener("click", defineImage, false);The defineImage method constructs the JSON structureas shown above and sends it to the endpoint using websocket.send().An instant snapshot of the canvas is sent using binary transfer withWebSocket. The WebSocket is initialized as:var wsUri = "ws://localhost:8080/whiteboard/websocket";var websocket = new WebSocket(wsUri);websocket.binaryType = "arraybuffer";The important part is to set the binaryType propertyof WebSocket to arraybuffer. This ensures that anybinary transfers using WebSocket are done using ArrayBufferas the default type seem to be blob. The actual binarydata transfer is done using the following:var image = context.getImageData(0, 0, canvas.width, canvas.height);var buffer = new ArrayBuffer(image.data.length);var bytes = new Uint8Array(buffer);for (var i=0; i<bytes.length; i++) { bytes[i] = image.data[i];}websocket.send(bytes);This comprehensive sample shows the following features of JSR 356API:Annotation-driven endpointsSend/receive text and binary payload in WebSocketEncoders/decoders for custom text payloadIn addition, it also shows how images can be captured and drawnusing HTML5 Canvas in a JSP.How could this be turned in to an online game ? Imagine drawing aTic-tac-toeboard on the canvas with two players playing and others watching.Then you can build access rights and controls within theapplication itself. Instead of sending a snapshot of the canvas ondemand, a new peer joining the game could be automaticallytransferred the current state as well. Do you want to build thisgame ?I built a similar game afew years ago. Do somebody want to rewrite the game usingWebSocket APIs ? :-)Many thanks to Jituand Akshay for helpingthrough the WebSocket internals!Here are some references for you:JSR 356:Java API for WebSocket - Specification (EarlyDraft) and Implementation(already integrated in GlassFish4promoted builds)Subsequent blogs will discuss the following topics (not necessary inthat order) ...Error handlingInterface-driven WebSocket endpointJava client APIClient and Server configurationSecuritySubprotocolsExtensionsOther topics from the API

This blog has published a few blogs on using JSR 356 Reference Implementation (Tyrus) as its integrated in href="http://download.java.net/glassfish/4.0/promoted">GlassFish 4 promoted builds. href="http...

General

Non-blocking I/O using Servlet 3.1: Scalable applications using Java EE 7 (TOTD #188)

Servlet 3.0 allowed asynchronous request processing but onlytraditional I/O was permitted. This can restrict scalability of yourapplications. In a typical application, ServletInputStream is readin a while loop.public class TestServlet extends HttpServlet {    protected void doGet(HttpServletRequest request, HttpServletResponse response)         throws IOException, ServletException {     ServletInputStream input = request.getInputStream();       byte[] b = new byte[1024];       int len = -1;       while ((len = input.read(b)) != -1) {          . . .        }   }}If the incoming data is blocking or streamed slower than the servercan read then the server thread is waiting for that data. The samecan happen if the data is written to ServletOutputStream.This is resolved in Servet 3.1 (JSR 340, to bereleased as part Java EE 7) by adding eventlisteners - ReadListener and WriteListenerinterfaces. These are then registered using ServletInputStream.setReadListenerand ServletOutputStream.setWriteListener. Thelisteners have callback methods that are invoked when the content isavailable to be read or can be written without blocking.The updated doGet in our case will look like:AsyncContext context = request.startAsync();ServletInputStream input = request.getInputStream();input.setReadListener(new MyReadListener(input, context));Invoking setXXXListener methods indicate thatnon-blocking I/O is used instead of the traditional I/O. At most oneReadListener can be registered on ServletIntputStreamand similarly at most one WriteListener can beregistered on ServletOutputStream. ServletInputStream.isReadyand ServletInputStream.isFinished are new methods tocheck the status of non-blocking I/O read. ServletOutputStream.canWriteis a new method to check if data can be written without blocking. MyReadListener implementation looks like:@Overridepublic void onDataAvailable() { try { StringBuilder sb = new StringBuilder(); int len = -1; byte b[] = new byte[1024]; while (input.isReady() && (len = input.read(b)) != -1) { String data = new String(b, 0, len); System.out.println("--> " + data); } } catch (IOException ex) { Logger.getLogger(MyReadListener.class.getName()).log(Level.SEVERE, null, ex); }}@Overridepublic void onAllDataRead() { System.out.println("onAllDataRead"); context.complete();}@Overridepublic void onError(Throwable t) { t.printStackTrace(); context.complete();}This implementation has three callbacks:onDataAvailable callback method is calledwhenever data can be read without blockingonAllDataRead callback method is invoked data forthe current request is completely read.onError callback is invoked if there is an errorprocessing the request.Notice, context.complete() is called in onAllDataReadand onError to signal the completion of data read.For now, the first chunk of available data need to be read in the doGetor service method of the Servlet. Rest of the data canbe read in a non-blocking way using ReadListener afterthat. This is going to get cleaned up where all data read can happenin ReadListener only.The sample explained above can be downloaded fromhere and works with GlassFish4.0 build 64 and onwards.The slides and a complete re-run of What'snew in Servlet 3.1: An Overview session at JavaOne isavailable here.Here are some more references for you:JavaEE 7 Specification StatusServletSpecification ProjectJSRExpert Group Discussion ArchiveServlet3.1 Javadocs

Servlet 3.0 allowed asynchronous request processing but only traditional I/O was permitted. This can restrict scalability of your applications. In a typical application, ServletInputStream is readin...

General

What's new in EJB 3.2 ? - Java EE 7 chugging along!

EJB 3.1 added a whole ton of features for simplicity and ease-of-usesuch as @Singleton, @Asynchronous, @Schedule, Portable JNDI name,EJBContainer.createEJBContainer, EJB 3.1 Lite, and many others. Aspart of Java EE 7, EJB 3.2 (JSR 345) is makingprogress and this blog will provide highlights from the work done sofar. This release has been particularly kept small but includeseveral minor improvements and tweaks for usability.More features in EJB.LiteAsynchronous session beanNon-persistent EJB Timer serviceThis also means these features can be used in embeddable EJBcontainer and there by improving testability of yourapplication.Pruning - The following features were made Proposed Optionalin Java EE 6 and are now made optional.EJB 2.1 and earlier Entity Bean Component Contract for CMPand BMPClient View of an EJB 2.1 and earlier Entity BeanEJB QL: Query Language for CMP Query MethodsJAX-RPC-based Web Service Endpoints and Client ViewThe optional features are moved to a separate document and asa result EJB specification is now split into Core and Optionaldocuments. This allows the specification to be more readableand better organized.Updates and ImprovementsTransactional lifecycle callbacks in Stateful Session Beans,only for CMT. In EJB 3.1, the transaction context for lifecylecallback methods (@PostConstruct, @PreDestroy, @PostActivate,@PrePassivate) are defined as shown.@PostConstruct@PreDestroy@PrePassivate@PostActivateStatelessUnspecifiedUnspecifiedN/AN/AStatefulUnspecifiedUnspecifiedUnspecifiedUnspecifiedSingletonBean's transactionmanagement typeBean's transactionmanagement typeN/AN/AIn EJB 3.2, stateful session bean lifecycle callback methodscan opt-in to be transactional. These methods are thenexecuted in a transaction context as shown.@PostConstruct@PreDestroy @PrePassivate @PostActivate Stateless UnspecifiedUnspecifiedN/AN/AStateful Bean's transactionmanagement typeBean's transactionmanagement typeBean's transactionmanagement typeBean's transactionmanagement typeSingleton Bean's transactionmanagement typeBean's transactionmanagement typeN/AN/AFor example, the following stateful session bean require a newtransaction to be started for @PostConstruct and @PreDestroylifecycle callback methods.@Statefulpublic class HelloBean {   @PersistenceContext(type=PersistenceContextType.EXTENDED)   private EntityManager em;   @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)   @PostConstruct   public void init() {        myEntity = em.find(...);   }   @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)   @PostConstruct   public void destroy() {       em.flush();   }}Notice, by default the lifecycle callback methods are nottransactional for backwards compatibility. They need to beexplicitly opt-in to be made transactional.Opt-out of passivation for stateful session bean - If yourstateful session bean needs to stick around or it hasnon-serializable field then the bean can be opt-out ofpassivation as shown.@Stateful(passivationCapable=false)public class HelloBean {    private NonSerializableType ref = ... . . .}Simplified the rules to define all local/remote views of thebean. For example, if the bean is defined as:@Statelesspublic class Bean implements Foo, Bar {    . . .}where Foo and Bar have no annotations of their own, then Fooand Bar are exposed as local views of the bean. The bean maybe explicitly marked @Local as@Local@Statelesspublic class Bean implements Foo, Bar {    . . .}then this is the same behavior as explained above, i.e. Fooand Bar are local views.If the bean is marked @Remote as:@Remote@Statelesspublic class Bean implements Foo, Bar {    . . .}then Foo and Bar are remote views. If an interface is marked@Local or @Remote then each interface need to be explicitlymarked explicitly to be exposed as a view. For example:@Remotepublic interface Foo { . . . }@Statelesspublic class Bean implements Foo, Bar {    . . .}only exposes one remote interface Foo.Section 4.9.7 from the specification provide more detailsabout this feature.TimerService.getAllTimers is a newly added convenience APIthat returns all timers in the same bean. This is only fordisplaying the list of timers as the timer can only becanceled by its owner.Removed restriction to obtain the current class loader, andallow to use java.io package. This is handy if you want to dofile access within your beans.JMS 2.0 alignment - A standard list of activation-configproperties is now defineddestinationLookupconnectionFactoryLookupclientIdsubscriptionNameshareSubscriptionsTons of other clarifications through out the spec. AppendixA provide a comprehensive list of changes since EJB 3.1.ThreadContext in Singleton is guaranteed to be thread-safe.Embeddable container implement Autocloseable.A complete replay of EnterpriseJavaBeans Today and Tomorrow from JavaOne 2012 can be seenhere (click on CON4654_mp4_4654_001 in Media).The specification is still evolving so the actual property ormethod names or their actual behavior may be different from thecurrently proposed ones.Are there any improvements that you'd like to see in EJB 3.2 ?The EJB 3.2 Expert Group would love to hearyour feedback. An EarlyDraft of the specification is available. The latest versionof the specification can always be downloaded from here.JavaEE 7 Specification StatusEJB SpecificationProjectJIRA of EJBSpecificationJSRExpert Group Discussion ArchiveThese features will start showing up in GlassFish4 Promoted Builds soon.

EJB 3.1 added a whole ton of features for simplicity and ease-of-use such as @Singleton, @Asynchronous, @Schedule, Portable JNDI name,EJBContainer.createEJBContainer, EJB 3.1 Lite, and many...

General

JPA 2.1 Schema Generation (TOTD #187)

UPDATED: May 24, 2012JPA 2.1 specification is now final and can be download fromhere. The Reference Implementation is integrated in GlassFish4 Promoted Builds (soon to be final). The Schema Generationproperty names have changed since the blog was originally publishedand is now updated in the table below.Blog from Nov 11, 2012This blog explainedsome of the keyfeaturesof JPA 2.1 earlier. Since then Schema Generation has beenadded to JPA 2.1. This Tip Of The Day(TOTD)will provide more details about this new feature in JPA 2.1.Schema Generation refers to generation of database artifacts liketables, indexes, and constraints in a database schema. It may or maynot involve generation of a proper database schema depending uponthe credentials and authorization of the user. This helps inprototyping of your application where the required artifacts aregenerated either prior to application deployment or as part ofEntityManagerFactory creation. This is also useful in environmentsthat require provisioning database on demand, e.g. in a cloud.This feature will allow your JPA domain object model to be directlygenerated in a database. The generated schema may need to be tunedfor actual production environment. This usecase is supported byallowing the schema generation to occur into DDL scripts which canthen be further tuned by a DBA.The following set of properties in persistence.xml or specifiedduring EntityManagerFactory creation controls the behaviour ofschema generation.Property NamePurposeValuesjavax.persistence.schema-generation.database.actionSpecifies the action to be taken by thepersistence provider with regard to the database artifactsPer.book"none", "create", "drop-and-create", "drop"javax.persistence.schema-generation.scripts.actionSpecifies which scripts are to be generatedby the persistence providerPer.book"none", "create", "drop-and-create", "drop"javax.persistence.schema-generation.create-sourcejavax.persistence.schema-generation.drop-source Specifies whether the creation/dropping ofdatabase artifacts is to occur on the basis of theobject/relational mapping metadata, DDL script, or acombination of the two."metadata", "script", "metadata-then-script","script-then-metadata"javax.persistence.schema-generation.create-database-schemasSpecifies whether the persistence provider isto create the database schema(s) in addi- tion to creatingdatabase objects such as tables, sequences, constraints,etc."true", "false"javax.persistence.schema-generation.scripts.create-targetjavax.persistence.schema-generation.scripts.drop-targetIf scripts are to be generated, controlstarget locations for writing of scripts. Writers arepre-configured for the persistence provider. Need to bespecified only if scripts are to be generated.java.io.Writer (e.g. MyWriter.class) or URLstringsjavax.persistence.database-product-name, javax.persistence.database-major-version,javax.persistence.database-minor-versionNeeded if scripts are to be generated and noconnection to target database. Values are those obtainedfrom JDBC DatabaseMetaData. javax.persistence.schema-generation.scripts.create-script-sourcejavax.persistence.schema-generation.scripts.drop-script-sourceSpecifies locations from which DDL scriptsare to be read. Readers are pre-configured for thepersistence provider. java.io.Reader (e.g. MyReader.class) or URLstringsjavax.persistence.schema-generation.connectionJDBC connection to be used for schemagenerationjavax.persistence.sql-load-script-sourceSpecifies location of SQL bulk load script.java.io.Reader (e.g. MyReader.class) or URLstringSection 11.2 in the JPA2.1specification defines the annotations used for schemageneration process. For example, @Table, @Column, @CollectionTable,@JoinTable, @JoinColumn, are used to define the generated schema.Several layers of defaulting may be involved. For example, the tablename is defaulted from entity name and entity name (which can bespecified explicitly as well) is defaulted from the class name.However annotations may be used to override or customize the values.The following entity class:@Entity public class Employee {    @Id private int id;    private String name;    . . .    @ManyToOne    private Department dept;}is generated in the database with the following attributes:Maps to EMPLOYEE table in default schema"id" field is mapped to ID column as primary key"name" is mapped to NAME column with a default VARCHAR(255).The length of this field can be easily tuned using @Column.@ManyToOne is mapped to DEPT_ID foreign key column. Can becustomized using JOIN_COLUMN.In addition to these properties, couple of new annotations areadded to JPA 2.1:@Index - An index for the primary key is generated by defaultin a database. This new annotation will allow to defineadditional indexes, over a single or multiple columns, for abetter performance. This is specified as part of @Table,@SecondaryTable, @CollectionTable, @JoinTable, and@TableGenerator. For example:@Table(indexes = {@Index(columnList="NAME"), @Index(columnList="DEPT_ID DESC")})@Entity public class Employee {    . . .}The generated table will have a default index on the primarykey. In addition, two new indexes are defined on the NAME column(default ascending) and the foreign key that maps to thedepartment in descending order.@ForeignKey - It is used to define foreign key constraint orto otherwise override or disable the persistence provider'sdefault foreign key definition. Can be specified as part ofJoinColumn(s), MapKeyJoinColumn(s), PrimaryKeyJoinColumn(s). Forexample:@Entity public class Employee {    @Id private int id;    private String name;    @ManyToOne    @JoinColumn(foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (MANAGER_ID) REFERENCES MANAGER"))    private Manager manager;    . . .}In this entity, the employee's manager is mapped by MANAGER_IDcolumn in the MANAGER table. The value of foreignKeyDefinitionwould be a database specific string.A complete replay of Linda's talk at JavaOne 2012 can be seenhere (click on CON4212_mp4_4212_001 in Media). These features will be available in GlassFish4promoted builds in the near future. The development inEclipseLink is tracked here.JPA 2.1 will be delivered as part of Java EE 7. The differentcomponents in the Java EE 7 platform are trackedhere.JPA 2.1 Expert Group has released EarlyDraft2 of the specification. Section 9.4 and 11.2 provide alldetails about Schema Generation. The latest javadocs can beobtained fromhere. And the JPA EG would appreciatefeedback.

UPDATED: May 24, 2012 JPA 2.1 specification is now final and can be download href="http://jcp.org/aboutJava/communityprocess/final/jsr338/index.html">from here. The Reference Implementation is...

General

Custom Text and Binary Payloads using WebSocket (TOTD #186)

TOTD #185 explained how to process text and binary payloads ina WebSocket endpoint. In summary, a text payload may be received aspublic void receiveTextMessage(String message) {    . . . }And binary payload may be received as:public void recieveBinaryMessage(ByteBuffer message) {    . . .}As you realize, both of these methods receive the text and binarydata in raw format. However you may like to receive and send thedata using a POJO. This marshaling and unmarshaling can be done inthe method implementation but JSR 356 API provides a cleaner way.For encoding and decoding text payload into POJO, Decoder.Text(for inbound payload) and Encoder.Text (for outboundpayload) interfaces need to be implemented.A sample implementation below shows how text payload consisting ofJSON structures can be encoded and decoded.public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> {    private JsonObject jsonObject;    @Override    public MyMessage decode(String string) throws DecodeException {        this.jsonObject = new JsonReader(new StringReader(string)).readObject();               return this;    }    @Override    public boolean willDecode(String string) {        return true;    }    @Override    public String encode(MyMessage myMessage) throws EncodeException {        return myMessage.jsonObject.toString();    } public JsonObject getObject() { return jsonObject; }}In this implementation, the decode method decodesincoming text payload to MyMessage, the encodemethod encodes MyMessage for the outgoing textpayload, and the willDecode method returns trueor false if the message can be decoded.The encoder and decoder implementation classes need to be specifiedin the WebSocket endpoint as:@WebSocketEndpoint(value="/endpoint", encoders={MyMessage.class}, decoders={MyMessage.class})public class MyEndpoint {public MyMessage receiveMessage(MyMessage message) {. . .}}Notice the updated method signature where the application is workingwith MyMessage instead of the raw string.Note that the encoder and decoder implementations just illustratethe point and provide no validation or exception handling. SimilarlyEncooder.Binary and Decoder.Binaryinterfaces need to be implemented for encoding and decoding binarypayload.Here are some references for you:JSR 356:Java API for WebSocket - Specification (EarlyDraft) and Implementation(already integrated in GlassFish4 promoted builds)TOTD#183 - Getting Started with WebSocket in GlassFishTOTD#184 - Logging WebSocket Frames using Chrome DeveloperTools, Net-internals and WiresharkTOTD#185: Processing Text and Binary (Blob, ArrayBuffer,ArrayBufferView) Payload in WebSocketSubsequent blogs will discuss the following topics (not necessary inthat order) ...Error handlingInterface-driven WebSocket endpointJava client APIClient and Server configurationSecuritySubprotocolsExtensionsOther topics from the API

href="https://blogs.oracle.com/arungupta/entry/processing_text_and_binary_payload"> TOTD #185 explained how to process text and binary payloads ina WebSocket endpoint. In summary, a text payload may...

General

Processing Text and Binary (Blob, ArrayBuffer, ArrayBufferView) Payload in WebSocket - (TOTD #185)

The WebSocket APIdefines different send(xxx) methods that can be usedto send text and binary data. This Tip Of TheDay (TOTD) will show how to send and receive text and binarydata using WebSocket.TOTD #183 explains how to get started with a WebSocket endpointusing GlassFish 4. A simple endpoint from that blog looks like:@WebSocketEndpoint("/endpoint")public class MyEndpoint {public void receiveTextMessage(String message) {. . .}}A message with the first parameter of the type Stringis invoked when a text payload is received. The payload of theincoming WebSocket frame is mapped to this first parameter.An optional second parameter, Session, can bespecified to map to the "other end" of this conversation. Forexample:public void receiveTextMessage(String message, Session session) {    . . .}The return type is void and that means no response isreturned to the client that invoked this endpoint. A response may bereturned to the client in two different ways. First, set the returntype to the expected type, such as:public String receiveTextMessage(String message) {String response = . . . . . . return response;}In this case a text payload is returned back to the invokingendpoint.The second way to send a response back is to use the mapped sessionto send response using one of the sendXXX methods in Session,when and if needed.public void receiveTextMessage(String message, Session session) {    . . .    RemoteEndpoint remote = session.getRemote();    remote.sendString(...);    . . .    remote.sendString(...);   . . .   remote.sendString(...);}This shows how duplex and asynchronous communication between the twoendpoints can be achieved. This can be used to define differentmessage exchange patterns between the client and server.The WebSocket client can send the message as:websocket.send(myTextField.value);where myTextField is a text field in the web page.Binary payload in the incoming WebSocket frame can be received if ByteBufferis used as the first parameter of the method signature. The endpointmethod signature in that case would look like:public void receiveBinaryMessage(ByteBuffer message) {    . . .}From the client side, the binary data can be sent using Blob,ArrayBuffer, and ArrayBufferView. Blob isa just raw data and the actual interpretation is left to theapplication. ArrayBuffer and ArrayBufferVieware defined in the TypedArrayspecification and are designed to send binary data usingWebSocket. In short, ArrayBuffer is a fixed-lengthbinary buffer with no format and no mechanism for accessing itscontents. These buffers are manipulated using one of the viewsdefined by one of the subclasses of ArrayBufferViewlisted below:Int8Array (signed 8-bit integer or char)Uint8Array (unsigned 8-bit integer or unsignedchar)Int16Array (signed 16-bit integer or short)Uint16Array (unsigned 16-bit integer or unsignedshort)Int32Array (signed 32-bit integer or int)Uint32Array (unsigned 16-bit integer or unsignedint)Float32Array (signed 32-bit float or float)Float64Array (signed 64-bit float or double)WebSocket can send binary data using ArrayBuffer witha view defined by a subclass of ArrayBufferView or asubclass of ArrayBufferView itself.The WebSocket client can send the message using Blob as:blob = new Blob([myField2.value]);websocket.send(blob);where myField2 is a text field in the web page.The WebSocket client can send the message using ArrayBufferas:var buffer = new ArrayBuffer(10);var bytes = new Uint8Array(buffer);for (var i=0; i<bytes.length; i++) { bytes[i] = i;}websocket.send(buffer);A concrete implementation of receiving the binary message may looklike:@WebSocketMessagepublic void echoBinary(ByteBuffer data, Session session) throws IOException {    System.out.println("echoBinary: " + data);    for (byte b : data.array()) {        System.out.print(b);    }    session.getRemote().sendBytes(data);}This method is just printing the binary data for verification butyou may actually be storing it in a database or converting to animage or something more meaningful.Be aware of TYRUS-51if you are trying to send binary data from server to client usingmethod return type.Here are some references for you:JSR 356:Java API for WebSocket - Specification (EarlyDraft) and Implementation(already integrated in GlassFish4 promoted builds)TOTD#183 - Getting Started with WebSocket in GlassFishTOTD#184 - Logging WebSocket Frames using Chrome DeveloperTools, Net-internals and WiresharkSubsequent blogs will discuss the following topics (not necessary inthat order) ...Error handlingCustom payloads using encoder/decoderInterface-driven WebSocket endpointJava client APIClient and Server configurationSecuritySubprotocolsExtensionsOther topics from the API

The WebSocket API defines different send(xxx) methods that can be used to send text and binary data. This Tip Of TheDay (TOTD) will show how to send and receive text and binary data using WebSocket.hr...

General

Logging WebSocket Frames using Chrome Developer Tools, Net-internals and Wireshark (TOTD #184)

TOTD#183 explained how to build a WebSocket-driven applicationusing GlassFish 4. This Tip Of The Day(TOTD) will explain how do view/debug on-the-wire messages, orframes as they are called in WebSocket parlance, over this upgradedconnection. This blog will use the application built in TOTD#183.First of all, make sure you are using a browser that supportsWebSocket. If you recall from TOTD#183 then WebSocket is combination of Protocol and JavaScript API. Abrowser supporting WebSocket, or not, means they understand your webpages with the WebSocket JavaScript. caniuse.com/websocketsprovide a current status of WebSocket support in different browsers.Most of the major browsers such as Chrome, Firefox, Safari alreadysupport WebSocket for the past few versions. As of this writing, IEstill does not support WebSocket however its planned for a futurerelease. Viewing WebSocket farmes require special settings because all thecommunication happens over an upgraded HTTP connection over a singleTCP connection. If you are building your application using Java,then there are two common ways to debug WebSocket messages today.Other language libraries provide different mechanisms to log themessages.Lets get started!ChromeDeveloper Tools provide information about the initialhandshake only. This can be viewed in the Network tab and selectingthe endpoint hosting the WebSocket endpoint.You can also click on "WebSockets" on the bottom-right to show onlythe WebSocket endpoints.Click on "Frames" in the right panel to view the actual frames beingexchanged between the client and server.The frames are not refreshed when new messages are sent or received.You need to refresh the panel by clicking on the endpoint again.To see more detailed information about the WebSocket frames, youneed to type "chrome://net-internals"in a new tab. Click on "Sockets" in the left navigation bar and thenon "View live sockets" to see the page.Select the box with the address to your WebSocket endpoint and seesome basic information about connection and bytes exchanged betweenthe client and the endpoint.Clicking on the blue text "source dependency ..." shows more detailsabout the handshake.If you are interested in viewing the exact payload of WebSocketmessages then you need a network sniffer. These tools are used tosnoop network traffic and provide a lot more details about the rawmessages exchanged over the network. However because they providelot more information so they need to be configured in order to viewthe relevant information. Wireshark (nee Ethereal) is apretty standard tool for sniffing network traffic and will be usedhere. For this blog purpose, we'll assume that the WebSocketendpoint is hosted on the local machine. These tools do allow tosniff traffic across the network though. Wireshark is quite acomprehensive tool and we'll capturetraffic on the loopback address.Start wireshark, select "loopback" and click on "Start".By default, all traffic information on the loopback address isdisplayed. That includes tons of TCP protocol messages, applicationsrunning on your local machines (like GlassFish or Dropbox on mine),and many others. Specify "http" as the filter in the top-left.Invoke the application built in TOTD#183 and click on "Say Hello" button once. The output inwireshark looks likeHere is a description of the messages exchanged:Message #4: Initial HTTP request of the JSP pageMessage #6: Response returning the JSP pageMessage #16: HTTP Upgrade requestMessage #18: Upgrade request acceptedMessage #20: Request faviconMessage #22: Responding with favicon not foundMessage #24: Browser making a WebSocket request to theendpointMessage #26: WebSocket endpoint responding backYou can also use Fiddlerto debug your WebSocket messages.How are you viewing your WebSocket messages ?Here are some references for you:JSR 356: Java API for WebSocket - Specification (EarlyDraft) and Implementation(already integrated in GlassFish4 promoted builds)TOTD#183 - Getting Started with WebSocket in GlassFishSubsequent blogs will discuss the following topics (not necessary inthat order) ...Binary data as payloadCustom payloads using encoder/decoderError handlingInterface-driven WebSocket endpointJava client APIClient and Server configurationSecuritySubprotocolsExtensionsOther topics from the API

href="https://blogs.oracle.com/arungupta/entry/websocket_applications_using_java_jsr">TOTD #183 explained how to build a WebSocket-driven application using GlassFish 4. This Tip Of The Day(TOTD) will...

General

JMaghreb 2012 Trip Report

JMaghreb is theinaugural Java conference organized by Morocco JUG. It is the biggestJava conference in Maghreb(5 countries in North West Africa).Oracle was the exclusive platinum sponsor with several others. Theregistrations had to be closed at 1412 for the free conference andseveral folks were already on the waiting list. Rabat with 531registrations and Casablanca with 426 were the top cities. Somestatistics ...850+ attendees over 2 days, 500+ every day30 sessions were delivered by 18 speakers from 10 differentcountries10 sessions in French and 20 in English6 of the speakers spoke at JavaOne 20128 will be at DevoxxAttendees from 5 different countries and 57 cities in Morocco40.9% qualified them as professional and rest as studentsTopics ranged from HTML5, Java EE 7, ADF, JavaFX, MySQL, JCP,Vaadin, Android, Community, JCP Java EE 6 hands-on lab was sold out within 7 minutes andJavaFX in 12 minutesI gave the keynote along with Simon Ritter which was basically arecap of the Strategyand Technicalkeynotes presented at JavaOne 2012.An informal survey during the keynote showed the following numbers:25% using NetBeans, 90% on Eclipse, 3 on JDeveloper, 1 onIntelliJAbout 10 subscribers to free online Javamagazine. This digital magazine is a comprehensive sourceof information for everything Java - subscribefor free!!About 10-15% using Java SE 7. DownloadJDK 7 and get started today! Even JDK 8 buildshave been available for a while now.My second talk explained the core concepts of WebSocket and how JSR 356 isproviding a standard API to build WebSocket-driven applications inJava EE 7. TOTD#183 explains how you can easily get started with WebSocket inGlassFish4. The complete slide deck is available: Next day started with a community keynote by Sonya Barry. Some of uslive the life of JCP, JSR, EG, EC, RI, etc every day, but not everybody is. To address that, Sonya prepared an excellent introductorypresentation providing an explanation of these terms and howjava.net infrastructure supports Java development.The registration for the lab showed there is a definite demand forthese technologies in this part of the world. I delivered the JavaEE 6 hands-on lab to a packed room of about 120 attendees. Most ofthe attendees were able to progress and follow the lab instructions.Some of the attendees did not have a laptop but were takingextensive notes on paper notepads. Several attendees were alreadyusing Java EE 6 in their projects and typically they are the onesasking deep dive questions. Also gave out three copies of myrecently released JavaEE 6 Pocket Guide and new GlassFisht-shirts. Definitely feels happy to coach ~120 more Javadevelopers learn standards-based enterprise Java programming.I also participated in a JCP BoF along with Werner, Sonya, and Badr.Adotp-a-JSR, java.net infrastructure, how to file a JSR, what is anRI, and other similar topics were discussed in a candid manner.You can follow @JMaghrebConfor check out their facebookpage. java.net published a timely conversationwith Badr El Houari - the fearless leader of the Morocco JUGteam. Did you know that Morocco JUG stood for JCP EC elections (ADDLINK) ? Even though they did not get elected but did fairly well.Now some sample tweets from #JMaghreb...#JMaghreb is over. Impressive for a first edition! Thanks@badrelhouari and all the @MoroccoJUG team ! Since you @speakjava : System.out.println("Thank you so muchdear Tech Evangelist ! The JavaFX was pretty amazing !!! ");#JMaghreb @YounesVendetta @arungupta @JMaghrebConf Right ! hope hewill be back to morocco again and again .. :) @Alji_ @arungupta @JMaghrebConf That dude is a genius ;) Putit on your wall :p @arungupta rocking Java EE 6 at @JMaghrebConf #Java #JavaEE#JMaghreb http://t.co/isl0Iq5p @sonyabarry you are an awesome speaker ;-) #JMaghreb rich more than 550 attendees in day one. Expectingmore tomorrow! ongratulations @badrelhouari the organisation was great! Thetalks were pretty interesting, and the turnout was surprising at#JMaghreb! #JMaghreb is truly awesome... The speakers are unbelievable! #JavaFX... Just amazing #JMaghreb Charmed by the talk about #javaFX ( nodes architecture, MVC,Lazy loading, binding... ) gotta start using it intead of SWT.#JMaghreb JavaFX is killing JFreeChart. It supports Charts a lot ofkind of them ... #JMaghreb The british man is back #JMaghreb I do like him!! #JMaghreb @arungupta rocking @JMaghrebConf.pic.twitter.com/CNohA3PE @arungupta Great talk about the future of Java EE (JEE 7& JEE 8) Thank you. #JMaghreb JEE7 more mooore power , leeess less code !! #JMaghreb They are simplifying the existing API for Java MessageService 2.0 #JMaghreb good to know , the more the code issimplified the better ! The Glassdoor guy #arungupta is doing it RIGHT ! #JMaghreb Great presentation of The Future of the Java Platform: JavaEE 7, Java SE 8 & Beyond #jMaghreb @arungupta is a great Guy apparently #JMaghrebOn a personal front, the hotel (Soiftel Jardin des Roses) was prettynice and the location was perfect. There was a 1.8 mile loop dirttrail right next to it so I managed to squeeze some runs before my upcoming marathon. Also enjoyedsome great Moroccan cuisine - Couscous, Tajine, mint tea,and moroccan salad. Visit to Kasbah ofthe Udayas, Hassan II(one of the tallestmosque in the world), and eating in a restaurant in a kasbahare some of the exciting local experiences.Now some pictures from the event (and around the city) ... And the complete album: Many thanks to Badr, Faisal, and rest of the team for organizing agreat conference. They are already thinking about how to improve thecontent, logisitics, and flow for the next year. I'm certainlylooking forward to JMaghreb 2.0 :-)

src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/4ca77c7e09d6a2d6e2d0439c330f45a0/jmaghreb_2012.png"height="217"...

General

Java EE 7 Status Update - November 2012

Here is a quick status update on different components that aretargeted to be included in the Java EE 7 Platform.UPDATE: Latest status tracked here.Java EE 7 Platform (JSR 342) - EarlyDraft2 (list,project,javadocs ?)Java Persistence API 2.1 (JSR 338) - EarlyDraft2 (list,project, javadocs?)Java API for RESTful Web Services 2.0 (JSR 339) - PublicReview (list,project, javadocs)Servlets 3.1 (JSR340) - EarlyDraft (list,project, javadocs?)Expression Language 3.0 (JSR 341) - PublicReview (list,project, javadocs?)Java Message Service 2.0 (JSR 343) - EarlyDraft (list,project, javadocs)JavaServer Faces 2.2 (JSR 344) - EarlyDraft (list,project,javadocs ?)Enterprise JavaBeans 3.2 (JSR 345) -EarlyDraft (list,project,javadocs ?)Context & Dependency Injection 1.1 (JSR 346) - PublicReview (list,project, javadocs)Bean Validation 1.1 (JSR 349) - PublicReview (list,project, javadocs ?)JCACHE Java Temporary Caching API (JSR 107) - EarlyDraft (list,project, javadocs)Batch Applications for the Java Platform (JSR 352) - PublicReview (list,project, javadocs)Java API for JSON Processing (JSR 353) - EarlyDraft (list,project,javadocs)Java API for WebSocket (JSR 356) - EarlyDraft (list,project, javadocs)As evident, all the components have released at least an Early Draftspecification. Some have released second Early Draft and some evenhave a Public Review in different stages. Several implementationsare already integrated in GlassFish4. Promoted Builds.Which ones are you tracking or contributing ?Make sure to file an issue so that your usecase and needs areaddressed. Download GlassFish4. Promoted Build and providefeedback.  

Here is a quick status update on different components that are targeted to be included in the Java EE 7 Platform.UPDATE: Latest status tracked here. Java EE 7 Platform (href="http://jcp.org/en/jsr/det...

General

WebSocket Applications using Java: JSR 356 Early Draft Now Available (TOTD #183)

WebSocket provide a full-duplex and bi-directional communicationprotocol over a single TCP connection. JSR 356 is defininga standard API for creating WebSocket applications in the Java EE 7Platform. This Tip Of The Day (TOTD)will provide an introduction to WebSocket and how the JSR isevolving to support the programming model.First, a little primer on WebSocket!WebSocket is a combination of IETF RFC 6455 Protocoland W3C JavaScript API(still a Candidate Recommendation). The protocol defines an openinghandshake and data transfer. The API enables Web pages to use theWebSocket protocol for two-way communication with the remote host.Unlike HTTP, there is no need to create a new TCP connection andsend a chock-full of headers for every message exchange betweenclient and server. The WebSocket protocol defines basic messageframing, layered over TCP. Once the initial handshake happens usingHTTPUpgrade, the client and server can send messages to eachother, independent from the other. There are no pre-defined messageexchange patterns of request/response or one-way between client andand server. These need to be explicitly defined over the basicprotocol.The communication between client and server is pretty symmetric butthere are two differences:A client initiates a connection to a server that is listeningfor a WebSocket request.A client connects to one server using a URI. A server maylisten to requests from multiple clients on the same URI.Other than these two difference, the client and server behavesymmetrically after the opening handshake. In that sense, they areconsidered as "peers".After a successful handshake, clients and servers transfer data backand forth in conceptual units referred as "messages". On the wire, amessage is composed of one or more frames. Application frames carrypayload intended for the application and can be text or binary data.Control frames carry data intended for protocol-level signaling.Now lets talk about the JSR!The Java API forWebSocket is worked upon as JSR 356 in theJava Community Process. This will define a standard API for buildingWebSocket applications. This JSR will provide support for:Creating WebSocket Java components to handle bi-directionalWebSocket conversationsInitiating and intercepting WebSocket eventsCreation and consumption of WebSocket text and binary messagesThe ability to define WebSocket protocols and content modelsfor an applicationConfiguration and management of WebSocket sessions, liketimeouts, retries, cookies, connection poolingSpecification of how WebSocket application will work withinthe Java EE security modelTyrus is the ReferenceImplementation for JSR 356 and is already integrated in GlassFish4.0 Promoted Builds. And finally some code!The API allows to create WebSocket endpoints using annotations andinterface. This TOTD will show a simple sample using annotations. Asubsequent blog will show more advanced samples.A POJO can be converted to a WebSocket endpoint by specifying @WebSocketEndpointand @WebSocketMessage.@WebSocketEndpoint("/hello")public class HelloBean {    @WebSocketMessage    public String sayHello(String name) {        return "Hello " + name + "!";    }}@WebSocketEndpoint marks this class as aWebSocket endpoint listening at URI defined by the valueattribute. The @WebSocketMessage identifies the method thatwill receive the incoming WebSocket message. This first methodparameter is injected with payload of the incoming message. Inthis case it is assumed that the payload is text-based. It canalso be of the type byte[] in case the payload isbinary. A custom object may be specified if decodersattribute is specified in the @WebSocketEndpoint.This attribute will provide a list of classes that define how acustom object can be decoded.This method can also take an optional Sessionparameter. This is injected by the runtime and capture aconversation between two endpoints.The return type of the method can be String, byte[]or a custom object. The encoders attribute on @WebSocketEndpointneed to define how a custom object can be encoded.The client side is an index.jsp with embeddedJavaScript. The JSP body looks like:<div style="text-align: center;"><form action="">    <input onclick="say_hello()" value="Say Hello" type="button">        <input id="nameField" name="name" value="WebSocket" type="text"><br>   </form></div><div id="output"></div>The code is relatively straight forward. It has an HTML form with abutton that invokes say_hello() method and a textfield named nameField. A div placeholderis available for displaying the output.Now, lets take a look at some JavaScript code:<script language="javascript" type="text/javascript">var wsUri = "ws://localhost:8080/HelloWebSocket/hello";    var websocket = new WebSocket(wsUri);    websocket.onopen = function(evt) { onOpen(evt) };    websocket.onmessage = function(evt) { onMessage(evt) };    websocket.onerror = function(evt) { onError(evt) };    function init() {        output = document.getElementById("output");    }    function say_hello() {     websocket.send(nameField.value);        writeToScreen("SENT: " + nameField.value);    }This application is deployed as "HelloWebSocket.war" (downloadhere) on GlassFish4.0 promoted build 57. So the WebSocket endpoint islistening at "ws://localhost:8080/HelloWebSocket/hello". A newWebSocket connection is initiated by specifying the URI toconnect to.The JavaScript API defines callback methods that are invokedwhen the connection is opened (onOpen), closed (onClose),error received (onError), or a message from theendpoint is received (onMessage).The client API has several send methods thattransmit data over the connection. This particular script sendstext data in the say_hello method using nameFieldsvalue from the HTML shown earlier.Each click on the button sends the textbox content to theendpoint over a WebSocket connection and receives a responsebased upon implementation in the sayHello methodshown above.How to test this out ?Download the entire source project hereor just the WARfile. Download GlassFish4.0build 57 or laterand unzip.Start GlassFish as "asadmin start-domain".Deploy the WAR file as "asadmin deploy HelloWebSocket.war".Access the application at http://localhost:8080/HelloWebSocket/index.jsp.After clicking on "Say Hello" button, the output would look like:Here are some references for you:WebSocket - Protocoland JavaScript APIJSR 356: Java API for WebSocket - Specification (EarlyDraft) and Implementation(already integrated in GlassFish4 promoted builds)Subsequent blogs will discuss the following topics (not necessary inthat order) ...Binary data as payloadCustom payloads using encoder/decoderError handlingInterface-driven WebSocket endpointJava client APIClient and Server configurationSecuritySubprotocolsExtensionsOther topics from the APICapturing WebSocket on-the-wire messages

WebSocket provide a full-duplex and bi-directional communication protocol over a single TCP connection. href="http://jcp.org/en/jsr/detail?id=356">JSR 356 is defininga standard API for creating...

General

JavaOne 2012 Keynote and GlassFish Party Pictures

Some pictures from the keynote ...And some pictures from the GlassFish Party ...And the evolving album ...

Some pictures from the keynote ... src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/ca1c8566edc89b0aa895e3dcf21d3708/dscn3449.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/8e9a8e390ec13611a93d5912cbfccc1c/dscn3453.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/01eb2fb17e138f6db27c36b502515de2/dscn3455.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/3e5f82897497618bc0d94f3c74a228bf/dscn3454.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/51206a8f05281f87cd3b1d096c13d9fc/dscn3459.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/37df2db763a1b30ee797d681ddc21d42/dscn3460.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/fbfdf6549ffe4cf87daf33a3cd432dd0/dscn3462.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/327cff3894283d1b66ebc0c394c5b4a1/dscn3471.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/a5310391c5a8f9f6b25a09193cae79b9/dscn3477.jpg" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/f54311008bae24817c86e24a2f39dbfe/dscn3479.jpg" height="216" width="288"> And some pictures from the GlassFish Party ... src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/3b38311e9c79d4c27ccab87405d79e64/dscn3483.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/3ab020066d4ebcbf0e61b430e58005fc/dscn3484.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/ba7cc60b854b43abab347f8be4efc6b5/dscn3488.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/5c44903de8fe179dd6695adf6987bc84/dscn3491.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/dfe8fbb05bbf195909f3b42a5c67ed08/dscn3495.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/08f5c997b88dd96225c4c674dd8ab414/dscn3497.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/66c46be4993c3016fe746b705060c19e/dscn3499.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/52def0c7fddc655fc909fdfbf2ca959e/dscn3504.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/411223b620dd91c97c4117c87b1ef00c/dscn3505.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/eff30dd77e490cd97821c9318d165db1/dscn3506.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/25382324caf3915d734cbf989daed85e/dscn3485.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/255ca536cdbe3f29089459bf952af161/dscn3509.JPG" height="216" width="288"> And the evolving album ... src="https://picasaweb.google.com/s/c/bin/slideshow.swf" flashvars="host=picasaweb.google.com&hl=en_US&feat=flashalbum&RGB=0x000000&feed=https%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2F101195212405190467512%2Falbumid%2F5793791164753144705%3Falt%3Drss%26kind%3Dphoto%26hl%3Den_US" pluginspage="http://www.macromedia.com/go/getflashplayer" height="192" width="288">

General

JavaOne 2012 Pictures - Java Leaders Brunch and GlassFish Community Event

Some pictures from the Java Leaders Brunch ...And some pictures from the GlassFish Community Event (with 110+attendees) ...And the evolving album ...

Some pictures from the Java Leaders Brunch ... src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/8a64aebcf0e8c823a8720ffae6504540/dscn3417.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/fa433814e48ab3634885985fcefc344e/dscn3418.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/f0bb9af24a092d589fcc749e325722fd/dscn3419.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/da7874399b32de20242d540c44623ded/dscn3421.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/9e97fdb3ebc423383d411e3343efb600/dscn3427.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/8936cefeff5c4c3e74c3183839b9fac4/dscn3431.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/53f70edc82b19db6a9bfa4a47773d8e0/dscn3422.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/c844b59235e9a37e1248fd76f855fc17/dscn3424.JPG" height="216" width="288"> And some pictures from the GlassFish Community Event (with 110+ attendees) ... src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/d5b8a57f256164ea8e988541e871d170/dscn3433.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/484c2310fbd29a4da4fb69fb8ee1d78f/dscn3434.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/8eb090e367ca6551c6c78c107ec68ef9/dscn3440.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/1e2d03f4da6d509a696fd13f9923f08a/dscn3443.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/d21e4aced9cd6ddd8a4566d680311f64/dscn3439.JPG" height="216" width="288"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/1f76e43d31638d20066879b071fe492c/dscn3444.JPG" height="216" width="288"> And the evolving album ... src="https://picasaweb.google.com/s/c/bin/slideshow.swf" flashvars="host=picasaweb.google.com&hl=en_US&feat=flashalbum&RGB=0x000000&feed=https%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2F101195212405190467512%2Falbumid%2F5793791164753144705%3Falt%3Drss%26kind%3Dphoto%26hl%3Den_US" pluginspage="http://www.macromedia.com/go/getflashplayer" height="192" width="288">

General

Java EE 6 Pocket Guide from O'Reilly - Now Available in Paperback and Kindle Edition

Hot off the press ...Java EE 6Pocket Guide from 'OReilly Media is now availablein Paperback and Kindle Edition. Here are the book details:Release Date: Sep 21, 2012Language: EnglishPages: 208 Print ISBN: 978-1-4493-3668-4 | ISBN 10:1-4493-3668-X Ebook ISBN:978-1-4493-3667-7 | ISBN 10:1-4493-3667-1 The book provides a comprehensive summary ofthe Java EE 6 platform. Main features of differenttechnologies from the platform are explained and accompaniedby tons of samples. A chapter is dedicated to Managed Beans,Servlets, Java Persistence API, Enterprise JavaBeans,Contexts and Dependency Injection, JavaServer Faces,SOAP-Based Web Services, RESTful Web Services, Java MessageService, and Bean Validation in that format.Many thanks to MarkusEisele, JohnYeary, and BertErtman for reviewing and providing valuable comments.This book was not possible without their extensive feedback!This book was mostly written by compiling my blogs,material from 2-dayworkshops,and severalhands-onworkshopsaroundtheworld.The interactions with users of different technologies andwhiteboard discussions with different specification leadshelped me understand the technology better. Many thanks tothem for helping me be a better user!The long international flights during my travelaroundtheworldproved extremely useful for authoring the content. No phone,no email, no IM, food served on the table, power outlet = aperfect recipe for authoring ;-) Markus wrote a detailedreview of the book. He was one of the manuscript reviewers ofthe book as well and provided valuable guidance. Some excerpts fromhis blog:It covers the basics you need to know of Java EE 6 and gives goodexamples of all relevant parts....This is a pocket guide which is comprehensively written. Icould follow all examples and it was a good read overall. Nocomplicated constructs and clear writing....GO GET IT! It is the only book you probably will need aboutJava EE 6! It is comprehensive, wonderfully written and coverseverything you need in your daily work. It is not a completereference but provides a great shortcut to the things you need toknow. To me it is a good beginners guide and also works as acompanion for advanced users.Here is the first tweet feedback ...Jeff West was super prompt to place the first pre-order of my book,pretty much the hour it was announced. Thank you Jeff!@mike_neck posted the veryfirst tweet about the book, thanks for that!The book is now available in Paperback and Kindle Edition from thefollowing websites:O'ReillyMedia (Ebook, Print & Ebook, Print)Amazon.com(Kindle Edition and Paperback)Barnesand NobleOverstock(1% off Amazon)Buy.comBooktopia.comTowerBooksAngus& RobertsonShopping.comHere is how I can use your help:Help spread the word about the bookIf you bought a Paperback or downloaded Kindle Edition, then postyour review here.If you have not bought, then you can buy it at amazon.comand multiple other websites mentioned above.If you are coming to JavaOne, you'll have an opportunity to get afree copy at O'Reilly's booth on Monday (October 1) from 2-3pm.And you can always buy it from the JavaOne Bookstore.I hope you enjoy reading it and learn something new from it or honeyour existing skills. As always, looking forward to your feedback!

Hot off the press ...Java EE 6 Pocket Guide from 'OReilly Media is now href="http://www.amazon.com/Java-EE-6-Pocket-Guide/dp/144933668X/">availablein Paperback and Kindle Edition. Here are the book...

General

25 reasons to attend JavaOne 2012

17th JavaOneis just around the corner, less than 3 weeks away! If you arestill thinking about registering for the conference, here are mytop 25 reasons to attend the conference:Biggest gathering of Java geeks in the worldLatest and greatest content with 475technical sessions/Birds of Feathers/Hands-on labssessions (about 20% more from last year)Reduced number of keynotesto accommodate room for more technical contentNo product pitches, exclusive focus on technology (I can tellyou that from my experience as a tracklead)Sessions are divided in different in-depthtechnical tracks to focus on Java technology that mostinterests youReruns of several popular sessionsExperts and Practitioners-led HOLs and tutorialsRock star speakers,panelists, faculties, and instructors. Meet several JavaChampions and JUG leadersfrom all around the worldEngage with speakers and discuss with fellow developers in acasual setting with lots of networkingspaceA complete conference dedicated for JavaEmbeddedExtensive and fast-paced hands-on UniversitySessions on Sunday, learn while you are at the conference.You can register for JavaUniversity only or attend with the conference.Dukes Choice Awardsrecognize and celebrate the most innovative usage of the JavaplatformDEMOgroundsand ExhibitionHall provide extensive opportunities for networking andengagement with the biggest names in Java (dedicated hours oneach day as well)Dedicated day for Java User Groups and Communities (GlassFishCommunity Event and NetBeansCommunity Day)Multiple registrationpackages to meet your needsPay for 4 full conference passes and get a fifth one freeStudents and Bloggers get a freepassGeek Bike Ridewith fellow speakers and attendees in a casual settingGreenestconference on the plane Enjoy different cuisines in the San Francisco city, take atrip to Alcatraz or Napa Valley or go running on the crookedstreet ;-) There are tons of tourist opportunities in/around SanFrancisco.Tons of parties during the conference, in the evening, latenight, and early mornings. Don't forget Thirsty BearParty! Pearl Jam and Kings of Leon at AppreciationPartyOracleMusic Festival at Yerba Buena GardensGrab the bragging rights "I have attended JavaOne"!Learn a new skill, build new connections, conceive a new idea andpush the boundaries of Java in the most important educational andnetworking event of the year for Java developers and enthusiasts.With so much geekgasm going on during the 5 days of JavaOne, isthere a reason for you to wait ?Registerfor the conference now!Grab your buttons, banners, and other collateral at JavaOneToolkit.You can also send an email to JavaOneReg@gpj.com.And reach out to us using different social media channels ...As a 13 year veteran of the conference, I can tell this is something every Java developer must experience!I will be there, will you ?

17th JavaOne is just around the corner, less than 3 weeks away! If you are still thinking about registering for the conference, here are my top 25 reasons to attend the conference: Biggest gathering of...

General

Jersey 2 in GlassFish 4 - First Java EE 7 Implementation Now Integrated (TOTD #182)

The JAX-RS 2.0 specification released their EarlyDraft 3 recently. One of my earlierblogs explained as the features were first introduced in thevery first draft of the JAX-RS 2.0 specification. Last week wasanother milestone when the first Java EE 7 specificationimplementation was added to GlassFish 4 builds.Jakub bloggedabout Jersey 2 integration in GlassFish 4 builds. Most of the basicfunctionality is working but EJB, CDI, and Validation are still aTBD. Here is a simple Tip Of The Day(TOTD) sample to get you started with using that functionality.Create a Java EE 6-style Maven projectmvn archetype:generate-DarchetypeGroupId=org.codehaus.mojo.archetypes-DarchetypeArtifactId=webapp-javaee6 -DgroupId=example-DartifactId=jersey2-helloworld -DarchetypeVersion=1.5-DinteractiveMode=falseNote, this is still a Java EE 6 archetype, at least for now.Open the project in NetBeans IDE as it makes it much easier toedit/add the files. Add the following <repositories><repositories> <repository> <id>snapshot-repository.java.net</id> <name>Java.net Snapshot Repository for Maven</name> <url>https://maven.java.net/content/repositories/snapshots/</url> <layout>default</layout> </repository></repositories>Add the following <dependency>s<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope></dependency><dependency> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId> <version>2.0-m09</version> <scope>test</scope></dependency><dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.0-m05</version> <scope>test</scope></dependency>The complete list of Maven coordinates for Jersey2 are availablehere. An up-to-date status of Jersey 2 can always beobtained fromhere.Here is a simple resource class:@Path("movies")public class MoviesResource { @GET @Path("list") public List<Movie> getMovies() { List<Movie> movies = new ArrayList<Movie>(); movies.add(new Movie("Million Dollar Baby", "Hillary Swank")); movies.add(new Movie("Toy Story", "Buzz Light Year")); movies.add(new Movie("Hunger Games", "Jennifer Lawrence")); return movies; }}This resource publishes a list of movies and is accessible at"movies/list" path with HTTP GET. The project is using thestandard JAX-RS APIs. Of course, you need the trivial "Movie" and the "Application"class as well. They are available in the downloadableproject anyway.Build the project mvn packageAnd deploy to GlassFish4.0 promoted build 43 (download, unzip, and start as"bin/asadmin start-domain") asasadmin deploy --force=true target/jersey2-helloworld.warAdd a simple test case by right-clicking on the MoviesResourceclass, select "Tools", "Create Tests", and take defaults.Replace the function "testGetMovies" to@Testpublic void testGetMovies() { System.out.println("getMovies"); Client client = ClientFactory.newClient(); List<Movie> movieList = client.target("http://localhost:8080/jersey2-helloworld/webresources/movies/list") .request() .get(new GenericType<List<Movie>>() {}); assertEquals(3, movieList.size());}This test uses the newly defined JAX-RS 2 client APIs to accessthe RESTful resource.Run the test by giving the command "mvn test" and see theoutput as------------------------------------------------------- T E S T S-------------------------------------------------------Running example.MoviesResourceTestgetMoviesTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.561 secResults :Tests run: 1, Failures: 0, Errors: 0, Skipped: 0GlassFish 4 contains Jersey 2 as the JAX-RS implementation. Ifyou want to use Jersey 1.1 functionality, then Martin'sblog provide more details on that. All JAX-RS 1.xfunctionality will be supported using standard APIs anyway. Thisworkaround is only required if Jersey 1.x functionality needs tobe accessed.The complete source code explained in this project can be downloadedfrom here.Here are some pointers to followJAX-RS2 Specification Early Draft 3Latest status onspecification (jax-rs-spec.java.net)LatestJAX-RS 2.0 JavadocsLatest status on Jersey(Reference Implementation of JAX-RS 2 - jersey.java.net)LatestJersey API JavadocsLatestGlassFish 4.0 Promoted BuildFollow @gf_jerseyProvide feedback on Jersey 2 to users@jersey.java.netand JAX-RS specification to users@jax-rs-spec.java.net.

The JAX-RS 2.0 specification released their href="http://jcp.org/aboutJava/communityprocess/edr/jsr339/index3.html">Early Draft 3 recently. One of my href="https://blogs.oracle.com/arungupta/entry/ja...

General

WebSocket and Java EE 7 - Getting Ready for JSR 356 (TOTD #181)

WebSocket isdeveloped as part of HTML 5 specification and provides abi-directional, full-duplex communication channel over a single TCPsocket. It provides dramatic improvement over the traditionalapproaches of Polling, Long-Polling, and Streaming for two-waycommunication. There is no latency from establishing new TCPconnections for each HTTP message.There is a WebSocket APIand the WebSocketProtocol. The Protocol defines "handshake" and "framing". Thehandshake defines how a normal HTTP connection can be upgraded to aWebSocket connection. The framing defines wire format of themessage. The design philosophy is to keep the framing minimum toavoid the overhead. Both text and binary data can be sent using theAPI.WebSocket may look like a competing technology to Server-Sent Events(SSE), but they are not. Here are the key differences:WebSocket can send and receive data from a client. A typicalexample of WebSocket is a two-player game or a chat application.Server-Sent Events can only push data data to the client. Atypical example of SSE is stock ticker or news feed. With SSE,XMLHttpRequest can be used to send data to the server.For server-only updates, WebSockets has an extra overhead andprogramming can be unecessarily complex. SSE provides a simpleand easy-to-use model that is much better suited.SSEs are sent over traditional HTTP and so no modification isrequired on the server-side. WebSocket require servers thatunderstand the protocol.SSE have several features that are missing from WebSocket suchas automatic reconnection, event IDs, and the ability to sendarbitrary events.The client automatically tries to reconnect if theconnection is closed. The default wait before trying toreconnect is 3 seconds and can be configured by including"retry: XXXX\n" header where XXXX is the milliseconds to waitbefore trying to reconnect.Event stream can include a unique event identifier. Thisallows the server to determine which events need to be firedto each client in case the connection is dropped in between.The data can span multiple lines and can be of any textformat as long as EventSource message handler can process it.WebSockets provide true real-time updates, SSE can beconfigured to provide close to real-time by setting appropriatetimeouts.OK, so all excited about WebSocket ? Want to convert your POJOs intoWebSockets endpoint ?websocket-sdk and GlassFish4.0 is here to help!The complete source code shown in this project can be downloadedhere.On the server-side, the WebSocket SDK converts a POJO into aWebSocket endpoint using simple annotations. Here is how a WebSocketendpoint will look like:@WebSocket(path="/echo")public class EchoBean { @WebSocketMessage public String echo(String message) { return message + " (from your server)"; }}In this code"@WebSocket" is a class-level annotation that declares a POJOto accept WebSocket messages. The path at which the messages areaccepted is specified in this annotation."@WebSocketMessage" indicates the Java method that is invokedwhen the endpoint receives a message. This method implementationechoes the received message concatenated with an additionalstring.The client-side HTML page looks like<div style="text-align: center;"> <form action=""> <input onclick="send_echo()" value="Press me" type="button"> <input id="textID" name="message" value="Hello WebSocket!" type="text"><br> </form></div><div id="output"></div>WebSocket allows a full-duplex communication. So the client, abrowser in this case, can send a message to a server, a WebSocketendpoint in this case. And the server can send a message to theclient at the same time. This is unlike HTTP which follows a"request" followed by a "response". In this code, the "send_echo"method in the JavaScript is invoked on the button click. There isalso a <div> placeholder to display the response from theWebSocket endpoint.The JavaScript looks like:<script language="javascript" type="text/javascript"> var wsUri = "ws://localhost:8080/websockets/echo"; var websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; function init() { output = document.getElementById("output"); } function send_echo() { websocket.send(textID.value); writeToScreen("SENT: " + textID.value); } function onOpen(evt) { writeToScreen("CONNECTED"); } function onMessage(evt) { writeToScreen("RECEIVED: " + evt.data); } function onError(evt) { writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.appendChild(pre); } window.addEventListener("load", init, false);</script>In this codeThe URI to connect to on the server side is of the formatws://<HOST>:<PORT>/websockets/<PATH>"ws" is a new URI scheme introduced by the WebSocket protocol.<PATH> is the path on the endpoint where the WebSocketmessages are accepted. In our case, it isws://localhost:8080/websockets/echoWEBSOCKET_SDK-1will ensure that context root is included in the URI as well.WebSocket is created as a global object so that the connectionis created only once. This object establishes a connection withthe given host, port and the path at which the endpoint islistening.The WebSocket APIdefines several callbacks that can be registered on specificevents. The "onopen", "onmessage", and "onerror" callbacks areregistered in this case. The callbacks print a message on thebrowser indicating which one is called and additionally alsoprints the data sent/received.On the button click, the WebSocket object is used to transmittext data to the endpoint. Binary data can be sent as one blobor using buffering.The HTTP request headers sent for the WebSocket call are:GET ws://localhost:8080/websockets/echo HTTP/1.1Origin: http://localhost:8080Connection: UpgradeSec-WebSocket-Extensions: x-webkit-deflate-frameHost: localhost:8080Sec-WebSocket-Key: mDbnYkAUi0b5Rnal9/cMvQ==Upgrade: websocketSec-WebSocket-Version: 13And the response headers received areConnection:UpgradeSec-WebSocket-Accept:q4nmgFl/lEtU2ocyKZ64dtQvx10=Upgrade:websocket(Challenge Response):00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00The headers are shown in Chrome as shown below:The complete source code shown in this project can be downloadedhere.The builds from websocket-sdkare integrated in GlassFish 4.0 builds. Would you like to live onthe bleeding edge ? Then follow the instructions below to checkout the workspace and install the latest SDK:Check out the source codesvn checkouthttps://svn.java.net/svn/websocket-sdk~source-code-repositoryBuild and install the trunk in your local repository as:mvn installCopy"./bundles/websocket-osgi/target/websocket-osgi-0.3-SNAPSHOT.jar"to "glassfish3/glassfish/modules/websocket-osgi.jar" in your GlassFish4 latest promoted build. Notice, you need to overwrite theJAR file.Anybody interested in building a cool application using WebSocketand get it running on GlassFish ? :-)This work will also feed into JSR 356 - Java API forWebSocket.On a lighter side, there seems to be less agreement on the name.Here are some of the options that are prevalent:WebSocket (W3C API, the URL is www.w3.org/TR/websocketsthough)Web Socket (HTML5 Demos - html5demos.com/web-socket)Websocket (Jenkins Plugin - wiki.jenkins-ci.org/display/JENKINS/Websocket%2BPlugin)WebSockets (Used by Mozilla - developer.mozilla.org/en/WebSockets,but use WebSocket as well)Web sockets (HTML5 Working Group - www.whatwg.org/specs/web-apps/current-work/multipage/network.html)Web Sockets (Chrome Blog - blog.chromium.org/2009/12/web-sockets-now-available-in-google.html)I prefer "WebSocket" as that seems to be most common usage and usedby the W3C API as well. What do you use ?

WebSocket is developed as part of HTML 5 specification and provides a bi-directional, full-duplex communication channel over a single TCP socket. It provides dramatic improvement over the traditionalap...

General

Server-Sent Events using GlassFish (TOTD #180)

Bhakti bloggedabout Server-Sent Events on GlassFish and I've been planning to tryit out for past some days. Finally, I took some time out today tolearn about it and build a simplistic example showcasing the touchpoints.Server-Sent Eventsis developed as part of HTML5 specification and provides pushnotifications from a server to a browser client in the form of DOMevents. It is defined as a cross-browser JavaScript API called EventSource.The client creates an EventSource by requesting aparticular URL and registers an onmessage eventlistener to receive the event notifications. This can be done asshownvar url = 'http://' + document.location.host + '/glassfish-sse/simple';eventSource = new EventSource(url);eventSource.onmessage = function (event) { var theParagraph = document.createElement('p'); theParagraph.innerHTML = event.data.toString(); document.body.appendChild(theParagraph);}This code subscribes to a URL, receives the data in the eventlistener, adds it to a HTML paragraph element, and displays it inthe document. This is where you'll parse JSON and other processingto display if some other data format is received from the URL.The URL to which the EventSource is subscribed to isupdated on the server side and there are multipe ways to do that.GlassFish 4.0 provide support for Server-Sent Events and it can beachieved registering a handler as shown below:@ServerSentEvent("/simple")public class MySimpleHandler extends ServerSentEventHandler { public void sendMessage(String data) { try { connection.sendMessage(data); } catch (IOException ex) { . . . } }}And then events can be sent to this handler using a singletonsession bean as shown:@Startup@Statelesspublic class SimpleEvent { @Inject @ServerSentEventContext("/simple") ServerSentEventHandlerContext<MySimpleHandler> simpleHandlers; @Schedule(hour="*", minute="*", second="*/10") public void sendDate() { for(MySimpleHandler handler : simpleHandlers.getHandlers()) { handler.sendMessage(new Date().toString()); } }}This stateless session bean injects ServerSentEventHandlerslistening on "/simple" path. Note, there may be multiple handlerslistening on this path. The sendDate method triggers every 10seconds and send the current timestamp to all the handlers. Theclient side browser simply displays the string.The HTTP request headers look like:Accept: text/event-streamAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3Accept-Encoding: gzip,deflate,sdchAccept-Language: en-US,en;q=0.8Cache-Control: no-cacheConnection: keep-aliveCookie: JSESSIONID=97ff28773ea6a085e11131acf47bHost: localhost:8080Referer: http://localhost:8080/glassfish-sse/faces/index2.xhtmlUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5And the response headers as:Content-Type: text/event-streamDate: Thu, 14 Jun 2012 21:16:10 GMTServer: GlassFish Server Open Source Edition 4.0Transfer-Encoding: chunkedX-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 4.0 Java/Apple Inc./1.6)Notice, the MIME type of the messages from server to the client is text/event-streamand that is defined by the specification.The code in Bhakti'sblog can be further simplified by using therecently-introduced TwitterAPIfor Java as shown below:@Schedule(hour="*", minute="*", second="*/10") public void sendTweets() { for(MyTwitterHandler handler : twitterHandler.getHandlers()) { String result = twitter.search("glassfish", String.class); handler.sendMessage(result); }} The complete source explained in this blog can be downloadedhere and tried on GlassFish4.0build 34. The latest promoted build can be downloaded fromhere and the complete source code for the API andimplementation is here.I tried this sample on Chrome Version 19.0.1084.54 on Mac OS X 10.7.3.

Bhakti href="http://weblogs.java.net/blog/bhaktimehta/archive/2012/04/21/server-sent-events-sample-glassfish">blogged about Server-Sent Events on GlassFish and I've been planning to tryit out for...

General

Twitter API for Java - Hello Twitter Servlet (TOTD #179)

There are a few TwitterAPIs for Java that allow you to integrate Twitterfunctionality in a Java application. This is yet anotherAPI, built using JAX-RSand Jersey stack. Istarted this effort earlier this year and kept delaying toshare because wanted to provide a more comprehensive API.But I've delayed enough and releasing it as awork-in-progress. I'm happy to take contributions in order to evolve this APIand make it complete, useful, and robust. Drop a comment on theblog if you are interested or ping me at @arungupta.How do you get started ? Just add the following to your "pom.xml":<dependency> <groupId>org.glassfish.samples</groupId> <artifactId>twitter-api</artifactId> <version>1.0-SNAPSHOT</version></dependency>The implementation of this API uses Jersey OAuthFilters for authentication with Twitter and so the followingdependencies are required if any API that requires authentication,which is pretty much all the APIs ;-)<dependency><groupId>com.sun.jersey.contribs.jersey-oauth</groupId>    <artifactId>oauth-client</artifactId>    <version>${jersey.version}</version></dependency><dependency>    <groupId>com.sun.jersey.contribs.jersey-oauth</groupId>    <artifactId>oauth-signature</artifactId>    <version>${jersey.version}</version></dependency> Once the dependencies are added to your project, inject Twitter API in your Servlet (or any other Java EE component) as:@Inject Twitter twitter;Here is a simple non-secure invocation of the API to get youstarted:SearchResults result = twitter.search("glassfish", SearchResults.class);for (SearchResultsTweet t : result.getResults()) { out.println(t.getText() + "<br/>");}This code returns the tweets that matches the query "glassfish".The source code for the complete project can be downloadedhere. Download it, unzip, and mvn package will build the .war file. And then deploy it on GlassFish or any other Java EE 6 compliant application server! The source code for the API also acts as the javadocs and can bechecked out fromhere.Read README.txt for complete details on how to get started.A more detailed sample using security and several other API fromthis library is coming soon!

cellspacing="5"> src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/e4604a9f59a9aa375acc367cf24f672e/twitter_bird_callout.png"> T...

Finance

JEEConf 2012 Trip Report

600+ participants, 3 days, 4 concurrent tracks, 28 sessions, 3workshops, 30+ speakers - a quick summary of JEEConf 2012.This is second year of the conference and they've grown >50% fromlast year.This is the only major Java conference in Ukraine and there is ahuge demand for Java speakers in this region. Even though theconference started with a focus on enterprise Java but hasdiversified into broader Java ecosystem covering Play, Gradle,Hazelcast, Scala, Hadoop, Cassandra, and other topics.I gave a talk on Java EE 7: Developing for the Cloud to about 400+developers. I used the newly refreshed slide deck with tons of codesamples from different technologies such as JAX-RS2.0, JPA2.1, and BeanValidation 1.1. The slide deck is available. Java EE 7: Developing for the Cloud at JEEConf2012 I had the opportunity to spend some time with Yakov Fain, aJava Champion, who gave two day-long workshops on Java EE 6and JavaScript. I also spent some time with Ruslan, CEO of Jelastic and thanked them fortheir continued support of GlassFish. The local JUG is not activebut I learned about Clubof Anonymous Developers where geeks meet couple of times amonth to talk about different technologies. If you live in the localregion, then consider joining this group and learn/share yourexperience.Thank you Nikolai and Alexsey for taking the lead on running a Javaconference in Ukraine. I hope to be back next year!Here are some pictures captured from the trip ...I also managed to run in the streets of Ukraine: And now the complete photo albumNext and last stop in this trip, JavaDeveloper Day, Johannesburg ...

src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/c234a0f430aa3b617a9f462be55bd3cf/jeeconf_2012_logo.png">600+ participants, 3...

General

Geecon 2012 Trip Report

What moved the Java world in Poland ? About 600 participants, 60+sessions, 45+ speakers, and 3 days at Geecon!This was my first time at the conference and they kept me busy :-)I've delivered the self-paced Java EE 6 hands-on lab multiple timesall around the world, but this is the first time where I used thecontent to demonstrate the simplicity and ease-of-use of theplatform in a code-driven session. The 2 hrs were entertaining withconstant interaction from about 50+ attendees. The lab material canbe downloaded from hereanyway.Then right after I gave a talk on Java EE 7: Developing for theCloud. This talk gave an introduction to the upcoming Java EE 7platform to about 50 attendees. And I refreshed the slide deck withtons of code samples from different technologies such as JAX-RS2.0, JPA2.1, and BeanValidation 1.1 that have released their early drafts so far.The slide deck is available. Java EE 7: Developing for the Cloud at Geecon2012 Pete Muir also helped me provide a more thorough insight intoContexts & Dependency Injection 1.1.The talk on JAX-RS 2.0 had about 100+ attendees where I gave anintroduction to JAX-RS, explained the motivation behind upcomingfeatures, and showed code samples of how the API is evolving. Theslide deck is available here.JAX-RS 2.0: RESTful Web services on steroids at Geecon2012And finally the last talk shared our experience of building a PaaSplatform using GlassFish, the slides are available.PaaSinga Java EE 6 Application at Geecon 2012This talk explained the internals of GlassFish and howOrachestration Engine, Service Provisioning Engine, IaaS ManagementService, and Cloud Elasticity Manager work together to provide aJava EE 7-based PaaS environment.Overall, the movie theater-style seating worked well and thetechnical crew knew their job very well. The volunteers were veryprompt in showing the time remaining which was helpful. Everybody inthe conference team gave a very welcome feeling which certainlywants me to go back there again next year (provided they accept mysubmissions ;-) Thank you AdamD (Poznan JUG leader and conferenceorganizer), AdamP, Adrian, Marcin, Lukasz, and everybody else for agreat show! The speakers' dinner was in the old part of the town and I enjoyedsharing stories with Gavin King, Pete Muir, Stephane Eperdaud, AntonArhipov, Joonas Lehtinen, and many others.Here are some pictures captured from the trip ...And the complete album Next stop JEEConf...

What moved the Java world in Poland ? About 600 participants, 60+ sessions, 45+ speakers, and 3 days at href="http://2012.geecon.org/">Geecon!This was my first time at the conference and they kept me...

General

JSON-P: Java API for JSON Processing (TOTD #178)

JSR 353 is JavaAPI for JSON Processing (JSON-P) and will define an API to process(e.g. parse, generate, transform, and query) JSON. This JSR will bedelivered as part of Java EE 7. The API will allow to produce andconsume JSON in a streaming fashion (StAX equivalent in XML world)and build a Java object model for JSON (DOM equivalent in XMLworld). Note, binding JSON to Java objects and vice versa is notpart of the scope of this JSR.json-processing-spec.java.netis where all the specification work is happening and jsonp.java.net is the project forthe  Reference Implementation. Its still early days but this Tip Of The Day (TOTD) will explain how toget started. The workspace can be checked out asgit clone git://java.net/jsonp~gitCloning into jsonp~git...remote: Counting objects: 313, done.remote: Compressing objects: 100% (218/218), done.remote: Total 313 (delta 110), reused 0 (delta 0)Receiving objects: 100% (313/313), 64.13 KiB, done.Resolving deltas: 100% (110/110), done.Building the workspace require JAVA_HOME to be set (/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Homeor /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home).Once set, the workspace can be built asmvn install[INFO] Scanning for projects...[INFO] ------------------------------------------------------------------------[INFO] Reactor Build Order:[INFO] [INFO] RI for JSON-P JSR[INFO] Java API for Processing JSON (JSON-P)[INFO] jsonp-tests[INFO] [INFO] ------------------------------------------------------------------------[INFO] Building RI for JSON-P JSR 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------. . .Tests run: 22, Failures: 0, Errors: 0, Skipped: 0[INFO] [INFO] --- maven-jar-plugin:2.3.1:jar (default-jar) @ jsonp-tests ---[WARNING] JAR will be empty - no content was marked for inclusion![INFO] Building jar: /Users/arungup/code/workspaces/jsonp~git/tests/target/jsonp-tests-1.0-SNAPSHOT.jar[INFO] [INFO] --- maven-install-plugin:2.3.1:install (default-install) @ jsonp-tests ---[INFO] Installing /Users/arungup/code/workspaces/jsonp~git/tests/target/jsonp-tests-1.0-SNAPSHOT.jar to /Users/arungup/.m2/repository/org/glassfish/jsonp-tests/1.0-SNAPSHOT/jsonp-tests-1.0-SNAPSHOT.jar[INFO] Installing /Users/arungup/code/workspaces/jsonp~git/tests/pom.xml to /Users/arungup/.m2/repository/org/glassfish/jsonp-tests/1.0-SNAPSHOT/jsonp-tests-1.0-SNAPSHOT.pom[INFO] ------------------------------------------------------------------------[INFO] Reactor Summary:[INFO] [INFO] RI for JSON-P JSR ................................. SUCCESS [0.528s][INFO] Java API for Processing JSON (JSON-P) ............. SUCCESS [12.214s][INFO] jsonp-tests ....................................... SUCCESS [1.695s][INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------The API .jar file is in api/target/jsonp-ri-1.0-SNAPSHOT.jarand javadocs are in api/target/jsonp-ri-1.0-SNAPSHOT-javadoc.jar.There are several tests in the tests directory thatshows the API usage. The RI JARs are not pushed to a public mavenrepo yet but are installed in the local repo with the above command.These can be included in your "pom.xml" with the followingcoordinates:<dependency> <groupId>javax.json</groupId> <artifactId>jsonp-ri</artifactId> <version>1.0-SNAPSHOT</version></dependency>The key APIs areDOM-based APIs (javax.json package)JsonBuilder - Builds a JSON object or JSON arrayJsonReader - Reads a JSON object or array from the streamJsonWriter - Writes a JSON object or array to the streamStreaming APIs (javax.json.stream package)JsonGenerator - Streaming JSON generatorJsonParser - Allows forward, read-only access to JSONHere is an sample usage of JsonBuilder:JsonObject value = new JsonBuilder()    .beginObject()      .add("firstName", "John")      .add("lastName", "Smith")      .add("age", 25)         .beginObject("address")          .add("streetAddress", "21 2nd Street")           .add("city", "New York")           .add("state", "NY")           .add("postalCode", "10021")         .endObject()        .beginArray("phoneNumber")           .beginObject()              .add("type", "home")              .add("number", "212 555-1234")           .endObject()           .beginObject()              .add("type", "home")              .add("number", "646 555-4567")           .endObject()         .endArray()    .endObject() .build(); Here is a sample usage of JsonReader:String json = "...";JsonReader reader = new JsonReader(new StringReader(json));JsonValue value = reader.readObject();reader.close();A sample usage of JsonWriter:JsonWriter jsonWriter = new JsonWriter(new FileWriter(...));JsonObject jsonObject = new JsonBuilder() .beginObject() . . . .endObject() .build();jsonWriter.writeObject(jsonObject);jsonWriter.close();Here is a sample usage of JsonGenerator:JsonGenerator generator = new JsonGenerator(new FileWriter(...));generator .beginObject() . . . .beginArray() . . . .endArray() .endObject().build();generator.close();And finally a sample usage of JsonParser:String json = "...";JsonParser parser = new JsonParser(new StringReader(json));Iterator<Event> it = reader.iterator();Event event = it.next();The event  can be of the following types:START_OBJECTEND_OBJECTSTART_ARRAYEND_ARRAYKEY_NAMEVALUE_STRINGVALUE_NUMBERVALUE_FALSEVALUE_TRUEVALUE_NULLHere are some references to track the progress and provide feedback:Join the specification project at json-processing-spec.java.netThe Reference Implementation is built at jsonp.java.netMailing Listsusers@json-processing-spec.java.netjsr353-experts@json-processing.java.netIssue Tracker: java.net/jira/browse/JSON_PROCESSING_SPECThis JSR will be delivered as part of Java EE 7. Here are some otherearly work that has been explained:JPA2.1 Early Draft ExplainedJAX-RS2.0 Early Draft ExplainedWhat's new in JSF 2.2?Have fun!

JSR 353 is Java API for JSON Processing (JSON-P) and will define an API to process (e.g. parse, generate, transform, and query) JSON. This JSR will bedelivered as part of Java EE 7. The API will allow...

General

Java Day, Istanbul, May 2012 Trip Report

About 120+ 150attendees at Java Day, Istanbul learned about Java EE 6/7earlier today. The Java track had about 100 110 attendeesduring most ofthe day. I gave 4 sessions:Developing Modern and Lightweight Java EE 6 Applications usingWebLogic 12c (keynote to all the attendees)What's coming in Java EE 7Java EE 6 Hands-on Lab using NetBeans/WebLogicRESTful Web services using JAX-RSThe attendees were generally quiet but the hands-on session hadsome interesting conversations around Java EE 6 usage. TOTD#177 showcase the WebLogic Maven plugin usage TOTD#176 shows how to run Conference Planner application onWebLogic 12c. I also had the opportunity to meet the Istanbul JUG leader and local GTUG leader. Showyour passion about Java by participating at the local JUG, all themore better to volunteer as a speaker :-)The slides presented are available below. WebLogic 12c Developer Deep Diveat Oracle Develop India 2012 Java EE 7: Developing forthe Cloud at Java Day, Istanbul, May 2012 RESTfulWebservices using JAX-RS The self-paced instructions for Java EE 6 hands-on lab usingNetBeans and WebLogic is availablehere.Some pictures from the event and around the city ...Here are a couple of more pictures from the local events team:And the complete album: Next stop Geecon,Poland ...

href="http://www.oracle.com/webapps/events/ns/EventsDetail.jsp?p_eventId=144022&src=7307403&src=7307403&Act=212">alt="" src="" style="border: 0px solid; width: 650px; height: 292px;"> About 120+ 150at...

General

wls-maven-plugin: WebLogic 12c Maven Plugin Usage (TOTD #177)

Oracle WebLogic Server 12c provides full Java EE 6 platformsupport. The screencast#39 shows how to build a complete application using NetBeans.The self-paced hands-on lab provides detailedinstructions on the same as well. The Maven support inWebLogic 12c is much more improved. SteveButton and MarkusEisele wrote detailed blogs on how/what/why of Maven supportin WebLogic. This Tip Of The Day(TOTD) will provide a quick overview of how to get started withusing the maven plugin for deploying a Java EE 6 web application.Download and install WebLogic 12c using the zip installer asexplained in TOTD#174. The Maven plugin can be installed using"$MW_HOME/wlserver/server/lib/wls-maven-plugin.jar". Change thedirectory to "$MW_HOME/wlserver/server/lib" and give thefollowing commands:mvn installmvn install:install-file –Dfile=wls-maven-plugin.jar -DpomFile=pom.xmlThe maven plugin usage can be seen by giving the followingcommand:mvn com.oracle.weblogic:wls-maven-plugin:helpOr add the following to "~/.m2/settings.xml":<pluginGroups>     <pluginGroup>com.oracle.weblogic</pluginGroup></pluginGroups>And then give the following command:mvn wls:helpto see the output as:[INFO] Scanning for projects...[INFO] [INFO] ------------------------------------------------------------------------[INFO] Building wls-maven-sample 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- wls-maven-plugin:12.1.1.0:help (default-cli) @ wls-maven-sample ---[INFO] WebLogic Server Maven PluginThe following goals are supported by wls-maven-plugin:appc: The appc compiler generates and compiles the classes needed to deploy EJBs and JSPs to WebLogic Server. It also validates the deployment descriptors for compliance with the current specifications at both the individual module level and the application level. deploy: To deploy a weblogic server application (supports all formats WAR,JAR etc..)create-domain: Create a domain for WebLogic Server using the default domain template. For more complex domain creation use the WLST goal. help: Provides a list of all the goals supported by the wls-maven-plugin install: Install WebLogic Server list-apps: Lists the deployment names for applications and stand-alone modules deployed distributed, or installed to the domain redeploy: Redeploys a running application or part of a running application start-app: Starts an application deployed on weblogic server. start-server: Start WebLogic Server stop-app: Stops an application stop-server: Stop Weblogic Server undeploy: Undeploys the application from weblogic server. Stops the deployment unit and removes staged files from target servers update-app: Updates an application's deployment plan by redistributing the plan files and reconfiguring the application based on the new plan contents. wlst: WLST wrapper for Maven For detailed help on a goal, use -Dgoal=<goal-name> -Ddetail=true options.[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 0.794s[INFO] Finished at: Thu May 03 06:38:23 IST 2012[INFO] Final Memory: 8M/125M[INFO] ------------------------------------------------------------------------More details about each goal can be found using the followingcommand:mvn wls:help -Dgoal=<GOAL> -Ddetail=trueFor example:mvn wls:help -Dgoal=install -Ddetail=true[INFO] Scanning for projects...[INFO] [INFO] ------------------------------------------------------------------------[INFO] Building Maven Stub Project (No POM) 1[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- wls-maven-plugin:12.1.1.0:help (default-cli) @ standalone-pom ---[INFO] WebLogic Server Maven PluginThe following goals are supported by wls-maven-plugin:install: Install WebLogic Server Available Parameters: installCommand: The command to use to install the product when using an 'executable' installer. The following macros are supported - @INSTALLER_FILE@ - the path to the installer file, @JAVA_HOME@ - path to the java home. eg: @JAVA_HOME@ -Xms512m -Xmx1024m -jar @INSTALLER_FILE@ one two artifactLocation: The address of the artifact. This can be one of the following - 1) A ':' separated maven coordinates of the form (groupId:artifac- tId:packaging:classifier:version) 2) A file on the local system (/home/prash/myapps/helloworld.war)3) A remote http url (http://foo/a/b.zip) middlewareHome: The home directory for Oracle WebLogic Server or Fusion Middleware installation. Required unless WLS was installed in the default location selected by the WLS Maven Plugin's install goal. domainHome: Location of WLS domain localRepository: The absolute path of a local maven repository. artifactFactory: The artifactFactory is used to locate an artifact with a groupId:artifactId:artifactName:version in the remote Repository as provided by the remoteRepsitories parameter. artifactResolver: Artifactresolver resolves the artifact from the remote repository. Downloads an updated version of the artifact if present in the remote repo. [INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 0.889s[INFO] Finished at: Wed May 02 17:35:46 PDT 2012[INFO] Final Memory: 6M/89M[INFO] ------------------------------------------------------------------------Build a Java EE 6 applicationCreate a Java EE 6 Maven web application as:mvn archetype:generate-DarchetypeGroupId=org.codehaus.mojo.archetypes-DarchetypeArtifactId=webapp-javaee6 -DgroupId=example-DartifactId=wls-maven-sample -DarchetypeVersion=1.5-DinteractiveMode=false Add a trivial servlet to the sample project by followingthe screencast#39. The complete source code for the project can be downloadedhere. Add the following code fragment to the generated "pom.xml":<plugin>                <groupId>com.oracle.weblogic</groupId><artifactId>wls-maven-plugin</artifactId><version>12.1.1.0</version></plugin>Try some Maven commands in the "wls-maven-sample" directoryThe server can be started as:mvn wls:start-server -DmiddlewareHome=/Users/arungup/tools/weblogic/12c -DdomainHome=/Users/arungup/tools/weblogic/mydomain[INFO] Scanning for projects...[INFO] [INFO] ------------------------------------------------------------------------[INFO] Building wls-maven-sample 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- wls-maven-plugin:12.1.1.0:start-server (default-cli) @ wls-maven-sample ---[INFO] ++====================================================================++[INFO] ++ wls-maven-plugin: start-server ++[INFO] ++====================================================================++.[INFO] Starting server in domain: /Users/arungup/tools/weblogic/mydomain[INFO] Check stdout file for details: /Users/arungup/tools/weblogic/mydomain/server-922019421247284651.out[INFO] Process being executed, waiting for completion.................[INFO] Server started successful[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 16.919s[INFO] Finished at: Wed May 02 18:06:22 PDT 2012[INFO] Final Memory: 5M/88M[INFO] ------------------------------------------------------------------------Build and deploy the application as:mvn wls:deploy -DmiddlewareHome=/Users/arungup/tools/weblogic/12c -DdomainHome=/Users/arungup/tools/weblogic/mydomain -Duser=admin -Dpassword=admin007 -Dsource=/Users/arungup/code/samples/weblogic/wls-maven-sample/target/wls-maven-sample-1.0-SNAPSHOT.war[INFO] Scanning for projects...[INFO] [INFO] ------------------------------------------------------------------------[INFO] Building wls-maven-sample 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- wls-maven-plugin:12.1.1.0:deploy (default-cli) @ wls-maven-sample ---[INFO] ++====================================================================++[INFO] ++ wls-maven-plugin: deploy ++[INFO] ++====================================================================++weblogic.Deployer invoked with options: -noexit -user admin -deploy -source /Users/arungup/code/samples/weblogic/wls-maven-sample/target/wls-maven-sample-1.0-SNAPSHOT.war<May 3, 2012 8:24:17 AM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating deploy operation for application, wls-maven-sample-1.0-SNAPSHOT [archive: /Users/arungup/code/samples/weblogic/wls-maven-sample/target/wls-maven-sample-1.0-SNAPSHOT.war], to configured targets.> Task 0 initiated: [Deployer:149026]deploy application wls-maven-sample-1.0-SNAPSHOT on myserver.Task 0 completed: [Deployer:149026]deploy application wls-maven-sample-1.0-SNAPSHOT on myserver.Target state: deploy completed on Server myserver[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 7.745s[INFO] Finished at: Thu May 03 08:24:18 IST 2012[INFO] Final Memory: 11M/130M[INFO] ------------------------------------------------------------------------ The application is accessible at localhost:7001/wls-maven-sample-1.0-SNAPSHOT/TestServlet.Stop the server as:mvn wls:stop-server -DmiddlewareHome=/Users/arungup/tools/weblogic/12c -DdomainHome=/Users/arungup/tools/weblogic/mydomain -Duser=admin -Dpassword=admin007[INFO] Scanning for projects...[INFO] [INFO] ------------------------------------------------------------------------[INFO] Building wls-maven-sample 1.0-SNAPSHOT[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- wls-maven-plugin:12.1.1.0:stop-server (default-cli) @ wls-maven-sample ---[INFO] ++====================================================================++[INFO] ++ wls-maven-plugin: stop-server ++[INFO] ++====================================================================++[INFO] Stop server in domain: /Users/arungup/tools/weblogic/mydomain[INFO] Process being executed, waiting for completion.[INFO] [exec] Stopping Weblogic Server...[INFO] [exec] [INFO] [exec] Initializing WebLogic Scripting Tool (WLST) ...[INFO] [exec] [INFO] [exec] Welcome to WebLogic Server Administration Scripting Shell[INFO] [exec] [INFO] [exec] Type help() for help on available commands[INFO] [exec] [INFO] [exec] Connecting to t3://localhost:7001 with userid admin ...[INFO] [exec] Successfully connected to Admin Server 'myserver' that belongs to domain 'mydomain'.[INFO] [exec] [INFO] [exec] Warning: An insecure protocol was used to connect to the [INFO] [exec] server. To ensure on-the-wire security, the SSL port or [INFO] [exec] Admin port should be used instead.[INFO] [exec] [INFO] [exec] Shutting down the server myserver with force=false while connected to myserver ...[INFO] [exec] WLST lost connection to the WebLogic Server that you were [INFO] [exec] connected to, this may happen if the server was shutdown or [INFO] [exec] partitioned. You will have to re-connect to the server once the [INFO] [exec] server is available.[INFO] [exec] Disconnected from weblogic server: myserver[INFO] [exec] Disconnected from weblogic server: [INFO] [exec] [INFO] [exec] [INFO] [exec] Exiting WebLogic Scripting Tool.[INFO] [exec] [INFO] [exec] Done[INFO] [exec] Stopping Derby Server...[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time: 10.847s[INFO] Finished at: Thu May 03 06:37:48 IST 2012[INFO] Final Memory: 9M/125M[INFO] ------------------------------------------------------------------------Simple, quick, and easy!Are you building Java EE 6 applications on WebLogic ? With Maven ?Now you can fully integrate the WebLogic lifecycle with your"pom.xml".The WebLogicApplication Development Guide provide detaileddocumentation on the maven plugin.

href="http://www.oracle.com/technetwork/middleware/weblogic/overview/index.html"> Oracle WebLogic Server 12c provides full Java EE 6 platform support. The href="https://blogs.oracle.com/arungupta/entr...

General

JavaOne and Oracle Develop India 2012 Trip Report

JavaOneand Oracle Develop India 2012 concluded earlier this week.About 2000 attendees for JavaOne makes it the biggest Java developerconference in South Asia. The conference showed Oracle's continuedcommitment to move Java forward and demonstrated progress ondifferent fronts. Several attendees told me that they liked Java EE related sessionsand how it demonstrated how the platform is making progress. Theautomatic service provisioning feature was particularly wellappreciated. The complete instructions to download the ConferencePlanner sample showing some PaaS capabilities of the platform isavailable at glassfish.org/javaone2011.And the video that explains the PaaSing a Java EE application isshown below.I had several speaking engagements at the conference includingTechnical Keynote, Meet The Experts, 2 Hands-on Labs, and 2Technical Sessions.I helped mentor a hands-on lab that explained how toDevelop/Deploy/Monitor a Java EE 6 Application in a GlassFishCluster. The room was packed with 120 attendees and several folksmade good progress by following the instructions in the document.The complete self-paced lab instructions can be downloadedhere and the sourcecode here. The lab explains how to create a 2-instancecluster, front-end the cluster with a load balancer, verify thatsession replication works, and then monitor the application usingJavaScript.The session on GlassFish REST Administration Backend explained theinternals of how GlassFish exposes a RESTful API for administration,monitoring, and management. But other than learning internals, theemphasis was more on how to build a large-scale RESTful application.The tips and tricks part of the presentation shared the lessonslearned during our exercise of publishing this API. The slides areavailable: GlassFish REST Administration Backend atJavaOne India 2012 Do you know the RESTful management API is at localhost:4848/management/domainand the monitoring API is localhost:4848/monitoring/domain.And did you know that you can append ".xml" or ".json" to theRESTful URIs and the data is displayed in the requested format ?The evening concluded with a dinner with several JUG leaders andJava Champions from all around the world. There was Kevin Nilsonfrom the Silicon Valley JUG, Vinicius and Yara Senger from theSouJava, Stephen Chin from the Java FX User Group, Raj Mahendra fromthe JUG Chennai, Kayal from JDuchess Chennai, Murali Vallath fromAIOUG and several other luminaries. However its still surprisinglyshocking that in a country of 1.2 billion+ people, there are only 4active JUGs - Pune, Bangalore, Chennai, and Nagpur. And then Hyderabad JUG was created atJavaOne India. I plan to write a detailed blog on what it takes tostart a JUG any where and hopefully that will motivate someindividuals to start more JUGs around the world. Anyway, here aresome pictures from the dinner:Day 2 for me started with Meet The Experts session with DaliborTopic, Terrence Barr, Michael Heinrichs, and Markus Hirt. The 9amsession started low on attendance but the 250+ capacity room was packed within 15minutes. And the questions ranged from merged JVMs, comparisonbetween HTML5 and JavaFX, NoSQL support in Java EE, JavaFX onmobile, features in JDK 8/9/10, Project Avatar, and all over theJava landscape. The engaged audience kept asking questions all theway to the end.Then I delivered a session on WebLogic 12c: Developer Deep Dive atOracle Develop. This session gave an overview of some of the newfeatures that are available in Oracle WebLogic Server 12c such aszip installer (TOTD#174), simplified programming model with Java EE 6, new Mavengoals, and extensive IDE support. The slides are available. WebLogic 12c Developer Deep Diveat Oracle Develop India 2012 A comprehensive Java EE 6 application was explained with a codewalk-through and deployed on WebLogic server using NetBeans. TOTD#176 explains how you can deploy this application on WebLogicas well. There are several blogs that explain new Maven support inWebLogic and I've already prepared a blog draft (to be publishedsoon) explaining the same using the TOTD format. There were somecases of Websphere -> WebLogic migration and that is alwayswelcome!The final session of the day for me was the Java EE 6 ApplicationDevelopment using NetBeans and WebLogic hands-on lab at OracleDevelop. This self-paced guided the attendees to build a completeend-to-end application using different Java EE 6 technologies suchas JavaServer Faces 2, Enterprise JavaBeans 3.1, Java PersistenceAPI 2, and Contexts & Dependency Injection. The self-paced labinstructions are availablehere. I was told that with about 75 attendees this was themost heavily attended lab of Oracle Develop.The evening concluded with the GlassFish & Friends Party. We'veconducted this party at the premier JavaOne event for the past 5years and this is the first time we've taken it to a regional event.There were about 110+ JavaOne attendees who were present at theparty and had some great conversations. Several folks told me thatthey enjoyed the party and are already looking forward to it nextyear. The Nagpur JUG had the biggest presence at the party and theyare a charged up bunch of folks. I really wish other cities havesimilar amount of passion and energy as well. Here are some picturesfrom the party:On a personal side, the fitness center of Novotel Hotel is prettygood and this allowed me to continue following the SpartacusWorkout. A visit to Hyderabad must include a trip to Paradise Biryani and somanaged to sneak in that after the GlassFish party. The OTN welcomeparty was a good way to decompress at the end of Day 1 and got theattendees dancing to the latest bollywood flicks by Vasundhara Das.Here are some pictures from the dance party:Here are some more pictures captured from the event:And now the complete album: Many thanks to the Novotel Hotel and HICC staff, competent technicalcrew, events team running around for logistics, attendees, local andinternational speakers, and everybody else. A good conference is ablend of all of these together and JavaOne India certainly had agood mix.For me, the next stops are Turkey,Poland, Ukraine, Johannesburg...

JavaOne and Oracle Develop India 2012 concluded earlier this week. About 2000 attendees for JavaOne makes it the biggest Java developerconference in South Asia. The conference showed...

General

Java EE 6 Sample Application on WebLogic 12c: Conference Planner (TOTD #176)

OracleWebLogic 12c provide a Java EE 6 Full Platform compliantapplication server. During the launchevent last year, a Java EE 6 application was shown thatdemonstrated all the features of Java EE 6. This application allowsconference organizers to publish details about their conference suchas tracks, sessions, and speakers. It also allows attendees toregister for the conference and prepare their schedule. Theapplication is built as a typical 3-tier Java EE 6 application usingJavaServer Faces (with PrimeFaces widgets) for the front-end,Enterprise JavaBeans for the middle tier business logic, and JavaPersistence API for connectivity with the database.This Tip Of The Day(TOTD) shows how to deploy the application on WebLogic 12c.Check out the application from svn.java.net/svn/glassfish~svn/branches/arun/ConferencePlanner/trunk/or download the sourcebundle.Download and install ApacheDerby. If you are using JDK7 then it comes bundled withDerby and installed in directory(/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home/db).Any other database can be used as well but the instructions willdiffer accordingly.Create "derby.properties" file in the main directory of andspecify the following content:#derby.user.sa=saThis creates a user "sa" with the password "sa".Start the database by invoking the "bin/startNetworkServer"script.Copy "derbyclient.jar" to "mydomain/lib" directory andrestart the server by using "mydomain/startWeblogic.sh"script.Create and populate the database by invoking the interactiveSQL scripting tool "bin/ij". Specify the location of the SQLfrom the application as shown../ijij version 10.8ij> driver 'org.apache.derby.jdbc.ClientDriver';ij> connect 'jdbc:derby://localhost:1527/cp;ServerName=localhost;databaseName=cp;user=sa;password=sa;create=true';ij> run '/Users/arungup/code/workspaces/arun/ConferencePlanner/trunk/src/main/sql/javaone-sf-2011.sql';ij> . . .1 row inserted/updated/deletedij> exit;Download,unzip, and configure WebLogic 12c as described in TOTD#174. Here is my simple script that performs all the stepsrequired:mkdir 12ccd 12cexport CLASSPATH=/Users/arungup/tools/db-derby-10.8.2.2-bin/lib/derbyclient.jarunzip ~/Downloads/wls1211_dev.zipexport JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home./configure.sh. $MW_HOME/wlserver/server/bin/setWLSEnv.shcd ..mkdir mydomaincd mydomain$JAVA_HOME/bin/java $JAVA_OPTIONS -Xmx1024m -XX:MaxPermSize=256m weblogic.ServerNotice, here we are explicitly including "derbyclient.jar" inthe  CLASSPATH. This will ensure that Derby database's JDBCdriver is available to WebLogic Administration Console which wasnot able to pick up JAR files from "mydomain/lib" directoryotherwise.Access WebLogic Admin Console at localhost:7001/console,the login/password used in TOTD#174 is admin/admin007.Create a JDBC data sourceClick on "Data Sources" as shown.Click on "New" and select "Generic Data Source" as shown.Specify the values as shown.The JDBC resource name is "jdbc/cp" and the database is"Derby".Change the "Database Driver" to "Derby's Driver (Type 4)Versions: Any" and click on "Next". Make sure to not chooseType 4 XA driver which is the default.Take the defaults and select "Next".Specify the connection properties as shown.And click on "Next".Click on "Test Configuration" to make sure that every thingis configured correctly. Make sure to see the message"Connection test succeeded.". Verify the defaults and click on"Next".Select the target "myserver" as shownand click on "Finish".Deploy the applicationIn the localhost:7001/console, click on "Home" (at the topcenter) and then "Deployments".Click on "Install".Specify the location of the WAR file as shownMake sure to pick the WAR file by selecting the radio buttonand click on "Next".Take the defaults and click on "Next".Take the defaults again and click on "Next". Notice that"myserver" is chosen as the target of deployment.Click on "Finish". After the application is deployed theconsole shows the following snapshot:Access the application at localhost:7001/ConferencePlanner tosee the output as:Feel free to browse through the source code!DownloadWebLogic and play with it! Screencast#39 explains how to build a more comprehensive Java EE 6application using NetBeans andWebLogic.

href="http://www.oracle.com/technetwork/middleware/weblogic/overview/index.html">Oracle WebLogic 12c provide a Java EE 6 Full Platform compliant application server. During the href="https://event.on24...

General

Chennai Java Summit 2012 Trip Report

I attended my first Chennai Java Summitlast weekend.The one-day conference had two parallel tracks. The conference wasorganized as part of AIOUG (AllIndia Oracle User Group) and so there was a parallel track coveringOracle technologies as well. Nagaraj Paduvare fromOracle talked about what User Groups. The title of the presentation"User Groups - Are you a member yet ?" clearly conveyed the urge forthe community to join the local User Groups - be it Java . Oracle'svision is to promote a world-class user group community wherecommunity and customers realize outstanding value from participationand experience constant and healthy dialogue with one another andOracle at all levels. There are 870+ independent Oracle user groupsrelated by interests and location. You can find all the informationabout them at iouc.org.I gave two presentations and the slides are available. JavaSummit Chennai: Java EE 7 There were about 40+ attendees in this talk. Some of the audiencewere not even aware of Java EE 6 so I started the talk with aNetBeans-driven introduction to the platform. A more comprehensivevideo of Java EE 6 tooling with NetBeans is available at screencast#36. The screencast #37 covers the same with Eclipse. And then Iexplained how Java EE 7 platform is embracing cloud by providingsupport for  dynamic service provisioning, metrics-drivenelasticity, and multi-tenancy. Its important to remember that JavaEE 7 will offer lot more than cloud as several specifications suchas Java Message Service 2.0, Java API for RESTful Web Service 2.0,and Expression Language 3.0. Several other specifications aregetting a minor update as well. You can get all the latest updatesat javaee-spec.java.net.The demonstration of taking a Java EE 6 application and deploying itto GlassFish 4 showing service provisioning hit the point home. Thecomplete instructions to download and build the sample are availableat glassfish.org/javaone2011. JavaSummit Chennai: JAX-RS 2.0 This talk gave a brief overview of REST Architecture, how JAX-RSprovides support for RESTful Web services, and a complete overviewof the new features coming in JAX-RS 2.0. I also demonstrated howNetBeans wizards make life simple for generating RESTful Webservices from JPA Entity classes. The working JAX-RS 2.0 samplecodes convey the point that an early implementation is alreadyavailable. You can get all the latest updates at jax-rs-spec.java.net.It was certainly good to spend some time with Venkat Subramaniam andScott Davis.On a personal side, I enjoyed Dal-Baati-Churma ata Rajasthani restaurant in the hotel. For me, enjoying the localcuisine is definitely one of the joys of staying in India. Howeverthe humidity was very high and so that prevented me from running inthe morning. In times like this, the SpartacusWorkout from Men's HealthMagazine has been really helping me recently. If you have nottried this workout, you must!Here are some pictures captured from the event:And the complete video album: Thank you Raj Mahendra for holding the Java flag strong and leadingthe community in Chennai. Only Bangalore, Nagpur, Chennai, and Punehas an active JUG. The JUG community in India is in its infancy andI hope more cities start planning activities like this.Next stop JavaOne India ...

src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/373e570409c2733f17857b1973d18610/chennai_java_summit_2012.png">I attended my...

General

Great Indian Developer Summit 2012 Trip Report

I attended the fifth, and my first, Great Indian Developer Summit inthe SiliconValley of India, Bangalore. The conference is spread over 4days with each day covering .NET, Web, Java, and Workshopsrespectively. The Java track had 800+ attendees (roughly based on acursory headcount for the opening keynote) and the hall was packed.The theater style seating allowed the attendees to enjoy the widescreen presentations. Another unique and cool thing about the conference is that theycreate life size posters of all the speakers and display themoutside the speakers' room. This not only help you identify yourroom easily but also makes you feel like a celebrity ;-) Here aresome pictures of the posters:Venkat's opening keynote is always fun. He talked about "Refactoryour Language Knowledge Portfolio: We're What We Can Code In". Hisentertaining presentation style keeps the audience engaged andlaughing. His Essencevs Ceremony analogy was particularly impressive and Irecommend reading that blog.I gave three presentations and a hands-on workshop and the slidesare now available. GIDS 2012:Java Message Service 2.0 This presentation gave an overview of JMS 2.0 and the new featurescoming there. This presentation had 200+ attendees and 50% of theaudience were existing users of JMS. There was a lot interactivityduring/after the session. Do you know JMS2.0 Early Draft is already available ? The primary goal of this specification is to provide a simplifiedAPI and clarify the ambiguities discovered over the past few years.Check out thisblog for a quick comparison between the existing and thesimplified API. If you have any feature request then its highlyrecommended to file a JIRA issue at jms-spec.java.net. GIDS 2012: JAX-RS 2.0: RESTful Java onSteroids This presentation gave an overview of JAX-RS 2.0. Do you know that Early Draft 2 is already available ? Check out thisblog for a brief overview of the new features coming in JAX-RS2.0. You can find the latest updates at jax-rs-spec.java.net andalso follow @gf_jersey. GIDS 2012: PaaSing a Java EE Application This presentation explained the key concepts of how GlassFishPaaS-enable your Java EE application. The talk also showed how aJava EE application can be deployed where all he services requiredby the application are dynamically provisioned. A working version ofthe application, along with instructions, are available at glassfish.org/javaone2011.A video of the application in action is shown below:The video also shows how the cluster dynamically adjusts to meet theelasticity constraints pre-defined for the application.The Java EE 6 hands-on lab had about 20 attendees. The self-paceinstructions can be downloadedhere. I was pretty amazed by the level of interaction. Therewas one particular guy who who came from the PHP land, was takingnotes on a paper notebook, and was asking the most intelligentquestions. There were other experienced J2EE/Java EE users who alsoenjoyed the simplicity introduced in the platform. And somehow for the past few days the question of Java EE 6 overSpring has come up during each such engagement. My views are clearlyexpressed at WhyJava EE 6 is better than Spring. And do read the interestingdiscussion in the comments, all the way to the end.The conference was well organized with a personal introduction ofeach speaker. The rooms were well marked and the projectors workedvery well. The conference crew was very helpful and prompt inreminding about the time remaining. However a 45 minute session is afew minutes too short and so had to tweak my existing slide deck tomeet the time requirements.Multiple conflicting talks were arranged such as Mike's Java EE 7and mine JMS 2.0, Venkat's "Java 8: A Sneak Peak" and Simon's "JavaSE 8 & Beyond". This feedback was conveyed to the organizers.Hopefully they'll be able to do a better job of this next timearound.On a personal side, I enjoyed a team dinner at BBQ Nation and isdefinitely worth visiting once at least. And could also manage toenjoy a lunch at MTRwith Vivek. The ITC Windsoris a nice hotel with a decent fitness center and a great restaurant.The breakfast buffet had a great variety and very scrumptious.Here are some pictures captured from the event:And now the complete album: The Java EE 7 platform will be much more mature by this time nextyear and who knows I might even submit a Java EE 7 hands-on lab!Thank you Salt March Mediafor putting up a great show and providing me an opportunity topresent. Looking forward to my participation again next year!

I attended the fifth, and my first, Great Indian Developer Summit in the Silicon Valley of India, Bangalore. The conference is spread over 4days with each day covering .NET, Web, Java, and...

General

JMS 2.0 Early Draft - Simplified API Sample Code

Java Message Service (JSR343) is undergoing a major revision as part of Java EE 7. TheEarlyDraft of the specification has been available for a few weeksnow and onlinejavadocs are now available. Several other specifications suchas JPA2.1, JAX-RS2.0, EJB3.2, JavaServerFaces 2, and CDI1.1 in the Java EE 7 umbrella have released early drafts. Someof the specs have been explained in detailed:JAX-RS2.0 Early Draft ExplainedJPA2.1 Early Draft ExplainedWhat's new in JSF 2.2? (external contribution)This blog will provide an update on JMS2.0 Early Draft.JMS 1.1 was released in Dec 2003. A lothas chnged in the Java landscape since then - think aboutannotations, generics, auto-closeable, dependency injection, and alot more. The Java EE platform itself has evolved extensively sincethen, especially Java EE 6 is a "game changer". There are multipleJMS implementations still running solid and so there is lot ofdevelopment/deployment experience on that as well. Keeping all ofthat, and much more, in mind, the main goals of JMS 2.0 are:Changes to improve ease of developmentClarification of relationship between the JMS and other JavaEE specificationsDefinition of a new mandatory API to allow any JMS provider tobe integrated with any Java EE application serverExtensions to support Java EE 7Other enhancements as requested by the communityThis blog will take a code sample from the section 11.4 of the EarlyDraft to highlight how ease-of-development changes are nowcoming to JMS 2.0.This is how a message is sent using the existing JMS API:@Resource(lookup = "jms/connectionFactory ")ConnectionFactory connectionFactory;@Resource(lookup="jms/inboundQueue")Queue inboundQueue;public void sendMessageOld (String payload) { Connection connection = null;try { connection = connectionFactory.createConnection();Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);MessageProducer messageProducer = session.createProducer(inboundQueue);TextMessage textMessage = session.createTextMessage(payload);messageProducer.send(textMessage);} catch (JMSException e) { // do something } finally { try { if (connection != null) connection.close(); } catch (JMSException e2) { // do something else } }}This works very well but several issues with it:Multiple intermediate objects such as Connection,Session, and MessageProducer need tobe created in order to send a message. All these objects serve apurpose but makes the JMS application more complicated. It alsoleads to lots of boilerplate code as well.The arguments to createSession are confusing.The first argument specifies whether the session is transactedor not. The second argument specifies, how, if you used thesession to receive messages, how those messages would beacknowledged. These two arguments are not independent. If thefirst argument is set to true then the second argument isirrelevant. So we only need one argument here.The other part is when this method is in a EJB then thetransactions are controlled by the container. Or if abean-managed transactions are used then the transaction would bestarted and committed using the UserTransactionAPI, not by methods in the JMS API. In fact, the EJB spec saysthat if this code is running in a transaction then the argumentsto createSession are completely ignored. And eventhen we are required to supply some arguments here to satisfythe contract.The Connection need to explicitly closed in thefinally block in order to release the resources appropriately onthe server side. The code does not even show closing of MessageProducerand Session and And the finally block gets uglywith nested exceptions.Now lets take a look at how the new API will simplify theprogramming model:@Resource(lookup = "jms/connectionFactory")ConnectionFactory connectionFactory;@Resource(lookup="jms/inboundQueue")Queue inboundQueue;public void sendMessageNew (String payload) {try (JMSContext context = connectionFactory.createContext();){context.send(inboundQueue,payload);}}Simple, isn't it ?Here are the main changes:All the boilerplate is gone. Instead just create a ConnectionFactory,create a context from it, and invoke send on it.The destinatation (inboundQueue) is now specified on sendinsead of MessageProducer.Connection is now auto-closeable so try blockwill close it autoamatically.New methods throw runtime exception so the code looks muchcleaner.And if you are using Dependency Injection, then the code can befurther simplified to: @Inject@JMSConnectionFactory("jms/connectionFactory")private JMSContext context;@Resource(mappedName = "jms/inboundQueue")private Queue inboundQueue;public void sendMessageNew(String payload) { context.send(inboundQueue, payload);}Some clean ups to note here are ...No need for application to instantiate JMSContextThe same injected JMSContext is available inother places, if within the same CDI scopeHow cool is that ?Here is yet another example on how the simplified API receives amessage synchronously:@Inject@JMSConnectionFactory("jms/connectionFactory")private JMSContext context;@Resource(lookup="jms/inboundQueue")Queue inboundQueue;public String receiveMessageNew() {JMSConsumer consumer = context.createConsumer(inboundQueue);return consumer.receivePayload(String.class);}The section 11.4 of the JMS 2.0 Early Draft provide more lot moresamples with the standard (or existing) API and the simplified (ornew) API.Do you like the direction that the JMS 2.0 Expert Group is taking ?Would you like to provide feedback and contribute ?The latest progress on JMS 2.0 can be tracked at:jms-spec.java.netJSR 343 EG archive at jsr343-expertsDiscussion at users@jms-specJSR 343EarlyDraftLatest Javadocs (download,online)Help us make JMS 2.0 better, simpler, easier to use. Join users@jms-specand contribute!

Java Message Service (JSR 343) is undergoing a major revision as part of Java EE 7. Thehref="http://jcp.org/aboutJava/communityprocess/edr/jsr343/index.html">Early Draft of the specification has...

General

JavaOne Moscow/Russia Trip Report

JavaOne Moscow/Russia was kick started this morning andfollowed the usual pattern of a strategy keynote providing anoverall strategy of the Java platform, technical keynotes providingmore detailed overview of Java SE, JavaFX, Java ME, and Java EE, andthen there were hands-on labs and sessions. The big keynote theaterwas packed with 1300+ audience in the morning and then scattered todifferent rooms.The "Develop, Deploy, and Monitor a Java E 6 Application onGlassFish" hands-on lab had about 40+ attendees. The network was alittle slow and so it took a long time to download the mavenrepository. However as I was explaining the Java EE 6 applications,folks started drawing analogies with Spring and realizing how muchsimpler Java EE 6 has become from its predecessors. An existingSpring user pointed out that "Java EE 6 is much simpler than Springbecause of the default conventions and require minimalconfiguration". Read a more engaged discussion on WhyJava EE 6 is better than Spring.Anyway, the content for the hands-on lab can be downloadedfrom here. It explains:Walk through a Java EE 6 applicationCreate a 2-instance GlassFish cluster and front-end with a Webserver and a load balancerShow session replication when one of the instances failUse extensible monitoring infrastructure to generateapplication-specific monitoring dataI also delivered the Java EE Technical Keynote which gave anupdate on Java EE 7. It also showed a demo of how GlassFishautomatically provisions service as part of the initial work inJava EE 7. The complete demo instructions, along with a video areavailable at glassfish.org/javaone2011.Here are some pictures captured from the day:Do you know the man in the last picture on right column ?You probably will not see him in person. But he is the man whomaintains the master JavaOne schedule, besides many other tasks. Itsnot an easy job as you can imagine :-)Many thanks to Ralph Crawford for doing an outstanding job for allthese years!And now the complete album: JavaOne Russia continues tomorrow so make sure you attend thesessions, talk with the speakers, and make the best use of thispremier conference in your neighborhood.For me, next stop is Great IndianDeveloper Summit!

JavaOne Moscow/Russia was kick started this morning and followed the usual pattern of a strategy keynote providing an overall strategy of the Java platform, technical keynotes providingmore detailed...

General

Java EE 6 and NoSQL/MongoDB on GlassFish using JPA and EclipseLink 2.4 (TOTD #175)

TOTD#166 explained how to use MongoDB in your Java EE 6applications. The code in that tip used the APIs exposed by the MongoDBJava driver and so requires you to learn a new API. However ifyou are building Java EE 6 applications then you are alreadyfamiliar with Java Persistence API (JPA). EclipseLink 2.4, scheduled to release as part of EclipseJuno, provides support for NoSQLdatabases by mapping a JPA entity to a document. Their wikiprovides complete explanation of how the mapping is done.This Tip Of The Day(TOTD) will show how you can leverage that support in your Java EE 6applications deployed on GlassFish3.1.2.Before we dig into the code, here are the key concepts ...A POJO is mapped to a NoSQL data source using @NoSQL or<no-sql> element in "orm.xml".A subset of JPQL and Criteria query are supported, based uponthe underlying data storeConnection properties are defined in "persistence.xml"Now, lets lets take a look at the code ...Download the latest EclipseLink2.4 Nightly Bundle. There is a Installer, Source, andBundle - make sure to download the Bundle link (20120410)and unzip.Download GlassFish3.1.2 zip and unzip.Install the Eclipse Link 2.4 JARs in GlassFishRemove the following JARs from "glassfish/modules":org.eclipse.persistence.antlr.jarorg.eclipse.persistence.asm.jarorg.eclipse.persistence.core.jarorg.eclipse.persistence.jpa.jarorg.eclipse.persistence.jpa.modelgen.jarorg.eclipse.persistence.moxy.jarorg.eclipse.persistence.oracle.jarAdd the following JARs from Eclipse Link 2.4 nightly buildto "glassfish/modules":org.eclipse.persistence.antlr_3.2.0.v201107111232.jarorg.eclipse.persistence.asm_3.3.1.v201107111215.jarorg.eclipse.persistence.core.jpql_2.4.0.v20120407-r11132.jarorg.eclipse.persistence.core_2.4.0.v20120407-r11132.jarorg.eclipse.persistence.jpa.jpql_2.0.0.v20120407-r11132.jarorg.eclipse.persistence.jpa.modelgen_2.4.0.v20120407-r11132.jarorg.eclipse.persistence.jpa_2.4.0.v20120407-r11132.jarorg.eclipse.persistence.moxy_2.4.0.v20120407-r11132.jarorg.eclipse.persistence.nosql_2.4.0.v20120407-r11132.jarorg.eclipse.persistence.oracle_2.4.0.v20120407-r11132.jarStart MongoDBDownload latest MongoDBfrom here (2.0.4 as of this writing).Create the default data directory for MongoDB as:sudo mkdir -p /data/db/sudo chown `id -u` /data/dbRefer to Quickstartfor more details.Start MongoDB as:arungup-mac:mongodb-osx-x86_64-2.0.4 <arungup> ->./bin/mongod./bin/mongod --help for help and startup optionsMon Apr  9 12:56:02 [initandlisten] MongoDB starting : pid=3124 port=27017 dbpath=/data/db/ 64-bit host=arungup-mac.localMon Apr  9 12:56:02 [initandlisten] db version v2.0.4, pdfile version 4.5Mon Apr  9 12:56:02 [initandlisten] git version: 329f3c47fe8136c03392c8f0e548506cb21f8ebfMon Apr  9 12:56:02 [initandlisten] build info: Darwin erh2.10gen.cc 9.8.0 Darwin Kernel Version 9.8.0: Wed Jul 15 16:55:01 PDT 2009; root:xnu-1228.15.4~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_40Mon Apr  9 12:56:02 [initandlisten] options: {}Mon Apr  9 12:56:02 [initandlisten] journal dir=/data/db/journalMon Apr  9 12:56:02 [initandlisten] recover : no journal files present, no recovery neededMon Apr  9 12:56:02 [websvr] admin web console waiting for connections on port 28017Mon Apr  9 12:56:02 [initandlisten] waiting for connections on port 27017Check out the JPA/NoSQL sample from SVNrepository. The complete source code built in this TOTDcan be downloadedhere.Create Java EE 6 web appCreate a Java EE 6 Maven web app as:mvn archetype:generate-DarchetypeGroupId=org.codehaus.mojo.archetypes-DarchetypeArtifactId=webapp-javaee6-DgroupId=model -DartifactId=javaee-nosql-DarchetypeVersion=1.5 -DinteractiveMode=falseCopy the model files from the checked out workspace to thegenerated project as:cd javaee-nosqlcp -r ~/code/workspaces/org.eclipse.persistence.example.jpa.nosql.mongo/src/model src/main/javaCopy "persistence.xml"mkdir src/main/resourcescp -r ~/code/workspaces/org.eclipse.persistence.example.jpa.nosql.mongo/src/META-INF ./src/main/resourcesAdd the following dependencies:<dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa</artifactId> <version>2.4.0-SNAPSHOT</version> <scope>provided</scope></dependency><dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.nosql</artifactId> <version>2.4.0-SNAPSHOT</version></dependency><dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.7.3</version></dependency>The first one is for the EclipseLink latest APIs, the secondone is for EclipseLink/NoSQL support, and the last one is theMongoDB Java driver. And the following repository:<repositories><repository> <id>EclipseLink Repo</id> <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo</url> <snapshots> <enabled>true</enabled> </snapshots> </repository>  </repositories>Copy the "Test.java" to the generated project:mkdir src/main/java/examplecp -r ~/code/workspaces/org.eclipse.persistence.example.jpa.nosql.mongo/src/example/Test.java ./src/main/java/example/This file contains the source code to CRUD the JPA entity toMongoDB. This sample is explained in detail on EclipseLinkwiki.Create a new Servlet in "example" directory as:package example;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * @author Arun Gupta */@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})public class TestServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>"); try { Test.main(null); } catch (Exception ex) { ex.printStackTrace(); } out.println("</body>"); out.println("</html>"); } finally { out.close(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }}Build the project and deploy it as:mvn clean packageglassfish3/bin/asadmin deploy --force=true target/javaee-nosql-1.0-SNAPSHOT.warAccessing http://localhost:8080/javaee-nosql/TestServletshows the following messages in the server.log:connecting(EISLogin( platform=> MongoPlatform user name=> "" MongoConnectionSpec())). . .Connected: User: Database: 2.7  Version: 2.7 . . .Executing MappedInteraction() spec => null properties => {mongo.collection=CUSTOMER, mongo.operation=INSERT} input => [DatabaseRecord( CUSTOMER._id => 4F848E2BDA0670307E2A8FA4 CUSTOMER.NAME => AMCE)]. . .Data access result: [{TOTALCOST=757.0, ORDERLINES=[{DESCRIPTION=table, LINENUMBER=1, COST=300.0}, {DESCRIPTION=balls, LINENUMBER=2, COST=5.0}, {DESCRIPTION=rackets, LINENUMBER=3, COST=15.0}, {DESCRIPTION=net, LINENUMBER=4, COST=2.0}, {DESCRIPTION=shipping, LINENUMBER=5, COST=80.0}, {DESCRIPTION=handling, LINENUMBER=6, COST=55.0},{DESCRIPTION=tax, LINENUMBER=7, COST=300.0}], SHIPPINGADDRESS=[{POSTALCODE=L5J1H7, PROVINCE=ON, COUNTRY=Canada, CITY=Ottawa,STREET=17 Jane St.}], VERSION=2, _id=4F848E2BDA0670307E2A8FA8,DESCRIPTION=Pingpong table, CUSTOMER__id=4F848E2BDA0670307E2A8FA7, BILLINGADDRESS=[{POSTALCODE=L5J1H8, PROVINCE=ON, COUNTRY=Canada, CITY=Ottawa, STREET=7 Bank St.}]}]You'll not see any output in the browser, just the output in theconsole. But the code can be easily modified to do so. Once again, the complete Maven project can be downloadedhere.Do you want to try accessing relational and non-relational (akaNoSQL) databases in the same PU ?

href="https://blogs.oracle.com/arungupta/entry/totd_166_using_nosql_database">TOTD #166 explained how to use MongoDB in your Java EE 6 applications. The code in that tip used the APIs exposed by the h...

General

Great Indian Developer Summit (GIDS), JavaOne Moscow, Java Summit Chennai

My whirlwind tour of Java EE and GlassFish starts next weekend andcovers the following cities in the next 6 weeks:JavaOne and Oracle Develop, MoscowGreat Indian Developer Summit, BangaloreJava Summit, ChennaiJavaOne, HyderabadOTN Developer Day, PuneOTN Developer Day, IstanbulGeecon, PoznanJEEConf, KievOTN Developer Day, JohannesburgSeveral other members of the team will be speaking at some ofthese events as well. Please feel free to reach out to any of us,ask a question, and share your passion. Here is the first set ofconferences coming up:Date: Apr 17-18ScheduleMy Schedule      Deploying your Java EE 6 Applicationsin Producion hands-on lab      Technical Keynote      Some other technical sessionsVenue: Russian Academy ofSciencesRegisterConnect: @OracleRUDate: April 17-20Schedule (date decided, time slots TBD)My Schedule: NetBeans/Java EE 6 workshop on April 19th, Othersessions (as listed above) on April 20Venue: J.N. Tata Auditorium, National Science Symposium Complex, Sir C. V.Raman Avenue, Bangalore, IndiaRegisterConnect: @GreatIndianDevDate: April 21, 2011ScheduleMy Schedule: Java EE 7 at 9:30am, JAX-RS 2.0 at 11amVenue: VELS UniversityRegister(FREE)Connect: @jug_cWhere will I meet or run with you ?Do ask me to record a video session if you are using GlassFish andwould like to share your story at blogs.oracle.com/stories.

My whirlwind tour of Java EE and GlassFish starts next weekend and covers the following cities in the next 6 weeks:JavaOne and Oracle Develop, Moscow Great Indian Developer Summit, Bangalore Java...

General

Why is Java EE 6 better than Spring ?

Java EE 6 was released over2 years ago and now there are 14compliant application servers. In all my talks around theworld, a question that is frequently asked isWhy should I use Java EE 6 insteadof Spring ?There are already several blogs covering that topic:JavaEE wins over Spring by Bill BurkeWhywill I use Java EE instead of Spring in new Enterprise Javaprojects in 2012 ? by Kai Waehner (morediscussion on TSS)Spring to Java EE migration (Part 1and 2,3 and 4 coming as well) by David HeffelfingerSpringto Java EE - A Migration Experience by Lincoln BaxterMigratingSpring to Java EE 6 by Bert Ertman and Paul Bakker atNLJUGMovingfrom Spring to Java EE 6 - The Age of Frameworks is Overat TSSJavaEE vs Spring Shootout by Rohit Kelapure and Reza Rehman atJavaOne 2011JavaEE 6 and the Ewoks by Murat YenerDefiniteexcuse to avoid Spring forever - Bert Ertman and ArunGuptaI will try to share my perspective in this blog.First of all, I'd like to start with a note:Thank you Spring framework forfilling the interim gap and providing functionality that is nowincluded in the mainstream Java EE 6 application servers. The JavaEE platform has evolved over the years learning from frameworkslike Spring and provides all the functionality to build anenterprise application. Thank you very much Spring framework!While Spring was revolutionary in its time and is still very popularand quite main stream in the same way Struts was circa 2003, itreally is last generation's framework - some people are even callingit legacy.However my theory is "code is king". So my approach is to build/takea simple Hello World CRUD application in Java EE 6 and Spring andcompare the deployable artifacts.I started looking at the official tutorial Developinga Spring Framework MVC Application Step-by-Step but it isusing the older version 2.5. I wasn't able to find any updatedversion in the current 3.1 release. Next, I downloaded Spring ToolSuite and thought that would provide some template samples to getstarted. A least a quick search did not show any handy tutorials -either video or text-based. So I searched and found a link to theirSVN repository at src.springframework.org/svn/spring-samples/.I tried the "mvc-basic" sample and the generated WAR file was 4.43MB.While it was named a "basic" sample it seemed to come with 19different libraries bundled but it was what I could find:./WEB-INF/lib/aopalliance-1.0.jar./WEB-INF/lib/hibernate-validator-4.1.0.Final.jar./WEB-INF/lib/jcl-over-slf4j-1.6.1.jar./WEB-INF/lib/joda-time-1.6.2.jar./WEB-INF/lib/joda-time-jsptags-1.0.2.jar./WEB-INF/lib/jstl-1.2.jar./WEB-INF/lib/log4j-1.2.16.jar./WEB-INF/lib/slf4j-api-1.6.1.jar./WEB-INF/lib/slf4j-log4j12-1.6.1.jar./WEB-INF/lib/spring-aop-3.0.5.RELEASE.jar./WEB-INF/lib/spring-asm-3.0.5.RELEASE.jar./WEB-INF/lib/spring-beans-3.0.5.RELEASE.jar./WEB-INF/lib/spring-context-3.0.5.RELEASE.jar./WEB-INF/lib/spring-context-support-3.0.5.RELEASE.jar./WEB-INF/lib/spring-core-3.0.5.RELEASE.jar./WEB-INF/lib/spring-expression-3.0.5.RELEASE.jar./WEB-INF/lib/spring-web-3.0.5.RELEASE.jar./WEB-INF/lib/spring-webmvc-3.0.5.RELEASE.jar./WEB-INF/lib/validation-api-1.0.0.GA.jarAnd it is not even using any database!The app deployed fine on GlassFish 3.1.2 but the "@ControllerExample" link did not work as it was missing the context root.With a bit of tweaking I could deploy the application and assumethat the account got created because no error was displayed in thebrowser or server log.Next I generated the WAR for "mvc-ajax" and the 5.1 MB WAR had 20JARs (1 removed, 2 added):./WEB-INF/lib/aopalliance-1.0.jar./WEB-INF/lib/hibernate-validator-4.1.0.Final.jar./WEB-INF/lib/jackson-core-asl-1.6.4.jar./WEB-INF/lib/jackson-mapper-asl-1.6.4.jar./WEB-INF/lib/jcl-over-slf4j-1.6.1.jar./WEB-INF/lib/joda-time-1.6.2.jar./WEB-INF/lib/jstl-1.2.jar./WEB-INF/lib/log4j-1.2.16.jar./WEB-INF/lib/slf4j-api-1.6.1.jar./WEB-INF/lib/slf4j-log4j12-1.6.1.jar./WEB-INF/lib/spring-aop-3.0.5.RELEASE.jar./WEB-INF/lib/spring-asm-3.0.5.RELEASE.jar./WEB-INF/lib/spring-beans-3.0.5.RELEASE.jar./WEB-INF/lib/spring-context-3.0.5.RELEASE.jar./WEB-INF/lib/spring-context-support-3.0.5.RELEASE.jar./WEB-INF/lib/spring-core-3.0.5.RELEASE.jar./WEB-INF/lib/spring-expression-3.0.5.RELEASE.jar./WEB-INF/lib/spring-web-3.0.5.RELEASE.jar./WEB-INF/lib/spring-webmvc-3.0.5.RELEASE.jar./WEB-INF/lib/validation-api-1.0.0.GA.jar2 more JARs for just doing Ajax.Anyway, deploying this application gave the following error:Caused by: java.lang.NoSuchMethodError: org.codehaus.jackson.map.SerializationConfig.<init>(Lorg/codehaus/jackson/map/ClassIntrospector;Lorg/codehaus/jackson/map/AnnotationIntrospector;Lorg/codehaus/jackson/map/introspect/VisibilityChecker;Lorg/codehaus/jackson/map/jsontype/SubtypeResolver;)V    at org.springframework.samples.mvc.ajax.json.ConversionServiceAwareObjectMapper.<init>(ConversionServiceAwareObjectMapper.java:20)    at org.springframework.samples.mvc.ajax.json.JacksonConversionServiceConfigurer.postProcessAfterInitialization(JacksonConversionServiceConfigurer.java:40)    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)Seems like some incorrect repos in the "pom.xml".Next one is "mvc-showcase" and the 6.49 MB WAR now has 28 JARs asshown below:./WEB-INF/lib/aopalliance-1.0.jar./WEB-INF/lib/aspectjrt-1.6.10.jar./WEB-INF/lib/commons-fileupload-1.2.2.jar./WEB-INF/lib/commons-io-2.0.1.jar./WEB-INF/lib/el-api-2.2.jar./WEB-INF/lib/hibernate-validator-4.1.0.Final.jar./WEB-INF/lib/jackson-core-asl-1.8.1.jar./WEB-INF/lib/jackson-mapper-asl-1.8.1.jar./WEB-INF/lib/javax.inject-1.jar./WEB-INF/lib/jcl-over-slf4j-1.6.1.jar./WEB-INF/lib/jdom-1.0.jar./WEB-INF/lib/joda-time-1.6.2.jar./WEB-INF/lib/jstl-api-1.2.jar./WEB-INF/lib/jstl-impl-1.2.jar./WEB-INF/lib/log4j-1.2.16.jar./WEB-INF/lib/rome-1.0.0.jar./WEB-INF/lib/slf4j-api-1.6.1.jar./WEB-INF/lib/slf4j-log4j12-1.6.1.jar./WEB-INF/lib/spring-aop-3.1.0.RELEASE.jar./WEB-INF/lib/spring-asm-3.1.0.RELEASE.jar./WEB-INF/lib/spring-beans-3.1.0.RELEASE.jar./WEB-INF/lib/spring-context-3.1.0.RELEASE.jar./WEB-INF/lib/spring-context-support-3.1.0.RELEASE.jar./WEB-INF/lib/spring-core-3.1.0.RELEASE.jar./WEB-INF/lib/spring-expression-3.1.0.RELEASE.jar./WEB-INF/lib/spring-web-3.1.0.RELEASE.jar./WEB-INF/lib/spring-webmvc-3.1.0.RELEASE.jar./WEB-INF/lib/validation-api-1.0.0.GA.jarThe app at least deployed and showed results this time. But still nodatabase!Next I tried building "jpetstore" and got the error:[ERROR] Failed to execute goal on project org.springframework.samples.jpetstore:Could not resolve dependencies for project org.springframework.samples:org.springframework.samples.jpetstore:war:1.0.0-SNAPSHOT: Failed to collect dependencies for [commons-fileupload:commons-fileupload:jar:1.2.1 (compile), org.apache.struts:com.springsource.org.apache.struts:jar:1.2.9 (compile), javax.xml.rpc:com.springsource.javax.xml.rpc:jar:1.1.0 (compile), org.apache.commons:com.springsource.org.apache.commons.dbcp:jar:1.2.2.osgi (compile), commons-io:commons-io:jar:1.3.2 (compile), hsqldb:hsqldb:jar:1.8.0.7 (compile), org.apache.tiles:tiles-core:jar:2.2.0 (compile), org.apache.tiles:tiles-jsp:jar:2.2.0 (compile), org.tuckey:urlrewritefilter:jar:3.1.0 (compile), org.springframework:spring-webmvc:jar:3.0.0.BUILD-SNAPSHOT (compile), org.springframework:spring-orm:jar:3.0.0.BUILD-SNAPSHOT (compile), org.springframework:spring-context-support:jar:3.0.0.BUILD-SNAPSHOT (compile), org.springframework.webflow:spring-js:jar:2.0.7.RELEASE (compile), org.apache.ibatis:com.springsource.com.ibatis:jar:2.3.4.726 (runtime), com.caucho:com.springsource.com.caucho:jar:3.2.1 (compile), org.apache.axis:com.springsource.org.apache.axis:jar:1.4.0 (compile), javax.wsdl:com.springsource.javax.wsdl:jar:1.6.1 (compile), javax.servlet:jstl:jar:1.2 (runtime), org.aspectj:aspectjweaver:jar:1.6.5 (compile), javax.servlet:servlet-api:jar:2.5 (provided), javax.servlet.jsp:jsp-api:jar:2.1 (provided), junit:junit:jar:4.6 (test)]: Failed to read artifact descriptor for org.springframework:spring-webmvc:jar:3.0.0.BUILD-SNAPSHOT: Could not transfer artifact org.springframework:spring-webmvc:pom:3.0.0.BUILD-SNAPSHOT from/to JBoss repository (http://repository.jboss.com/maven2): Access denied to: http://repository.jboss.com/maven2/org/springframework/spring-webmvc/3.0.0.BUILD-SNAPSHOT/spring-webmvc-3.0.0.BUILD-SNAPSHOT.pomIt appears the sample is broken - maybe I was pulling from the wrongrepository - would be great if someone were to point me at a goodtarget to use here.With a 50% hit on samples in this repository, I started searchingthrough numerous blogs, most of which have either outdatedinformation (using XML-heavy Spring 2.5), some piece ofconfiguration (which is a typical "feature" of Spring) is missing,or too much complexity in the sample. I finally found thisblog that worked like a charm. This blog creates a trivialSpring MVC 3 application using Hibernate and MySQL. This applicationperforms CRUD operations on a single table in a database usingtypical Spring technologies.  I downloaded the sample code fromthe blog, deployed it on GlassFish 3.1.2 and could CRUD the "person"entity. The source code for this application can be downloadedhere. More details on the application statistics below.And then I built a similar CRUD application in Java EE 6 usingNetBeans wizards in a couple ofminutes. The source code for the application can be downloadedhere and the WARhere. The Spring Source Tool Suite may also offer similar wizard-drivencapabilities but this blog focus primarily on comparing theruntimes. The lack of STS tutorials was slightly disappointing aswell. NetBeans however has tons of text-based and video tutorialsand tons of material even by the community. One more biton the download size of tools bundle ... NetBeans 7.1.1 "All" is 211 MB (which includes GlassFish and Tomcat)Spring Tool Suite  2.9.0 is 347 MB (~ 65% bigger)This blog is not about the tooling comparison so back to the Java EE6 version of the application ....In order to run the Java EE version on GlassFish, copy the MySQLConnector/J to glassfish3/glassfish/domains/domain1/lib/extdirectory and create a JDBC connection pool and JDBC resource as:./bin/asadmin create-jdbc-connection-pool --datasourceclassname \\com.mysql.jdbc.jdbc2.optional.MysqlDataSource --restype \\javax.sql.DataSource --property \\portNumber=3306:user=mysql:password=mysql:databaseName=mydatabase \\myConnectionPool./bin/asadmin create-jdbc-resource --connectionpoolid myConnectionPool jdbc/myDataSourceI generated WARs for the two projects and the table below highlightssome differences between them:Java EE 6SpringWAR File Size0.021030 MB10.87 MB (~516x)Number of files2053 (> 2.5x)Bundled libraries036Total size oflibraries012.1 MBXML files35LoC in XML files50 (11 + 15 + 24)129 (27 + 46 + 16 +11 + 19) (~ 2.5x)Total .propertiesfiles1Bundle.properties2spring.properties, log4j.propertiesCold Deploy5,339 ms11,724 msSecond Deploy481 ms6,261 msThird Deploy528 ms5,484 msFourth Deploy484 ms5,576 msRuntime memory~73 MB~101 MBSome points worth highlighting from the table ...516x WAR file, 10x deploymenttime - With 12.1 MB of libraries (for a very basicapplication) bundled in your application, the WAR file size andthe deployment time will naturally go higher. The WAR file forSpring-based application is 516x bigger and the deployment timeis double during the first deployment and ~ 10x duringsubsequent deployments. The Java EE 6 application is fullyportable and will run on any Java EE 6 compliant applicationserver.36 libraries in the WAR- There are 14JavaEE 6 compliant application servers today. Each of thoseservers provide all the functionality like transactions,dependency injection, security, persistence, etc typicallyrequired of an enterprise or web application. There is no needto bundle 36 libraries worth 12.1 MB for a trivial CRUDapplication. These 14 compliant application servers provide allthe functionality baked in.Now you can also deploy these libraries in the container butthen you don't get the "portability" offered by Spring in thatcase. Does your typical Spring deployment actually do that ?3x LoC in XML - Thenumber of XML files is about 1.6x and the LoC is ~ 2.5x. So muchXML seems circa 2003 when the Java language had no annotations.The XML files can be further reduced, e.g. faces-config.xml canbe replaced without providing i18n, but I just want to comparestock applications.Memory usage - Boththe applications were deployed on default GlassFish 3.1.2installation and any additional memory consumed as part ofdeployment/access was attributed to the application. This is byno means scientific but at least provides an initial ballpark.This area definitely needs more investigation.Another table that compares typical Java EE 6 compliantapplication servers and the custom-stack created for a Springapplication ...Java EE 6SpringWeb Container✓53 MB(tcServer 2.6.3 Developer Edition)Security✓ 12 MB(Spring Security 3.1.0)Persistence✓ 6.3 MB(Hibernate 4.1.0, required)Dependency Injection✓ 5.3 MB(Framework)Web Services✓ 796 KB(Spring WS 2.0.4)Messaging✓ 3.4 MB(RabbitMQ Server 2.7.1)936 KB (Java client 936)OSGi✓1.3 MB(Spring OSGi 1.2.1)GlassFishand WebLogic (starting at 33 MB)83.3 MBThere are differentiating factors on both the stacks. But most ofthe functionality like security, persistence, and dependencyinjection is baked in a Java EE 6 compliant application server butneeds to be individually managed and patched for a Springapplication. This very quickly leads to a "stack explosion". TheJava EE 6 servers are tested extensively on a variety of platformsin different combinations whereas a Spring application developer isresponsible for testing with different JDKs, Operating Systems,Versions, Patches, etc. Oraclehas both the leading OSS lightweight server with GlassFish and theleading enterprise Java server with WebLogic Server, both Java EE 6and both with lightweight deployment options.The Web Container offered as part of a Java EE 6 application servernot only deploys your enterprise Java applications but also provideoperational management, diagnostics, and mission-criticalcapabilities required by your applications.The Java EE 6 platform also introduced the Web Profile which is asubset of the specifications from the entire platform. It istargeted at developers of modern web applications offering areasonably complete stack, composed of standard APIs, and is capableout-of-the-box of addressing the needs of a large class of Webapplications. As your applications grow, the stack can grow to thefull Java EE 6 platform. The GlassFish Server Web Profile startingat 33MB (smaller than just the non-standard tcServer) provides mostof the functionality typically required by a web application.WebLogic provides battle-tested functionality for a high throughput,low latency, and enterprise grade web application. No individualmanaging or patching, all tested and commercially supported for you!Note that VMWare does have a server, tcServer, but it isnon-standard and not even certified to the level of the standard WebProfile most customers expect these days. Customers who choose thisrisk proprietary lock-in since VMWare does not seem to want toformally certify with either Java EE 6 Enterprise Platform or withJava EE 6 Web Profile but of course it would be great if they wereto join the community and help their customers reduce the risk ofdeploying on VMWare software.Some more points to help you decide choose between Java EE 6 andSpring ...Freedom to choose container- There are 14JavaEE 6 compliant application servers today, with a varietyof open source and commercial offerings. A Java EE 6 applicationcan be deployed on any of those containers. So if you deployedyour application on GlassFish today and would like to scale upwith your demands then you can deploy the same application toWebLogic. And because of the portability of a Java EE 6application, you can even take it a different vendor altogether.Spring requires a runtime which could be any of these appservers as well. But why use Spring when all the requiredfunctionality is already baked into the application serveritself ?Spring also has a different definition of portability where theyclaim to bundle all the libraries in the WAR file and move toany application server. But we saw earlier how bloated thatarchive could be.The equivalent features in Spring runtime offerings (mainlytcServer) are not all open source, not as mature, and oftenrequire manual assembly.  Vendor choice - TheJava EE 6 platform is created using the Java Community Processwhere all the big players like Oracle, IBM, RedHat, and Apacheare conritbuting to make the platform successful. Eachapplication server provides the basic Java EE 6 platformcompliance and has its own competitive offerings. This allowsyou to choose an application server for deploying your Java EE 6applications. If you are not happy with the support or featureof one vendor then you can move your application to a differentvendor because of the portability promise offered by theplatform. Spring is a set of products from a single company, one pricebook, one support organization, one sustaining organization, onesales organization, etc. If any of those cause a customerheadache, where do you go ? Java EE, backed by multiple vendors,is a safer bet for those that are risk averse.Production support -With Spring, typically you need to get support from two vendors- VMWare and the container provider. With Java EE 6, all of thisis typically provided by one vendor. For example, Oracle offerscommercial support from systems, operating systems, JDK,application server, and applications on top of them. VMWarecertainly offers complete production support but do you reallywant to put all your eggs in one basket ?Do you really use tcServer ? ;-)Maintainability - WithSpring, you are likely building your own distribution withmultiple JAR files, integrating, patching, versioning, etc ofall those components. Spring's claim is that multiple JAR filesallow you to go à la carte and pick the latest versions ofdifferent components. But who is responsible for testing whetherall these versions work together ? Yep, you got it, its YOU!If something does not work, who patches and maintains the JARs ?Of course, you!Commercial support for such a configuration ? On your own!The Java EE application servers manage all of this for you andprovide a well-tested and commercially supported bundle.While it is always good to realize that there is something new andimproved that updates and replaces older frameworks like Spring, thegood news is not only does a Java EE 6 container offer what isdescribed here, most also will let you deploy and run your Springapplications on them while you go through an upgrade to a moremodern architecture. End result, you get the best of both worlds -keeping your legacy investment but moving to a more agile,lightweight world of Java EE 6.A message to the Spring lovers ...The complexity in J2EE 1.2, 1.3, and 1.4 led to the genesis ofSpring but that was in 2004. This is 2012 and the name has changedto "Java EE 6" :-) There are tons of improvements in the Java EEplatform to make it easy-to-use and powerful. Some examples:Adding @Stateless on a POJO makes it an EJBEJBs can be packaged in a WAR with no special packaging ordeployment descriptors"web.xml" and "faces-config.xml" are optional in most of thecommon casesTypesafe dependency injection is now part of the Java EEplatformAdd @Path on a POJO allows you to publish it as a RESTfulresourceEJBs can be used as backing beans for Facelets-driven JSFpages providing full MVCJava EE 6 WARs are known to be kilobytes in size and deployedin millisecondsTons of other simplifications in the platform and applicationserversSo if you moved away from J2EE to Spring many years ago and have notlooked at Java EE 6 (which has been out since Dec 2009) then youshould definitely try it out. Just be at least aware of what otheralternatives are available instead of restricting yourself to onestack. Here are some workshops and screencasts worth trying:screencast#37 shows how to build an end-to-end application usingNetBeansscreencast#36 builds the same application using Eclipsejavaee-lab-feb2012.pdfis a 3-4 hours self-paced hands-on workshop that guides you tobuild a comprehensive Java EE 6 application using NetBeansEach city generally has a "spring cleanup" program every year. Itallows you to clean up the mess from your house. For your softwareprojects, you don't need to wait for an annual event, just getstarted and reduce the technical debt now! Move away from yourlegacy Spring-based applications to a lighter and more modernapproach of building enterprise Java applications using Java EE 6.Watch this beautiful presentation that explains how to migrate fromSpring -> Java EE 6: List of files in the Java EE 6 project: ./index.xhtml./META-INF./person./person/Create.xhtml./person/Edit.xhtml./person/List.xhtml./person/View.xhtml./resources./resources/css./resources/css/jsfcrud.css./template.xhtml./WEB-INF./WEB-INF/classes./WEB-INF/classes/Bundle.properties./WEB-INF/classes/META-INF./WEB-INF/classes/META-INF/persistence.xml./WEB-INF/classes/org./WEB-INF/classes/org/javaee./WEB-INF/classes/org/javaee/javaeemysql./WEB-INF/classes/org/javaee/javaeemysql/AbstractFacade.class./WEB-INF/classes/org/javaee/javaeemysql/Person.class./WEB-INF/classes/org/javaee/javaeemysql/Person_.class./WEB-INF/classes/org/javaee/javaeemysql/PersonController$1.class./WEB-INF/classes/org/javaee/javaeemysql/PersonController$PersonControllerConverter.class./WEB-INF/classes/org/javaee/javaeemysql/PersonController.class./WEB-INF/classes/org/javaee/javaeemysql/PersonFacade.class./WEB-INF/classes/org/javaee/javaeemysql/util./WEB-INF/classes/org/javaee/javaeemysql/util/JsfUtil.class./WEB-INF/classes/org/javaee/javaeemysql/util/PaginationHelper.class./WEB-INF/faces-config.xml./WEB-INF/web.xmlList of files in the Spring 3.x project:./META-INF./META-INF/MANIFEST.MF./WEB-INF./WEB-INF/applicationContext.xml./WEB-INF/classes./WEB-INF/classes/log4j.properties./WEB-INF/classes/org./WEB-INF/classes/org/krams./WEB-INF/classes/org/krams/tutorial./WEB-INF/classes/org/krams/tutorial/controller./WEB-INF/classes/org/krams/tutorial/controller/MainController.class./WEB-INF/classes/org/krams/tutorial/domain./WEB-INF/classes/org/krams/tutorial/domain/Person.class./WEB-INF/classes/org/krams/tutorial/service./WEB-INF/classes/org/krams/tutorial/service/PersonService.class./WEB-INF/hibernate-context.xml./WEB-INF/hibernate.cfg.xml./WEB-INF/jsp./WEB-INF/jsp/addedpage.jsp./WEB-INF/jsp/addpage.jsp./WEB-INF/jsp/deletedpage.jsp./WEB-INF/jsp/editedpage.jsp./WEB-INF/jsp/editpage.jsp./WEB-INF/jsp/personspage.jsp./WEB-INF/lib./WEB-INF/lib/antlr-2.7.6.jar./WEB-INF/lib/aopalliance-1.0.jar./WEB-INF/lib/c3p0-0.9.1.2.jar./WEB-INF/lib/cglib-nodep-2.2.jar./WEB-INF/lib/commons-beanutils-1.8.3.jar./WEB-INF/lib/commons-collections-3.2.1.jar./WEB-INF/lib/commons-digester-2.1.jar./WEB-INF/lib/commons-logging-1.1.1.jar./WEB-INF/lib/dom4j-1.6.1.jar./WEB-INF/lib/ejb3-persistence-1.0.2.GA.jar./WEB-INF/lib/hibernate-annotations-3.4.0.GA.jar./WEB-INF/lib/hibernate-commons-annotations-3.1.0.GA.jar./WEB-INF/lib/hibernate-core-3.3.2.GA.jar./WEB-INF/lib/javassist-3.7.ga.jar./WEB-INF/lib/jstl-1.1.2.jar./WEB-INF/lib/jta-1.1.jar./WEB-INF/lib/junit-4.8.1.jar./WEB-INF/lib/log4j-1.2.14.jar./WEB-INF/lib/mysql-connector-java-5.1.14.jar./WEB-INF/lib/persistence-api-1.0.jar./WEB-INF/lib/slf4j-api-1.6.1.jar./WEB-INF/lib/slf4j-log4j12-1.6.1.jar./WEB-INF/lib/spring-aop-3.0.5.RELEASE.jar./WEB-INF/lib/spring-asm-3.0.5.RELEASE.jar./WEB-INF/lib/spring-beans-3.0.5.RELEASE.jar./WEB-INF/lib/spring-context-3.0.5.RELEASE.jar./WEB-INF/lib/spring-context-support-3.0.5.RELEASE.jar./WEB-INF/lib/spring-core-3.0.5.RELEASE.jar./WEB-INF/lib/spring-expression-3.0.5.RELEASE.jar./WEB-INF/lib/spring-jdbc-3.0.5.RELEASE.jar./WEB-INF/lib/spring-orm-3.0.5.RELEASE.jar./WEB-INF/lib/spring-tx-3.0.5.RELEASE.jar./WEB-INF/lib/spring-web-3.0.5.RELEASE.jar./WEB-INF/lib/spring-webmvc-3.0.5.RELEASE.jar./WEB-INF/lib/standard-1.1.2.jar./WEB-INF/lib/xml-apis-1.0.b2.jar./WEB-INF/spring-servlet.xml./WEB-INF/spring.properties./WEB-INF/web.xmlSo, are you excited about Java EE 6 ? Want to get started now ? Hereare some resources: JavaEE 6 SDK (including runtime, samples, tutorials etc)GlassFishServer Open Source Edition 3.1.2 (Community)OracleGlassFish Server 3.1.2 (Commercial)JavaEE 6 using WebLogic 12c and NetBeans (Video)JavaEE 6 with NetBeans and GlassFish (Video)JavaEE with Eclipse and GlassFish (Video)

Java EE 6 was released href="https://blogs.oracle.com/arungupta/entry/java_ee_6_is_now">over 2 years ago and now there are href="http://www.oracle.com/technetwork/java/javaee/overview/compatibility-j...

General

JavaOne 2012 CFP Open - Ends April 9

JavaOne 2012 San Franciscois the 17th edition of the premier Java developer conference. The CallFor Papers for this conference is now open. The main tracksare:Core Java PlatformDevelopment Tools and TechniquesEmerging Langauges on the JVMEnterprise Services Architectures and the CloudJava EE Web Profile and Platform TechnologiesJava ME, Java Card, Embedded, and DevicesJava FX and Rich User ExperiencesWhat are the key dates ?Call for Papers StartMar 14, WednesdayCall for Papers End11:59 pm PDT, April 9Accept/Decline NotificationsEnd of May/Early JuneSpeakers to Accept SessionsMid-JuneHere is some personal insight into the reviewprocess and tips for submissions. Bottom line ...No product/marketing pitches, pure technology talksMake titles catchyUse all the characters for providing details about yoursessionMake sure to submit talks in the appropriate trackMore tipshere.This year the conference is happening again at TheZone:View The Zone - JavaOneConference Location in a larger map Here is some of the feedback from last year's JavaOne:Not only thrill + thunder, butalso fun is back! #javaone11 Big thanx to Oracle for thisreally nice conference...really enjoyed it... #javaone11 JavaOne ended for me at breakfastthis morning. Now we're heading home. Great to be a part of such asuccessful show this year! #javaone11 #FF to all my fellow dev ghatattended #javaone11. Really happy to be part of such a greatcommunity. Good nigth San Francisco, I had agreat week at #javaone11 very productive and motivating. Will Iever be back Sitting at SFO waiting for myplane back. What an amazing #javaone11 lies behind us. Thanks toeverybody who made it happen. Thanks @Sharat_Chander for anexcellent #javaone11. Looking forward to many more to come. #JavaOne11 is a wrap! Greatconference and thanks @Oracle for listening to the community forimprovements. last session at #javaone11#javaone. it was most productive week in this year for me asdeveloper It would be a great achievementin my dev life if I come back to #javaone11 as a speaker.Don't you want to be part of this premier Java event ?What are you waiting for ? Just go ahead and share your passion withrest of the Java community. You can submit a Technical Session,Panel, and Birds-of-Feather. Read more details about submissionguidelines.You've 27 days to submityour talk! Don't wait too long though ;-)Check out blogreports and pictures from last year.Stay connected on JavaOne using any of the social media channels: Don't wait, submityour talk now!

href="http://www.oracle.com/javaone/call-for-papers/information/index.html">alt=""src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Im...

General

GlassFish 3.1.2 is released!

GlassFish 3.1.2 is here and downloadit now!This is the latest and the greatest release for GlassFish 3.x. Thethree main themes of this release are:Higher Quality: 500+bug fixes improving the overall quality of 3.1.x and stillmaintaining backwards compatibility. Several community-filedbugs are fixed in this release.Updated components (see below) alone provide 300+ bug fixesNew FeaturesAdministrationConsole ImprovementsBetter startup time and option to load in background afterserver startupFeature parity with asadmin CLIEnabling and disabling secure administrationViewing and monitoring app-scoped resourcesSetup SSH and Node installationConfigure JMS clustersConsolidation of monitoring data in a single tabAdministering Loadbalancer plug-in configurations (only inOracle GlassFish Server)Improved clusteringNew DCOM Support for Windows (as an alternative to SSH forremote management of GlassFish instances)Non-Multicast clusteringmod_proxy_ajp supportImproved EclipseLink integration with EclipseLink MOXysupport and TopLink Grid support (Coherence as 2nd level datacache and only in Oracle GlassFish Server)WebSocket (RFC 6455) SupportTransaction recovery using database (in addition to theexisting file system support)Improved Security (secure admin requires password, OracleGlassFish Server secure by default with new password requiredbe set during installation or on first use), and SSL Encryptedtraffic between the Domain Administration Server and remoteinstancesNetBeans7.1.1 ships with GlassFish Server 3.1.2 (more samples inNetBeans Update Center)Updated Platforms & Components (in addition to existingplatforms, complete supportedmatrix here)Supporting Mac OSX 10.7.1 and Ubuntu 11.0.4 as developerplatformJDKsJRockit 28.2.2JDK 7 U3 and JDK 6 U31 IBM/AIX JDK 6Browsers: Chrome 15.x, Firefox 9+, Safari 5.x, IE 7.x+Updated component bundles: JSF/Mojarra 2.1.6, Grizzly1.9.46, Metro 2.2, Jersey 1.11, Shoal, EclipseLink 2.3.2,OpenMQ 4.5.2, OSGi Core 4.3.0, Update Center, HibernateValidator, JavaDB 10.8.1.2, Weld 1.1.4Check out this video by GlassFish 3.1.2 engineering managerproviding highlights of the release:Here are some other pointers for you to get started:ReleaseNotesDownloadGlassFishServer Open Source Edition 3.1.2 (unsupported communityrelease)OracleGlassFish Server (supportedcommercial offering) JavaEE 6 SDK Update 4 (include samples, docs, APIs, etc)InstallationGuideQuickStart GuideAll-in-onedocumentation archive (Zip bundle of PDFs)JavaEE 6 API JavadocFeedback to GlassFishForums

GlassFish 3.1.2 is here and href="http://glassfish.java.net/downloads/3.1.2-final.html">download it now! This is the latest and the greatest release for GlassFish 3.x. Thethree main themes of this...

General

Java EE 6 workshop delivered at Umeå JUG

What's common between Austin(Texas), Reykjavik(Iceland), Stockholm(Sweden), and Umeå (Sweden) ?They all had a Java EE 6 workshop in the past 2.5 weeksAll of them had fairly higher attendance than normal/expectedEvery where the attendees stayed much longer than originallyplannedThe simplicity and power of awesome threesome of Java EE 6,NetBeans, and GlassFish was very well appreciated by theattendeesThe recently concluded workshop at Umeå JUG proved yetagain how Java EE 6 can easily attract audience. And now thatWebLogic and GlassFish are Java EE 6 compatible, there is a widevariety of containers available to deploy your applications.This JUG, part of Javaforum Sweden, is the second most northernJUG (Reykjavik is the northern most by about 150 km) in a smalluniversity town of about 115,000. The constant sub-zerotemperature and tons of snow during my stay made the cross-countryan interesting first time experience. Running outside in the coldwas harder than I originally thought as the cheeks were gettingcold and making it difficult to talk. Thank you Jonas for teachingme the basic skills and sharing your spikedrunning shoes. Quite an enjoyable experience over all!The interactive attendees learned all about:Improvements in Java Persistence API 2"web.xml"-free and annotation-driven ServletsSimplified packaging of EJBs in a WAR file, no-interface andsingle file definition of EJBSession preservation across redeploysFacelets (XHTML/CSS) as templating language for JavaServerFaes to achieve true MVCIntegration of Bean Validation with JPA and JSFTypesafe dependency injection and Producer/Observer of eventsusing CDIRESTful resources using JAX-RSThe hands-on lab document is availablehere and the completeapplication here.Here is a picture with Jonas and Mattias - the JUGleaders. Their mission is to learn and spread knowledge about Javain Umeå by bringing in speakers from all around the world. Alocal tech publication (InfoTechUmeå) also talked about the workshop. Here is apicture from the article:(Image Credits: InfoTechUmeå)And some more pictures from the visit ...The complete photo album is available at (pictures are from tripto JUGICE and Jfokus) ... Next stop 33rd Degree and Codemotion ...

What's common between href="https://blogs.oracle.com/arungupta/entry/java_ee_6_pulled_crowd">Austin (Texas), href="https://blogs.oracle.com/arungupta/entry/java_ee_6_netbeans_and">Reykjavik(Iceland),...

General

Jfokus 2012 Trip Report

If I were to summarize Jfokus 2012 in two words then they would be -bigger and better!Bigger because ...8 tutorials/hands-on lab in 2011 -> 10 in 20121 fully booked in 2011 -> 5 in 2012About 1450 attendees, 15% more from 2011Better because ...Coffee was served all dayThe best speakers' dinner at a top-notch restaurant. Any bodywilling to beat that ? Make your speakers feel more special ?;-)REST interface to the program scheduleAll-day JavaSpotlightSpeakers from Brazil, attendees from Morocco,  moreinternational participation (about 15-20% attendees were outsideSweden) Flawless wireless connection, no complaints on #jfokus orelsewhere#jfokuswas trendingThere were several talks by Oracle speakers. I gave a Java EE 6hands-on lab and two talks - PaaSinga Java EE Application and TheJava EE 7 Platform: Developing for the Cloud.Againand againthe awesome threesome of Java EE 6, NetBeans, and GlassFish continueto attract audience - this time at Jfokus 2012.  Lot more folksshowed up for the hands-on lab than originally registered and theconference organizers had to arrange extra table and chairs.One of the attendees forgot to bring his laptop and connected to aremote server running NetBeans using his Samsung Galaxy S1 smartphone. He built some part of the application that way and then gothis laptop during one of the coffee breaks. That was pretty awesome!The interactive attendees learned all about:Improvements in Java Persistence API 2"web.xml"-free and annotation-driven ServletsSimplified packaging of EJBs in a WAR file, no-interface andsingle file definition of EJBSession preservation across redeploysFacelets (XHTML/CSS) as templating language for JavaServerFaes to achieve true MVCIntegration of Bean Validation with JPA and JSFTypesafe dependency injection and Producer/Observer of eventsusing CDIRESTful resources using JAX-RSMost of the attendees stayed for the 3.5 hrs long workshop. Severalfolks gave positive feedback afterwards and suggestions on sometroubleshooting tips. The following bugs were filed/followed upon:190988(Refactor fields of an existing entity class to an Embeddableclass)203659(Generate new lines between fields of a JPA entity)208355(Injecting a POJO shows a warning message)205392(Change the default RESTful URL to /webresources or /restful -will be fixed in 7.2.The revised hands-on lab document is availablehere and the completeapplication here.Many thanks to Markus Eisele for helping me with the lab!The slides for "PaaSing your Java EE Application" are availablebelow:PaaSing a Java EEApplicationThis session explained different components of GlassFish to providea standards-based PaaS platform. There were about 25 attendees inthis 9am session.And the slides for "The Java EE 7 Platform: Developing for theCloud" are available below:TheJava EE 7 Platform: Developing for the CloudThis session gave an overview of the Java EE 7 platform. It alsogave a quick preview of Early Drafts from JAX-RS 2.0, JavaServerFaces 2.2, Enterprise JavaBeans 3.2, and Contexs and DependencyInjection 1.1. There were about 200+ attendees in this session.The JavaSpotlight podcast #69 had six different Java Champions - JonasBoner, Stephan Janssen, Chris Richardson, Mattias Karlsson, FabianeNardon, and Bert Ertman talked about "Is Java Dead ?", "How isOracle doing with the Java community ?" and similar topics.The opening keynote by Jurgen Holler reminded me of the famous quoteby Gandhi:First they ignore youThen they laugh at youThen they fight youThen you winI think we are at the last but one stage :-) IMHO product pitches and negative campaigning (feels like Republicanparty primaries back home) should be strictly avoided from suchconferences (not for the keynote at least) otherwise they leave abad taste!Check out some more pictures from the conference ... Even though it snowed overnight yesterday and a little bit thismorning as well but I managed to get a run in the city The city certainly has tons of running/biking trails and they lookbeautiful covered with snow!An evolving album is available at (the first few pictures are fromthe tripto JUGICE and then Jfokus)  ... Also watch a lovely set of photos by Markus Eisele: The returningspeakers at Jfokus are only 7% in contrast with other big Javaconferences such as JavaOne, Devoxx, and W-JAX. I've alreadyattended two years in a row so guess getting into the smallerpercentage already ;-)Next stop Umeåand finally home ...

If I were to summarize Jfokus 2012 in two words then they would be - bigger and better! Bigger because ...8 tutorials/hands-on lab in 2011 -> 10 in 2012 1 fully booked in 2011 -> 5 in 2012 About 1450...

General

Java EE 6, NetBeans, and GlassFish workshop at Reykjavik, Iceland

The JUGICEnormally has about 10-25 attendees, and onceagain, the awesome threesome of Java EE 6, NetBeans, andGlassFish attracted about 50+ attendees in Reykjavik, Iceland. The interactive attendees learned all learned about:Improvements in Java Persistence API 2"web.xml"-free and annotation-driven ServletsSimplified packaging of EJBs in a WAR file, no-interface andsingle file definition of EJBSession preservation across redeploysFacelets (XHTML/CSS) as templating language for JavaServerFaes to achieve true MVCIntegration of Bean Validation with JPA and JSFTypesafe dependency injection and Producer/Observer of eventsusing CDIRESTful resources using JAX-RSMost of the attendees stayed for almost 4 hrs long workshop. Severalfolks gave positive feedback afterwards and tweets like this aremuch more explicit about it:Almost everybody could complete all the exercises, which wasdefinitely satisfying. Most importantly I coached them on how todebug errors and got them little more comfortable in NetBeans andGlassFish. Some folks were even asking for the next level ofworkshop already. I'd love come back in Summer to enjoy theIcelandic hospitality!I had an interesting discussion with a J2EE-to-Spring-convertedarchitect on the benefits of Java EE 6 over Spring. Stay tuned onthat and I'll post more details in a few days :-)Check out some more pictures from the workshop ...The attendees helped me clarify the document further and the reviseddocument is availablehere and the completeapplication here.I also had some good discussions with Reynir Hubner, the marvelousand extremely hospitable JUGICE leader. He is the CTO at Eplica and also the VicePresident of Reykjavik Cycling Club.We had some interesting talks about cross training. He took mearound Golden Circle and to Blue Lagoon.And some more pictures from the stay ...Some interesting facts about Iceland ...The country has about 300k people with two-thirds living in Reykjavikmetro.Even though its close to Arctic circle, the temperature isstill relatively warm because of the Gulf Stream.Fishing, Aluminium smelting, Tourism, and Geothermal power arethe primary industries.One of the first countries to have a democratically electedfemale head of state.The landscape is vast, diverse (lava, craters, snow, lakes,glacier, geysir to name a new), and beautiful (somepictures).Teamhandball is the national sport and othersports are popular too. Icelandingwrestling (Glima)is a particularly interesting one!The heat bill is received yearly because of the widespreadusage of geothermal power.Iceland is all green, Greenland is all icy (morehere)Very low crime rate in Iceland is proven by the fact that thecountry's name does not even exist in thislist for 2010 and this shows 0 murderper 100k for the year 2008. The country has no Army, Navy, orAir Force and only has a Coast Guard. The only folks carryingguns is the VikingSquad which is about 50 cops in the entire country.Everybody talks in terms of before and after the 2008financial crisis.The roof colors in Reykjavik are very bright and vibrant andis by design. I guess this might be to complement the gray skywhich is prominent all through out the year ;-)CrossFitGames overall runner up is AnnieThorisdottir, an Icelander.66 o North is a common brand that sell outer wearfor all weather. No such thing as bad weather, just need to beproperly dressed.If you fly Iceland Air over Atlantic then you can take a 7-daystopover in Iceland without any additional cost.Icelandic horses are short but neve call them pony. More aboutthem at www.icelandichorsefestival.is.Check the latest weather conditions from vedur.is instead of weather.comAnd finally the complete set of pictures from Reykjavik and anevolving album of the trip of Nordics trip so far ... Next stop JFokus...

The href="http://www.linkedin.com/groups/JUGICE-Java-User-Group-Iceland-102100">JUGICE normally has about 10-25 attendees, and href="https://blogs.oracle.com/arungupta/entry/java_ee_6_pulled_crowd">o...

Finance

Running in Reykjavik, Iceland

How do runners explore a new country ?Yep, by running!That's exactly what I did after sleeping for about 2.5 hrs duringSan Francisco/Boston/Reykjavik night :-) Met an ex-Sun colleague whoarranged a wonderful trail run by Ellioa River and Atlantic Sea. Theriver is the largest river to run through Reykjavik and is wellknown for fishing salmon during summer. There was still sopmeresidual snow, from last week's storm, on the trail and of coursewater was all over. We also experienced some hail towards the end ofthe run but a quick ride to the hotel and a warm shower was a greatending.Here is the running route that we followed: And some pictures from the trail:Running seems to becoming more main stream in Reykjavik. Eachswimming pool has a "hlaupakort" (running map) posted near theentrance with routes marked in different lengths. The 3 mostfrequented pools in the downtown area areLaugardalslaug,Sundhöllin, and Vesterbær.There is no way to reach out the running groups except the last onehas a presencehere. Generally the rule is just show up in running clothesand look for the spandex-clad group stretching. Learn more aboutrunning meetups in Reykjavik in thisthread. There is even a 1/2Ironman in July and a full marathonin August and . Read more about running in Reykjavik here.Thank you Kristinn for arranging the run and Agust for showing methe trail!Now to JavaEE 6 workshop tomorrow morning ...

How do runners explore a new country ? Yep, by running! That's exactly what I did after sleeping for about 2.5 hrs during San Francisco/Boston/Reykjavik night :-) Met an ex-Sun colleague whoarranged...

General

JAX-RS 2.0 Early Draft Explained - Java EE 7 Making Progress

JAX-RS2.0 Early Draft has been available for about 3 months now.JAX-RS 2.0, just like JPA 2.1, was one oneof the first JSRs to be filed as part of JavaEE 7. Several other specifications in Java EE 7 have releasedearly drafts as well (JavaServerFaces 2.2, CDI1.1, EJB3.2, and more coming as well) and I'll cover them in laterblogs.Here are the topics covered so far:JPA2.1 Early Draft ExplainedWhat's new in JSF2.2? (external contribution)JAX-RS 2.0 is a brand new specification and here are the mainhighlights so far:Client API: The HTTPUrlConnectionis too low level and is not RESTful-oriented. Invoking a RESTfulresource using this class would look like:URL url = new URL("http://.../atm/balance");HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setRequestMethod("GET");conn.setDoInput(true);conn.setDoOutput(false);           BufferedReader br = new BufferedReader(newInputStreamReader(conn.getInputStream()));String line;while ((line = br.readLine()) != null) {    out.println(line);}Notice, how much code has to be written and its brittle. SomeJAX-RS 1.0/1.1 implementations already provide a higher-levelclient-side API to access the Web resources. For example, readTOTD #57 for more details about Jersey Client API. Aslightly more advanced sample to access Twitter timeline usingJersey Client API is described in TOTD#143.JAX-RS 2.0 introduces a standard Client API to in javax.ws.rs.clientpackage to access the Web resource. It also share features withJAX-RS server API (readers/writers).A simple usage looks like:Client client = ClientFactory.newClient();String balance = client.target("http://.../atm/balance")                      .request("text/plain")                      .get(String.class);Instead of Client client = ClientFactory.newClient(),would you like @Inject Client client then vote forJAX_RS_SPEC-170.Path and query parameters can be easily specified using thebuilder pattern as shown below:Client client = ClientFactory.newClient();String balance =client.target("http://.../atm/{card}/balance")                      .pathParam("card", "1111222233334444")                      .queryParam("pin", "1234")                      .request("text/plain")                      .get(String.class);See how the template in the target path is automaticallysubstituted with the correct value. The request type isspecified to be "text/plain" and GET method of this web resourceis invoked. This will be translated to:http://.../atm/1111222233334444/balance?pin=1234A POST request will look like:Money balance =client.target("http://.../atm/{card}/withdraw")                     .pathParam("card", "1111222233334444")                     .queryParam("pin", "1234")                    .request("application/json")                     .post(text("50.0"), Money.class);There is also generic command pattern that enables separation ofconcern between the creator and submitteruseful for batchprocessing using Invocation. And the code wouldlook like:Invocation inv1 =client.target("http://.../atm/{card}/balance")                      .pathParam("card", "1111222233334444")                      .queryParam("pin", "1234")                      .request("text/plain")                       .buildGet();Invocation inv2 =client.target("http://.../atm/{card}/withdraw")                       .pathParam("card","1111222233334444")                       .queryParam("pin", "1234")                       .request("application/json")                       .buildPost(text("50.0"));And once the Invocations are ready then they canbe invoked.Filters and Handlers:The filters and handlers allow app developers to perform messagerequest pre-processing and response post-processing viawell-defined extension points on the client- and server-side.This is yet another feature that was supported by several JAX-RS1.0/1.1 implementations with each using slightly differentsemantics and now getting standardized in JAX-RS 2.0.Filters are non-wrapping extension points, allow pre-processingwithout modifying the request itself. A filter implementsinterface RequestFilter or ResponseFilteror both and is annotated with @Provider. A loggingfilter that simply logs the message may look like:@Providerclass LoggingFilter implements RequestFilter, ResponseFilter {    @Override    public FilterAction preFilter(FilterContextctx) throws IOException {       logRequest(ctx.getRequest());        returnFilterAction.NEXT;    }    @Override    public FilterActionpostFilter(FilterContext ctx) throws IOException {       logResponse(ctx.getResponse());        returnFilterAction.NEXT;    }}Multiple filters are grouped in filter chains. The response from preFilterand postFilter indicate whether the next filter inthe chain need to be executed (FilterAction.NEXT)or stopped (FilterAction.STOP).Handlers provide wrapping extension points. A handler implementsinterface ReadFromHandler or WriteToHandleror both and is annotated with @Provider. A GZIPfilter that provides deflate and inflate capabilities may looklike:@Providerclass GzipHandler implements ReadFromHandler, WriteToHandler {    @Override    public ObjectreadFrom(ReadFromHandlerContext ctx) throws IOException {        InputStream old =ctx.getInputStream();       ctx.setInputStream(new GZIPInputStream(old));        try {           return ctx.proceed();        } finally {           ctx.setInputStream(old);        }    }    @Override    public Object writeTo(WriteToHandlerContextctx) throws IOException {       OutputStream old = ctx.getOutputStream();        GZIPOutputStreamgzipOutputStream = new GZIPOutputStream(old);       ctx.setInputStream(gzipOutputStream);        try {           return ctx.proceed();        } finally {           gzipOutputStream.finish();           ctx.setOutputStream(old);        }    } }Multiple handlers are grouped in handler chains. The proceedmethod must be explicitly called in order for the next handlerin the chain to be invoked.In the direction of flowthe filters always executed before handlers. The followingdiagram shows the exact execution order on client andserver-side:The handlers and filters can be associated to each method of aresource specifically using @NameBinding. Thespecification defines @GlobalBinding to associatehandlers and filters to all methods of a resource but the recentversion of the specification removes it and makes it a default.Also look at JAX_RS_SPEC-146that asks for a mechanism to override the globalfilters/handlers.The dynamic binding, enabled by implementing DynamicBinding,provide more control on the association with resources andmethods.Hypermedia: Linkingresources together is one of the main RESTful principles. Thereare structural linksthat are used to avoid sending a complete representation of aresource and enable lazy loading. The clients can follow thesetype of links to retrieve the "pieces" they need. A transitional link is usedto update the state of a resource and is typically identified bya "rel" attribute. Structural links are normally in the entity;transitional links could be in link headers or the entity.JAX-RS 2.0 will only support transitional links in headers usingnewly added Link and LinkBuilderclasses. The proposed Client API can also create atarget from a link. The code may look like:Response r =client.target("/product").request("application/json").get();ResponseHeaders rh = r.getHeaders();if (rh.hasLink("ship")) {   client.invocation(rh.getLink("ship")).invoke();}On the server side, ResponseBuilder has supportfor adding one or more link headers. The code may look like:@Path("/products")public class MyResponse {    @GET    @Path("{id}")    @Produces({"application/json","application/xml"})    public ResponsegetProduct(@PathParam("id")int id) {        Product product =new Product(id);        return Response               .ok(product)               .link("http://.../orders/" + id + "/ship", "ship")               .build();    }}Validation: Webresources must validate data received in query or headerparameters or entity bodies. Currently this validation has to beperformed in the application code. The Bean Validationspecification already defines a extensible mechanism to specifyvalidation constraints on a bean. So the JAX-RS specificationleverages that and introduces support for declarativevalidation. The constraint annotations can be specified inpublic constructor parameters, method parameters, fields andbean properties. In addition, they can also decorate resourceclasses, entity parameters and resource methods. Here is asample class augmented with constraint annotations:@Path("/")class ProductResource {    @POST   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)    public void addProduct(@NotNull@FormParam("productName") String name,                          @NotNull @Category @FormParam("category") String category) {        . . .    }}The @NotNull is a pre-defined constraint in theBean Validation API and ensures that the target parameters arenot null. The @Category is a user-definedconstraint using the extensible mechanism provided by the BeanValidation API. If the constraints are violated then theresource method is not invoked and instead a response withstatus code 400 (Bad Request) and an entity that describe theviolations is returned to the client.Here is a sample code of how to validate request entity bodieswhen they are mapped to resource method parameters:@CheckProductclass Product { . . . }@Path("/")class ProductResource {    @POST    @Consumes(MediaType.APPLICATION_JSON)    public void addProduct(@Valid Productproduct) {        . . .    }}The presence of @Valid (a pre-defined annotationin Bean Validation API) next to the method parameter ensuresthat the @CheckProduct constraint is called toverify the mapped entity.The JAX-RS specification also defines the sequence to validateroot resource class instances. The recommendation is to returnas many violations as possible instead of aborting after thefirst violation is encountered.Asynchronous Processing:JAX-RS 2.0 introduces asynchronous processing on server- andclient-side APIs for the usual reasons. The server-side codewill look like:@Path("/async")class ProductResource {    @Context ExecutionContext ctx;    @GET    @Suspend    public Product longOp() {       Executors.newSingleThreadExecutor().submit(           new Runnable() {               public void run() {                   Proruct product = longQueryFromDatabase();                   ctx.resume(product);               }           }        );    }}The longOp method is invoked when this resource isaccessed using GET, forks a new thread, and returns immediatelywithout producing the result. Once longQueryFromDatabasereturns the product then the connection is resumed and theresponse is returned by calling ctx.resume andsetting the value.ExecutionContext also provide suspend()that allows to override the values, such as timeout, specifiedin the annotation based upon the runtime state.On the client-side, the code will look like:Client client = ClientFactory.newClient();Future<String> future =client.target("http://.../atm/{card}/balance")                             .pathParam("card","1111222233334444")                            .queryParam("pin", "1234")                            .request("text/plain")                            .async()                             .get();The async() is called during building the clientrequest. The return Future<String> can beused to query/cancel the status of execution on the server-sideusing isDone and cancel. Once theresponse is ready then Future<T>.get() isinvoked to receive an instance of T if theresponse was successful or null if the invocation failed.Optionally an InvocationCallback<T> may beregistered during the request invocation. The completedmethod is called when the invocation completes successfully anda response is available and failed method iscalled when the invocation fails. The code looks like:Future<String> future =client.target("http://.../atm/{card}/balance")                             .pathParam("card","1111222233334444")                            .queryParam("pin", "1234")                            .request("text/plain")                            .async()                             .get(                                 new InvocationCallback<String>() {                                     @Override                                     public void completed(String result) {                                         // got the correct result                                         System.out.println(result);                                     }                                     @Override                                     public void failed(InvocationException error) {                                         // ouch, got an error!                                         System.err.println(error.getCause());                                     }                                 }                              );Notice, the type of the result is specified as type parameter toInvocationCallback.Client and server developers optimize their resources (threads) depending upon their needs and are independent of each other. A client really can't tell if a resource is implemented asynchronously or not and shouldn't even need to know. Improved connectionnegotiation: This would allow a server to specify apreferred MIME type if the client does not care about it. Thiscan be easily specified using the "qs" qualifier as shown below:@Path("/")class ProductResource {    @GET    @Produces({ "text/xml;qs=0.75","application/json"})    public Product[] getProducts() {        . . .    }}The default server-side qs-value and the final order ofserver-side served types preferences follow the same rules asthose specified for HTTPAccept Header. Per those rules an unspecified value takesthe default value of 1. So the above @Producesrule says "application/json" will be served as the preferredtype if there is no Accept header from the client.The section 3.5 talks more about qs parameter andthe section 3.8 in the specification provide complete detailsabout how media type of the response is chosen by a JAX-RSruntime.The Appendix D in the specification provide a comprehensive listof changes from the previous version of the specification.Here are some final set of references for you:JAX-RS2.0 SpecificationJavadocsJAX-RSSpecification WikiJAX-RSWorkspace (including API and javadocs)And of course, it'll all be delivered as part of GlassFish 4.0! Learn the latest and greatest about JAX-RS 2.0 from MarekPotociar's talk on JAX-RS at Devoxx 2011:

href="http://jcp.org/aboutJava/communityprocess/edr/jsr339/index.html">JAX-RS 2.0 Early Draft has been available for about 3 months now. JAX-RS 2.0, just like JPA 2.1, was one href="http://blogs.oracl...

General

Java EE 6 and 7 at JUGICE, Iceland, JFokus 2012, and Umeå JUG, Sweden

After an easy January month, the conference circuit is starting witha tour of the Nordics.What ? Java EE 6 hands-on workshop Date ? Saturday,Feb 11, 2012 Time ? 9am - 1pm Where ? Reykjavik University,Fönix (m-105) Register ? jugice-ag2012-eorg.eventbrite.com Prep work: Downloadand Install NetBeans 7.0.1 or later ("All" version) from netbeans.org, JDK 6 latestupdate from oracle.com/javase. Twitter: @JUGICEWhat ? JavaEE 6 hands-on workshop (Feb 13, 9am), PaaSinga Java EE Application (Feb 15, 9am), JavaEE 7: Developing for the Cloud (Feb 15, 1pm) Date ? Monday -Wednesday, Feb 13 - 15, 2012 Time ? All Day Where ? StockholmWaterfront Congress Center, Sweden Register ? jfokus.com(almost sold out, register quick) Prep work: (Forhands-on workshop only) Download and Install NetBeans 7.0.1or later ("All" version) from netbeans.org, JDK 6 latestupdate from oracle.com/javase. Website: jfokus.com Twitter: @jfokusCheck out my reports from JFokus2011.What ? JavaEE 6 hands-on workshop Date ? Thursday,Feb 16, 2012 Time ? 6pm Where ? Umeå University(Triple-Helix), Umeå, Sweden Register ? Justshow up Prep work: Downloadand Install NetBeans 7.0.1 or later ("All" version) from netbeans.org, JDK 6 latestupdate from oracle.com/javase. Website: umejug.blogspot.comWhere will I meet or run with you ? :)

After an easy January month, the conference circuit is starting with a tour of the Nordics. cellpadding="5" cellspacing="5">src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50...

General

Java EE 6 pulled crowd at Austin JUG

I delivered a NetBeans-driven Java EE 6 session to about 80+attendees at the Austin JUG yesterday. The session built a typicalthree-tier Web application using the new/updated technologies in theJava EE 6 platform. I was told this is one of the largest attendanceseen at the JUG in recent months. Java EE 6 is indeed a crowd puller;-)Rob Ratcliff, the JUG leader, started with a great overview of"Whats new in Java" covering recent JDKupdate releases, JavaFX 2.1 Developer Preview for Mac and Linux, JavaEE 6 and WebLogic 12c, NetBeans 7.1and other stuff. His complete slides are available here. I was fortunate to speak at the JUG because aninformal survey of the attendees showed that nobody attends (or planto attend) a conference in the coming months.During my session, the highly interactive attendees learned aboutNetBeans wizard-driven Java EE 6 application development. Here aresome of the features that were demonstrated in the talk:Improvements in Java Persistence API"web.xml"-free and annotation-driven ServletsSimplified packaging of EJBs in a WAR file, no-interface andsingle file definition of EJBSession preservation across redeploysFacelets (XHTML/CSS) as templating language for JavaServerFaes to achieve true MVCIntegration of Bean Validation with JPA and JSFTypesafe dependency injection and Producer/Observer of eventsusing CDIRESTful resources using JAX-RSThe application was built using NetBeans and deployed onGlassFish. This same application can be easily deployed onWebLogic 12c as well since it is full Java EE 6-compliant as wellnow. The complete instructions for NetBeans/GlassFish areavailable hereand sameinstructions for NetBeans/WebLogic will be made available shortlyas well.The session ran almost 45 minutes beyond the scheduled time withmost of the attendees staying late and asking questions. Thefeedback from the attendees was very positive. One of them was evenstarting a new project using NetBeans + Java EE 6 + GlassFish nextweek so this talk was directly relevant. Also found another attendeeusing GlassFish for development and WebLogic for deployment fortheir Java EE 6 application. Rob used GlassFish for an internal US Military project and has been deployed for more than 2 years with nearly zero maintenance.Check out some pictures from the JUG visit ...A tweet like the one below definitely make the quick trip worth it...The formal JUG session was followed by a beer-a-thon(lemonade-a-thon for me ;-) at BJs. Some interesting facts about Austin ...Michael Dell (chairman and CEO of Dell) lives in Austin, Dellworldwide headquarters are in Austin.Lance Armstrong is from Austin.Sandra Bullock, Matthew McConaughey, and Brad Pitt has homesin Austin.Whole Foods chain started and headquartered in Austin. I waslucky enough to squeeze time out for a lunch with a colleague atone of their stores in this less-than-24-hour visit to Austin.Keep Austin WeirdDownload the NetBeans/GlassFishinstructions and let us know how you are using Java EE 6.Next stop is Reykjavik (Iceland), Stockholm (Sweden) and Umeå(Sweden), more on that later ...

src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/117ee96d0f47f4da7ff6429c16b5ed6d/austinjug_banner_178x90.jpg">I delivered a...

Oracle

Integrated Cloud Applications & Platform Services