blogging from reza rahman’s jee 7 talk

This month’s NY JavaSig was chock full of information about JEE 7.  It was nice seeing it before Oracle’s launch webcast.  And at a more convenient time as well!  Given that Reza Rahman works for Oracle, we got the standard Oracle disclaimer that anything can change in the next two weeks.  But we all know they don’t have time to change much so 99.9% of this should be true.  [comments in brackets are my opinions; not Reza’s or Oracle’s]
High level JEE 7 changes
  • JMS 2. Batch. Transactions. Concurrency, interceptor, web socket java api, json java api
  • El 3, jms 2′ jax-rs 2.
  • Rest like EJB are minor releases. Ejb 3.2 (interestingly CMP is from J2EE 1.3)
  • Add to web profile: jax-rs 2
  • Deprecate jax rpc, cmp, cmp, jsr 88 – no known tools to get off bmp/cmp
  • Themes are productivity and html 5, core foundational apis
Jms 2
  • 8 year old api. Needed an overhall
  • Change api to use  DI
  • Delivery delay, async send, delivery count, now standard rather than optional, mdb alignment
  • Now you just inject JMSContext and Queue – a  new Object. Reduces code from a slide to a few lines.
  • Uses default JMSContext connection factory unless specify otherwise
  • Context has createProducer() and createConsumer(). Uses builder pattern so can chain/use one liners to configure
  • New API uses runtime exceptions
  • Added JMSConnectionFactoryDefinition and JMSDestinationDefinition annotations so can configure in code instead of vendor specific descriptor. Can still use xml instead of annotations
  • MDBs have new @ActivationConfigProperty
  • Spring will be supporting JMS 2 in their apis. Will need new JMS apis as well from third party libraries.
Websockets
  • Stateful protocol. Bidirectional async communication. Good for gaming, online stock tickers, etc
  • Uses HTTO as handshake between client and server
  • Part of HTML 5. Hope people will be using within 3-5 years.
  • Very high level API
  • Supports both declarative and progamatic programming. Most people should be dealiling with declarative api.  The programmatic one is meant for third party api developers
  • Abstracts keep alive setting
  • Weakness in websocket spec: can use up all sockets on a machine
  • Keep alive packets sent about every 5 minutes (vs 30 seconds normally). If your router times out after a minute, you’ll need to reconfigure. No session replication yet. If server goes down, you lose it
  • Server side code – POJO with annotaton for serverendpoint(url)’ onopen and onclose. Onopen and onclose callbacks get passed a session. Also callbacks for onmessage and onerror.  Use session.getRemote.  To get handle to remote endpoint and call sendXXX. It is NOT an HttpSession  because you are not in http level of abstraction
  • Client – JavaScript has an api for websocket.  Use this 90 peercent of the time
Json
[feels like java util logging.  late to the party and not as good as open source libraries]
  • Have jsonp – Like xmlp?
  • Will have jsonb in future –  Like xmlb. Eclipselink has two implementations now. Moxi and eclipse link json binding. The later one is likely to be closest to the standard.
  • No safe bet. Use what exists now and change later
To use
  • JsonArray  array = Json.createArrayBuilder(). Can add primatives and objects
  • To read: parser().iterator and parser,getString()
  • iterator,nextO will return START_OBJECT, KEY_NA ME, etc in addition to the real values.  [ugly – reminds me of the early days of DOM]
JAX-RS 2
[Lost what i typed because after deleting text undo deleted still more text. I think i remembered it all to retype]
  • Jersey is an implementation as is RESTEasy
  • Jax-rs was was introduced in jee 6
  • Hypermedia support – using hyperlinks in rest, like for lazy loading
  • Cient api, message filter, entity interceptor, asnc processing for high throughput, content negotiation (queues used to apply weight to client)
  • Client api: ClientBuilder.newClient() and client.target(url, params, …  )
  • For filter implement ContainerRequestFilter
JPA 2.1
  • Schema generation – every provider supports already.  This adds a standard format. Can create database and/or ddl,   Showed examole with index names in Java and said “no other way to do it” [yuck – this is why you should separate your DDL and not store it in only in Java.  You are going to need that standalone DDL later anyway for laters so why not put the index there.]
  • Stored procedure support – people want it, all providers have it already so gave in and put it in in ORM spec.  Looks like namedqueries. @NamedStoredProcedureQuery
  • Unsynchronized persistence contexts – can join when  ready to rejoin context
  • Entity convertors – edge case solution for odd format in database field but dont want in java objects
  • Fixes/enhancement
Jta 1.2
  • Old api that needed an update. Lots of fixes and two new features
  • Declarative transactions outside EJB – any CDI object supported now. @Transactional. Default is rollback for runtime exception and ignore checked exception
  • @TransactionScoped – new CDI scope. JMSContext uses this scope
Jsf 2.2
  • Html 5 support – pass thru html 5 components. Use normal inout type=color and then jsf:value and el expression as attribute. That way not limited to jsf component libraries. Similary jsf:id, jsf:validate, jsf:renderer
  • @Flowscoped – alternative to conversation scope. Conversation was suited to wizards. Flow scoped keeps certain objects active for different parts of the app. [Code looks like a state diagram in java code – long]
  • @ViewScoped for CDI
  • Deprecated JSF managed beans. Use CDI instead
  • File upload component – couldn’t add until now because JSF was being backward compatible with 2 versions of servlet apis
  • View actions – can trigger an action when land on page rather than wait for user to click on something
  • Multi templating – templates can have parents
  • Security
Batch applications
  • Concepts. JobRepository, Job,JobOperator, Step, ItemReader, ItemProcessor, ItemWriter ( map reduce pattern with readerprocess, write)
  • The java community doesnt generally get into batch processing. Financial community is different. Hadoop and analytics starting to bring batch to wider audience
  • To code use named annotation and implement Itemreader, ItemProcessor, ItemWriter
  • Write XML for step to chunk it and send to reader, processor and writer. Methods. ReadItem, processItems, writeitems
  • IBM websphere compute grid  called out for batch multi threading on different machines.
  • IBM most active and spring second most active contributor to batch spec. Presumably that means Spring is interesting in supporting
Bean validation 1.1
  • Added method level constraints.  Useful in REST. Method param and return type constraints.  Used to only have property level
  • Bean validation artifacts injectable
Concurrency utilities for JEE
  • Builds on JSE Executor Service
  • Thread pool aware
  • Relatively low level API
  • Don’t expect a lot of people to use.  Meant for third parties running on JEE so can share app server thread pool
  • Inject ManagedExecutorService annotation. Submit your task to executor
El. 3
  • Lambda expressions, collections support, operator support
  • EJB 3.2 truncating BMP/CMP
  • Servlet api – non blocking IO
  • Ordering of interceptors
Jee 8 
  • jsonB. – probably before JEE 8
  • Jcache – available as drop in jar before. Just missed JEE 7 cutoff
  • Lots more stuff
Tomcat
  • Base Tomcat planning on supporting JSR 356 (web sockets), maybe concurrency utilities
  • TomEE – apache project taking plain tomcat and brining up to JEE web profile level. It is certified against web profile

my first “thing in print”

mala-coverI was the technical proofer of Manning’s OCA book and got asked to write the foreword.  I got the book in the mail and was shocked to see “foreword by Jeanne Boyarsky” listed on the cover under the author’s name.  I’ve only noticed the foreword author listed on the cover when it is someone famous.  Or maybe it is that most books have an preface rather than a foreword.  Or maybe this is a shameless way to get me to advertise the book on my blog :).  (just kidding)   Anyway, it is AWESOME!

The publisher suggested putting the foreword on my blog.  Here it is.  Notice I got plugs in for Head First Java (from another publisher no less) and coderanch.com in there as well.  Speaking of plugs, feel free to read what I wrote on the blog about the OCAJP exam itself.

Note: I also contributed the equivalent of about half a chapter to the OCPJP book by Kathy Sierra and Bert Bates.  That was a lot more work and is really more of an accomplishment.  It comes out around summer.  But this foreword is the first thing I’ve ever written to wind up in a print book.  Very excited.

Taking the OCA Java Programmer I exam is a bit like taking a driving test. First you learn the basics, like where the brakes are. Then you start driving, and then you get ready to take the driving test to get your license. The written test includes things every- one should know, things that you’ll never use after the road test, and some things that are tricky edge cases. While the programmer exam cares about breaks more than brakes, it certainly likes edge cases!

Consider Mala Gupta your driving instructor to get you ready for the programmer exam. Mala points out what you’ll need to know when programming in the real world—on your first job.

And consider this book your driver’s manual. It gives you the rules of the road of Java, plus the gotchas that show up on that pesky written test. But don’t worry, it is much more fun to read this book than the driver’s manual. Just like the driver’s man- ual won’t teach you everything about driving, this book won’t teach you everything there is to know about Java. If you haven’t yet, read an intro to a Java book first. Start with a book like Head First Java or Thinking in Java and then come back to this book to study for the exam.

As the technical proofreader of this book, I got to see it evolve and get better as Mala worked on it. Through the conversations we had on little things, I learned that Mala knows her stuff and is a great teacher of Java. While I’ve only technical proofread a handful of books, I’ve posted reviews of over 150 technical books on Amazon, which makes it easy to spot a book that isn’t clear or helpful. I’m happy to say that Mala’s explanations are all very clear, and the pointers are great.

I also got to read Mala’s posts in the certification forums at coderanch.com. She’s been sharing updates about the exam as it comes out and posting fairly regularly for over a year. As a senior moderator at coderanch.com, it is great to see an author sharing her wisdom. It’s also nice to see the similarity in writing style between the forum posts and the book. This shows the book is readable and written in an easy-to-understand, casual style.

I particularly liked the diagrams, flow charts, and cartoons in this book. And, of course, the annotated code examples I’ve come to expect from any Manning book. Each chapter ends with sample mock exam questions and there is a full mock exam at the end. This gives you good practice in getting ready for the exam. Wrong answers are well explained so you don’t make the same mistakes over and over.

My favorite part of the book is the “Twist in the Tale” exercises. Mala gives a num- ber of examples of how making a seemingly minor change to the code can have major consequences. These exercises develop your attention to detail so you are more obser- vant for the mock exam questions and the exam itself.

I had already passed the OCA Java Programmer exam with a score of 98% before reading this book. If I hadn’t, the questions would have prepared me for the exam. Studying from this book will give you the skills and confidence you need to become an Oracle Certified Associate Java Programmer. Happy coding and good luck on the exam!

JEANNE BOYARSKY

SENIOR DEVELOPER & MODERATOR

CODERANCH

csrf for JForum without javascript

In February, I wrote a three part series on how we fixed JForum on coderanch to protect from CSRF.  In included;

  1. Analysis
  2. Extending OWASP
  3. Problems

Remaining problems

Unfortunately, there were three remaining problems.

  1. Some mobile devices weren’t able to handle the JavaScript which added the tokens.  Meaning our site didn’t work on all mobile devices.
  2. The CSRF token was in the URL of thread links which meant people were sharing those links with tokens in them.  This isn’t a significant security risk, but it does confuse Google which is bad for SEO.  It is a tiny security risk in that if someone posts their current CSRF token, that user can be targeted for a CSRF attack until that token expires.
  3. Some people take a really long time to write a post or have lunch in the middle and the token expires.  Giving them a CSRF error page when they finally finish.

This blog post shows how we solved these problems.

Ending requirement for JavaScript to set CSRF token and getting token out of URLS

In general, there are three options for setting a CSRF token in forums/URLs: JavaScript, a filter to change the HTML at runtime before it gets served to the client or hard coding the token.

Based on our experience with mobile devices, we decided not to go with option1 (JavaScript.)  I had used a technique similar to option 2 (changing the HTML as it goes by) to transform our JForum URLs to a different format.  This turned out to be more complex on a forum where users routinely post code.  The same problem would occur here so I decided against that option.  We don’t want to be adding CSRF tokens to code user’s post in questions.  And we certainly don’t want someone to be able to inject a CSRF attack in a post!

This left me with option 3 – hard coding the token.  There were a few steps to implementing this option:

  1. The JavaScript solution added the token to URLs in addition to forms.  This wasn’t “good” in the first place in that URLs shouldn’t be changing database state.  I had recognized this as a shortcoming back in February but lacked the time to fix it then.  There’s a representative list of these pages/URLs on github.  Many were fixed by a one to one conversion of links to forms. (with POST as the method.)  A few were fixed with a generic form on the page and JavaScript that calls it.  We used the generic JavaScript form for some admin links to save bandwidth. Most of these aren’t available in the mobile view anyway.  And moderators weren’t the ones having JavaScript issues in the first place – probably because we have newer mobile devices.
    </span></span>function submitActionForForum(actionVerb, forumId) {
    var action = document.actionForm.action;
    
    action = action.replace("ACTION", actionVerb);
    
    action = action.replace("FORUM_ID", forumId);
    
    document.actionForm.action = action;
    
    document.actionForm.submit();
    
    }
    
    
  2. At this point we don’t need to add tokens to anchors.
  3. Remove AddJavaScriptServletFilter and JavaScriptServlet so tokens are no longer generated by JavaScript.
  4. Add token to all forms:
    <input type="hidden" name="OWASP_CSRFTOKEN" value="${OWASP_CSRFTOKEN!""}" />
    
    
  5. For forms containing multipart/form-data (there were less than 10 of these), add to the URL:(this is needed because the multipart request is only parsed once – later on in the process and the parameter isn’t available to us in the filter)
    ?OWASP_CSRFTOKEN=${OWASP_CSRFTOKEN!""} 
  6. In parallel to the previous two steps, I wrote a unit test to ensure I didn’t miss any required tokens AND to alert anyone adding a form to the codebase in the future about the need to add a token.  Unit test available on github.
The other problem – session timeouts
My first thought was to use AJAX to keep the session active as long as the browser is open.  This session isn’t ideal as some users keep their browser open all day.  I talked to the site owner and we agreed on a three hour timeout for CSRF tokens based on inactivity.  (This also has the advantage of the token surviving a server restart which we do for deployments.)
I implemented by creating a database table with the user id and token.  I have a TimerTask that deletes any tokens over three hours old and runs every 15 minutes.  (This isn’t strictly accurate as it keeps the token alive as long as the user session or the token is less than 3 hours old.  So if I have an active session for 2 hours 55 minutes and a server restart happens, I lose my token.  This implementation may change if it turns out to be a problem in reality.  The current filter and helper class are now online for reference.
What I learned
It’s a lot harder to protect against CSRF on a public website than one with controlled users.  This was an interesting project though.