Featured FREE Whitepapers

What's New Here?

java-logo

Warming Up Your JVM – Superfast Production Servers and IDEs

A couple of months ago I was reading up on Complex Event Processing in Java and ways to achieve low latency. At the end of my hour long research I figured out that even if your application is well written and your methods run mostly in 0(log n) time, and you are using some bleeding edge hardware solutions, there is still some time consumed by the VM during its interpretation of the bytecode. On the good side of things, Java is interpreted and its bytecode is cross-JVM compatible but we also know that because of this we are bound to lose something somewhere. Our JVM reads the interpreted bytecode and runs it every time. Obviously, this takes time. But its not that bad considering our friendly neighbourhood JIT compiler (server or client) watches out for commonly used methods and when it figures out that the method is called just too many times, it compiles it into native machine code instead of making the JVM rely on bytecode all the time. The number for ‘too many times’ is configured using the vm argument <-XX:CompileThreshold And the default is 1500. One’s natural guess would be that reducing the number would mean more methods are converted to native code faster and that would mean faster application but it may not be. Considerably low numbers would mean that the server starts considerably slower because of the time taken by the JIT to compile too many methods (which may not be used that often after all) and since the native machine code resides in the memory, your application will be awarded the “Memory killer” award and die a slow painful death. A little googling shows that numbers around 100 is not that bad. Again, it depends on your application and the usage patterns and traffic. Forgot to mention, that the smallest compilation unit to become a JIT native compilation candidate is a method. Not a block. So, long running fat methods – good luck !!! In reality, this JIT compilation is not in one go. It has two neat phases : 1) Everytime a method is called, its counter gets increased by 1 and soon after it reaches the threshold, the JIT does its first compilation. 2) After the first compilation, the counter is reset to 0 and incremented again. In this second cycle, when it reaches the threshold, JIT does an second round of compilation – this time with more aggressive and awesome optimizations (sorry – unable to provide you much details here) If you are using JDK 7 and your machine runs on multi-core (I don’t see why not), then you could use the following flag to speed up your native compilation process -server -XX:+TieredCompilationI can’t claim to be an expert in JVM tuning considering the amount of options available. So, please leave your comments if you find this useful or is incorrect. Don’t forget to share! Reference: Warming Up Your JVM – Superfast Production Servers and IDEs from our JCG partner Arun Manivannan at the Rerun.me blog....
akka-logo

JavaOne 2012: Up, Up, and Out: Scaling Software with Akka

After the late-ending Community Keynote, I headed to Hilton Golden Gate 3/4/5 to see Viktor Klang‘s (Typesafe) ‘Up, Up and Out: Akka’ presentation. Klang is the technical lead on Akka. Akka is a ‘beautiful mountain in northern Sweden,’ is a Goddess, and is a Scala-based ‘toolkit and runtime for building highly concurrent, distributed, and fault tolerant event-driven applications on the JVM.’ Akka is not exclusive to Scala only and can be used ‘from Java today.’ Using Akka with Scala does allow you to do some things you cannot do with Akka when used with Java.Akka is used by many large companies to solve real problems. Akka is built to scare in many directions and to provide extreme flexibility. One of Akka’s goals is to ‘manage system overload.’ Akka uses Actors: ‘Akka’s unit of code organization.’ According to Klang, ‘Actors help you create concurrent, scalable, and fault-tolerant applications.’ Actors ‘keep many ‘policy decisions’ separate from the business logic.’ Actors originated in 1970s (‘like all cool stuff in computer science’) and Erlang has been using actors with ‘great success’ for several years. Klang warned to avoid ‘thinking in terms of shared state, a leaky abstraction.’ He added that threads and locks are ‘a means of execution’ rather than structural. He said this mixes execution with business logic. Concurrent collections are good optimizations for local uses. Actors are ‘distributable by design’ and Klang had a slide listing several bullets explaining this statement. He stated that an actor can be an alternative to ‘a thread,’ ‘an object instance,’ ‘a callback or listener,’ ‘a singleton or service,’ ‘a router, load-balancer, or pool,’ ‘Java EE session bean or Message-Driven Bean,’ ‘out of process service,’ and ‘finite state machines.’ Klang referenced a video of Carl Hewitt on actors. An actor is a ‘fundamental unit of computation that embodies several key characteristics.’ Klang showed code examples in my preferred format in a presentation: embedded in his slides with color syntax highlighting. He showed step 0 (‘DEFINE’) in which his code defined the Actor’s class and the Actor’s behavior. Once defined, the first operation (I – ‘CREATE’) ‘creates a new instance of an Actor.’ The created Actor is extremely lightweight and its ‘state and behavior are indistinguishable from each other.’ He drove this last point home: ‘The only way to observe state is by sending an actor a message and seeing how the actor reacts.’ The Actor is ‘very strong encapsulation’ of state, behavior, and message queue. Akka provides an ActorSystem for creating Akka Actor instances. An instance of Props is provided to the Actor because actors need props. Step 2 (‘SEND’) involves ‘sending a message to an Actor’ and ‘everything happens reactively’ and ‘everything is asynchronous and lockless.’ Akka supports a ‘fire and forget’ mode with the actor’s tell method. However, Akka provides guaranteed order of delivery. The reply is implemented in Akka with getSender().tell(). Step 3 (‘BECOME’) ‘redefines the Actor’s behavior’ and is ‘triggered reactively by receipt of message.’ The reasons one might want to change the behavior of an actor at runtime include supporting highly contended actor transforming to an actor pool or to implement graceful degradation. Actors can supervise other Actors, leading to Step 4 (‘SUPERVISE’). A ‘supevisor detects and responds to the failures of the Actor(s) it supervises’ and Klang stated that this translates to ‘a clean separation and processing and error handling.’ Klang talked about ‘failure management in Java, C, and C#’ where you are ‘given a single thread of control.’ He put it this way in a bullet: ‘If this thread blows up, you are screwed.’ The implication of this is that all ‘explicit error handling’ is done ‘within the single thread’ and ‘tangled up’ with the business code. Klang said the way to deal with error handling is to push the error handling out away from the business logic. He then referenced the onion-layer error kernel. Klang talked about callbacks (preRestart and postRestart) provided for Actors to handle failures. A Router is a special case of Actor. Klang showed a slide with code using a RoundRobinRouter. He also showed being able to define the deployment scenario outside of the code in configuration file and referencing that from the code with a path. He took this example even further to show code for ‘remote deployment’ specifying a URL with the ‘akka’ protocol, a host name, and a port. Everything that Klang presented to this point is available today as Akka 2.0. Klang said that there will be Akka Cluster in the to-be-released-soon Akka 2.1. He asked for feedback to ensure that the correct APIs and correct functionality are available for clustering in Akka 2.2. More information on Akka clustering is available in the specification, the user guide, and the code itself. Akka 2.1 will also feature Akka Camel based on Apache Camel. The Typesafe Console is also available to monitor an Akka application and there is a live demo of this available. Reference: JavaOne 2012: Up, Up, and Out: Scaling Software with Akka from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
software-development-2-logo

The Business Opportunity of the Decade

Peter Drucker, the famed management guru, frequently talks about risk (more specifically managing risk) in a business. Per usual, he simplifies into 4 kinds of risk: 1) Risks that you must take 2) Risks that you can afford to take 3) Risks that you cannot afford to take 4) Risks that you cannot afford to not take I believe the current transformation in Information Technology falls into category 4: its a risk that every organization cannot afford to not take. That fact creates the business opportunity of the decade, for someone or some group of people that decide to capitalize on it. The Macro View The current economy is turbulent. Unfortunately, this is a new normal vs. a phase, in my view. With continued QE’s, LTRO’s, and countless other government programs, there are attempts to keep things afloat. However, the result is increasing unemployment (euro zone now at largest level EVER), stagnating growth (Brazil barely growing??), and an inevitable reduction in global trade/commerce. When you have this type of environment, the actions for every company are fairly straightforward: spend less, do more with less (employees, tools, etc) and prepare for life in the new normal. The Transformation At the same time of the macro picture I paint above, as discussed in this book, we are at the start of the big data era. Let me simplify big data for a moment: this is simply about leveraging technology to do (or not do)things that were never possible before. I think these ‘things’ fit into 3 categories: 1) New use cases, applications, solutions. 2) Shift ‘how’ you do existing things, to a more efficient approach/platform 3) Consolidate everything (tasks, employees, IT, offices, spend, vendors, etc) Interestingly, 90% of the discussions that I have with clients on big data are focused in category 1 (new use cases, solutions, etc). In many cases, this is dream-storming (brainstorming, with a healthy amount of dreaming). Category 2 and 3 are where I believe the real opportunity lies, given the new normal. However, doing anything in category 2 or 3 is very hard for an organization: – You have to build a plan to define what, how, when – You have to have the fortitude to slaughter a massive number of ‘sacred cows’ – You have to overcome organizational inertia to take action These 3 inhibitors to making progress on Categories 2 and 3 are what present the business opportunity of the decade. This can only be done by an external party/partner, due to the inhibitors…and that presents a rich consulting opportunity. To build a business here, I think the right model is to earn fees as a % of dollars saved. This immediately eliminates the vast majority of large Systems Integrators and Consulting companies, as they cannot afford that model. I’ve seen the potential savings with my own eyes. Clients can save 50-70% on many functions, by leveraging this ‘ next generation middleware‘. Who will help them? Reference: The Business Opportunity of the Decade from our JCG partner Rob Thomas at the Rob’s Blog blog....
javaone-logo

JavaOne 2012: 101 Ways to Improve Java – Why Developer Participation Matters

Bruno Souza, Martijn Verburg, and Heather Vancura presented ‘101 Ways to Improve Java: Why Developer Participation Matters’ in Continental Ballroom 4 of the Hilton. They split these up into their areas of greatest familiarity. Souza, the founder and coordinator of SouJava, talked about greater participation via user groups. Verberg, also heavily involved in user groups with the London Java Community and recently heavily involved in the Adopt-A-JSR program, talked about Java Specification Requests (JSRs) and adopting a JSR. Vancura [JCP Program Management Office (PMO)] talked about the greater Java Community Process (JCP) and contributing to that.The 101 ways developers can participate in improving Java were divided among several categories such as ‘Ways to Improve Your Java User Group (JUG),’ ‘Ways to Teach,’ ‘Ways to Help Java Open Source Project,’ ‘Ways to Adopt a JSR,’ and ‘Ways to Participate in JCP.’ The ideas for ways Java developers can contribute to the improvement of Java ranged from very simple to more involved. Most, however, were highly approachable for the typical developer. One example from the improving JUGs category was to be a speaker or to provide a speaker from among one’s colleagues. The idea here was that even if one did not want to speak, he or she could probably refer a great speaker. Another simple idea is to promote a Java Users Group via Twitter, Facebook, or other means. Some of the ideas presented spanned categories. For example, writing a blog post could be an idea for furthering a Java User Group, for helping an open source project, for helping adopt a JSR, etc. I have blogged myself on how blogging can help other developers. Other example of where ideas from different categories overlapped are any of the cases where helping an open source project is also helping a JSR because that open source project is the JSR’s reference implementation. For example, previous work helping with Tomcat, GlassFish, or EclipseLink was helping the respective JSRs for which those projects are the reference implementations. Downloading OpenJDK 8 releases and using them, writing bug reports on them, and writing about them are all ways to help the OpenJDK project in particular and to help the development of JDK 8 in general. Some ideas were almost as simple as falling off a log. For example, one can download the reference implementation (RI) of a JAR and try it out. Recounting one’s favorite JavaOne experiences or lessons learned was another. Other easy ideas include simply requesting a new feature for a forthcoming JSR, writing a FAQ for a favorite or newly learned API or open source project, or even simply creating a simple web page listing available resources for more information on a particular subject. The three speakers at this session reiterated that there are selfish motivations to improving Java. They were able to tie better Java user groups, better Java adoption, and so forth to benefits for all of us. They pointed out, for example, that if typical developers help with more mundane tasks such as open source project documentation and responding to questions in forums, others can focus on development of new libraries and language features. Verburg mentioned a couple of times that we probably want Brian Goetz focused on improving the lambda expressions implementation in JDK 8 and we can help by working on mundane things surrounding that so that he can focus on the implementation itself. Contributing to open source projects allows us to enjoy better tools and frameworks and greater selection of tools and frameworks. The presentation slides were composed simply of the categories in which Java developers could help improve things with a list of bullets of the various ideas for each category. Those lists of ideas together obviously form one of the most important parts of the presentation and hopefully the presentation with those lists will be available online soon. Rather than regurgitate that list here, I have focused on a high-level description of the voice track the speakers provided to accompany the slides and lists of ideas. UPDATE – Vancura has made the list of all 101 ideas available on the JCP Program Office blog. One of the early themes already encountered frequently at JavaOne 2012 is the need for Java developers to contribute to the community and the success of Java and the Java ecosystem. Speakers from the Strategy Keynote and Technical Keynote repeatedly asked for community help and feedback and I have seen that theme expressed in other sessions of JavaOne already. Reference: JavaOne 2012: 101 Ways to Improve Java – Why Developer Participation Matters from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
javaone-logo

JavaOne 2012: Scala Tricks

The first session I attended after lunch was Venkat Subramaniam‘s ‘Scala Tricks,’ held in the Hilton Golden Gate 3/4/5 conference room area. This is the first session in which I switched my planned session during JavaOne. I switched it last night as I look at my day’s schedule and realized that, although excited about Lambda, I felt like I had the familiarity with Lambda I was looking for at this point (thanks to the Technical Keynote and The Road to Lambda), and felt like I’d benefit more from attending ‘Scala Tricks’ than from attending the previously scheduled session ‘Jump-Starting Lambda Programming’ (which sounds packed anyway). Although some speakers prefer questions and comments be asked at the end, Subramaniam prefers that questions be asked when they arise. Subramaniam began with a quick summary of the basics of the Scala programming language. He showed that everything is an object in Scala by showing the Groovy/Ruby-like example 1.toString(). He stated that you can use Scala anywhere you use Java and should expect 40 to 60 percent less code than you’d write in Java. He added that, like Groovy, you can mix Scala and Java. He likes the conciseness and expressiveness of Scala. The approach used in this presentation was not to necessarily provide a tutorial on basics of Scala, but rather to approach introduction of Scala via examples. In many ways, this felt like a presentation equivalent of a ‘recipes’ or ‘cookbook.’ Subramaniam’s first real example was reading a file (he went for one of Java’s ugly points early!): val stuff = Source.fromFile('sample.scala').mkString() [See this StackOverflow thread for differences between toString() and mkString()] There is no signs of exception handling. Like Groovy, Scala does not enforce catching or re-throwing/stating checked exceptions. Removing exception handling makes the code much more concise. Subramaniam stated that ‘one of the things I really like about Scala is there is no ceremony to deal with.’ He described ‘ceremony’ as the stuff you have to do before you can do the stuff you want to do. He pointed out that people teaching Java to someone else are reminded of how difficult Java can be to learn because there are so many aspects of ceremony to learn. The next example Subramaniam showed was returning multiple values from a method. In this case, he wanted to return two names: ‘James’ and ‘Bond.’ He showed creation of an immutable Tuple: def createAgent() = { ('James', 'Bond') } He showed how the above Tuple could be accessed. val agent = createAgent() println(agent._1 + ' ' + agent._2) Subramaniam showed what happens when he tried to access agent._3 in the code above: it led to a compile-time error because there aren’t three fields. This was an example of a runtime error being moved to a compile-time error. One of the Scala features that Subramaniam focused on that I also like is its requirement that method arguments be specified as mutable or immutable (val or var) when writing the signature. I liked the var modifier clear back when programming and hacking with Pascal and am glad to see this differentiation. Subramaniam covered a ‘very convenient feature’ that is on the borderline between ‘really cool’ and ‘really scary': the implicit keyword. It can, of course, be difficult to know when implicit keyword kicks in, especially if it comes from an import. Subramaniam joked that its use helps improve ‘job security.’ Another example was based on implementing a factorial method in Scala. As is almost always the case, the factorial was implemented with recursion. Subramaniam forced it to recurse enough times to lead to a StackOverflowError. He cited Structure and Interpretation of Computer Programs and then talked about how the code could be written in Scala so that it appears to be recursion, but the Scala compiler will optimize it to be a procedural loop. The @scala.annotation.tailrec annotation can be used to enforce that tail recursion applies, allowing for this compile time optimization to occur. This is pretty nifty, but it’s also a reminder that recursion should not be used solely because it’s cool. Subramaniam stated that ‘Scala says XML should be treated with the respect it deserves’ rather than forcing XML content into Strings. He then showed code in which a variable was assigned to an XML element directly without quotation marks. He showed how use of curly braces around that variable assigned directly to XML allows access to the body of that XML element. He said there is much more to Scala’s XML support. ‘Producing code that spits out XML should be given to people in prison’ was Subramaniam’s opening statement to introduce Scala’s support for generation of XML. He showed how he could embed Scala code within curly braces within the defined XML. This allowed him to define a function that would use Scala trickery to easily build XML based on an underlying Map of data. That is impressive! Traits are probably one of the most heralded aspects of Scala and Subramaniam covered them in his presentation. He stated that one of the problems with multiple inheritance was C++’s implementation of it. He talked about method pollution and showed how use of the with keyword, coupled with the extends keyword and trait keyword, supports traits. Subramaniam showed how traits can be applied to individual instances rather than to a general class when so desired (when the instance is different than the general class). His example here was that dogs are friends and so need the trait at the class level while most cats are not friends and so he modeled his cat’s individual instance with the friend trait rather than applying the fried trait to the Cat class. Subramaniam stated that he’d not let anyone use Java who had not first read Effective Java. He said that Java has been fixed to meet the approaches described in Effective Java and that version described in Effective Java is known as Scala. Subramaniam pulled off well one of the most challenging things I’ve seen in presentations. Most speakers who turn to their IDE quickly lose the audience as they lose themselves in the code and start talking to the monitor. Subramaniam, however, did a nice job of keeping the code samples small and displayed them with large font. This allowed for easy focus on the important things. His is one of the few code-heavy presentations I’ve seen that is easy to stay attentive to. The only downside is that these examples are not in the slides, but he said that they’ll be available for download. This was another presentation that was everything I had hoped for. I’m becoming motivated to play around with Scala again and picked up some nice ideas. It didn’t hurt that Subramaniam is a skilled and practiced speaker and entertains his audience while educating them. Some speakers, even at this JavaOne 2012, have required extra effort on the audience’s part to remain attentive, but that wasn’t the case here. Reference: JavaOne 2012: Scala Tricks from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
javaone-logo

JavaOne 2012: What’s New in Scala 2.10

After getting lunch, I went to Hilton Golden Gate 6/7/8 to see Martin Odersky‘s (Typesafe) presentation ‘What’s New in Scala 2.10.’ It is always an opportunity to hear a language’s creator discuss the language that he created. Odersky stated by providing a brief history of Scala:1996-1997 Pizza1998-2000 GJ, Java generics, javac2003-2006 The Scala ‘Experiment’2006-2009 Industrial Strength Programming LanguageScala is a unifier between worlds of functional programm and object-oriented programming and is a unifier of agile (with lightweight syntax) and safe/performant/strongly typed programming. Functional programming on the rise. 12 years ago OOPSLA had ten times attendance of ECOOP but today ICFP has three times ECOOP attendance and OOPSLA is no longer an independent conference. Functional programming important now because of market drivers. Odersky stated, ‘The world of software is changing because of hardware trends’ and added, ‘Moore’s Law is now achieved by increasing number of cores rather than clock cycles.’ In this new world of clock cycle limitations, we have a ‘Triple Challenge': ‘Parallel’ (how to use multicore), ‘Asynchronous’ (how to deal with asynchronous events), and ‘Distributed’ (how to deal with failures). In this world, ‘every piece of mutable state you have is a liability.’ The ‘problem in a nutshell’ is ‘non-determinism caused by concurrent threads accessing shared mutable state.’ non-determinism = parallel processing + mutable state Non-deterministic behavior is something ‘we are uncomfortable with’ and ‘avoiding mutable state means programming functionally.’ Eliminating mutable state is the one thing we have control over and can change. This is why Odersky believes that functional programming is just now rising out of the academic world to be used in the business world. Functional programming has always been inherently tied to fancy machines. Odersky pointed out that writing functional programming is quite different than writing object-oriented programming. The ‘thought process of functional programming is really quite different’ because it requires thinking of things spatially rather than temporally. Having made the case for functional programming, Odersky asked if we should all move to Haskell now? He answered that there are still important things learned from object-oriented development. His slide stated, ‘What the industry learned about OO decompositionis analysis and design stays valid.’ We want to have functions and objects in our coding. Odersky quoted Grady Booch, ‘Objects are characterized by state, identity, and behavior. Odersky maintains we now want to ‘eliminate, or at least reduce, mutable state.’ We want to get away from mutable state being the default. Odersky also believes we want to get away from referential equality and focus on structural equality. Odersky listed simplicity, productivity, and fun as other reasons for functional programming in addition to dealing with the hardware environment of parallel processors. Odersky moved from general functional programming discussion to specific Scala discussion. His bullet stated, ‘Scala can be as simple or as complex as you like, but it’s best when it’s simple.’ He cited Kojo as an example of Scala’s alignment with simplicity. He also referenced ‘Sadaj’s great talks.’ Odersky then began to work on some examples based on Ninety-Nine Scala Problems. Scala 2.10 is ‘very close to RC1′ and is in ‘code freeze’ while working on three remaining code blockers and several documentation blockers. Odersky talked about the Scala Improvement Process (SIP) and showed the ‘Pending SIPs’ that are accepted, postponed, or rejected. SIP 12 (‘String Interpolation’ addresses the weaknesses and difficulties associated with concatenation of Strings using the + operator. It is shorter and safer to use string interpolation. The biggest obstacle to adding string interpolation was that $ is ‘already a legal character in strings.’ Rather than using a ‘special trick’ of placing ‘s’ in front of strings for which $ should be escaped and used for string interpolation, Scala will use more general solution of recognizing arbitrary IDs. The ‘f’ string processor will interpret $ and %. Developers could implement their own string processors and Odersky showed examples of this that might be written for XML and JSON. Odersky stated that, ‘Adding XML support in Scala is something that did not turn out so well.’ He says now there would be an advantage to using an XML string processor instead and remove the XML specific library dependency Scala currently has. Odersky addressed why Scala does not have extension methods that ‘other cool languages’ have. He answered that Scala does not have extension methods because ‘we can’t abstract over them.’ It is ‘impossible to have them implement an interface.’ Odersky introduced SIP 11 (‘Implicit Classes’). One issue to think about here is ‘runtime overhead.’ SIP 15 (‘Value Classes’) introduces idea that Scala classes could extend AnyVal instead of Object. Classes extending AnyVal are ‘value classes’ and are always unboxed. Odersky showed what code using these value classes would expand (be compiled) to. The implicit keyword in Scala enables ‘very poweful’ implicit conversions, but Odersky warns that ‘they can be misused’ particularly if ‘there are too many of them.’ I like that Odersky likened them to chocolate: a little is very good, but too much leads to a stomach ache. You can turn off implicit conversion warnings by ‘bringing the identifier scala.langage.implicitConversions into scope (typically via import). Odersky briefly discussed SIP 18 (‘Language Imports’) and then covered ‘Better tools.’ I found Odersky’s goal for his language to be interesting: Odersky wants to ‘make Scala the language of choice for smart kids.’ To him, it’s the ideal of what the language should be. One attendee felt that boilerplate code is one of the best forms of simplicity and wondered whether Scala was missing its goal of simplicity by displacing boilerplate code. Odersky replied that boilerplate code would not be his preferred form of simplicity. Odersky stated that Scala is largely mature from the perspective of significant API changes and so forth. He pointed out that all languages reach the point where it is difficult to make wholesale fundamental changes and that Scala’s changes are smaller in nature now than they were in the late 2000s. In response to an audience member’s question, Odersky said that the best way to learn Scala is to read a book or take a course. He says many of the people he sees who try and struggle with Scala tried to learn it by studying its API documentation. When asked to compare Scala to Groovy and JRuby, Odersky said that Scala is about as complicated as JDK 7 and will be less complicated than JDK 8. He feels Groovy is more complicated because it is a superset of Java. This is an interestingly different perspective on complexity. I have found Groovy to be very simple to learn, but I do have years of Java experience. I wonder if someone without Java experience would find Scala less difficult to learn. For me, even with all of Scala’s great features, it cannot be easier to learn than Groovy was. Another audience member’s question led to Odersky mentioning some alternate IDE support (including Emacs and IntelliJ IDEA) for Scala in addition to ScalaIDE. There is a NetBeans plugin for Scala. Odersky pointed out something I like about Scala in response to another question. He stated that Scala allows the developer to easily specify a piece of data is mutable. I like that Scala ‘does not prejudice’ against mutable data and allows the developers to choose to do so if they want to. I really don’t like it when ‘opinionated software’ forces me to do what the framework’s or language’s author thinks is best. I really enjoyed this presentation. I had changed from a differently planned session to this one last night and am happy with the change (although the other likely would have been good as well). My only concern about this presentation had been that, given my lack of Scala familiarity, that I’d be overwhelmed by discussion of new Scala 2.10 features without proper foundation. Fortunately for me, Odersky did not get into Scala 2.10-specific features until half way into the session. His coverage of functional programming and basics and history of Scala were helpful to me in general and were helpful specifically in preparing me to appreciate the new Scala 2.10 features. Between this presentation and the Scala Tricks presentation, my interest in trying out Scala is being renewed. Don’t forget to share! Reference: JavaOne 2012: What’s New in Scala 2.10 from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
eclipse-logo

Customize PMD in Eclipse with your own rules

PMD is very nice Java code scanner which helps you avoid potential programming problems. It can be easily extended to your needs, and this post will bring you simple example of custom PMD rules related to JPA’s @Enumerated annotation usage. Before you’ll continue the reading, you should check one of my previous posts – JPA – @Enumerated default attribute. When you work with the group of people on JPA project, it is almost certain that one of the developers will use @Enumerated annotation without defining the EnumType, and if you don’t use strict data validation on the DB level (like column level constraints), you will fall into deep troubles. What we would like to achieve is reporting an error when one uses @Enumerated without the EnumType: @Entity @Table(name = 'BENEFITS') public class Benefit implements Serializable { ... @Column(name = 'BENEFIT_TYPE') @Enumerated public BenefitType getType() { return type; } ... }and a warning if one uses @Enumerated with ORDINAL EnumType: @Entity @Table(name = 'BENEFITS') public class Benefit implements Serializable { ... @Column(name = 'BENEFIT_TYPE') @Enumerated(EnumType.ORDINAL) public BenefitType getType() { return type; } ... }We can achieve our goal in two ways, either describing the PMD Rule in Java, or using XPath – I’ll focus on the second way in this post. Let’s start from the beginning ;) – we have to download PMD first (I used version 4.2.5, pmd-bin-4.2.5.zip), unpack it somewhere, change the working directory to the unpacked PMD directory, and run the Rule Designer (it can be found in ./bin/designer.sh). You should see something like this:Let’s put the code we want to analyze into the source code panel, and click ‘Go’ button:In the middle of Abstract Syntax Tree panel you may see: Annotation / MarkerAnnotation / Name structure corresponding to our @Enumerated annotation without defined EnumType. To match it we will put into XPath Query panel following XPath expression: //MarkerAnnotation/Name[@Image = 'Enumerated'] When you click on the ‘Go’ button now:you will see at the bottom right panel that the match was found :) – XPath Query is correct :). Now when we have the XPath Query we have to define the rule using it, let’s open new XML file, name it jpa-ruleset.xml, and put into it: <ruleset name='JPA ruleset' xmlns='http://pmd.sf.net/ruleset/1.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd' xsi:noNamespaceSchemaLocation='http://pmd.sf.net/ruleset_xml_schema.xsd'> <description>JPA ruleset</description> <rule name='AvoidDefaultEnumeratedValue' message='By default @Enumerated will use the ordinal.' class='net.sourceforge.pmd.rules.XPathRule'> <priority>2</priority> <properties> <property name='xpath' value='//MarkerAnnotation/Name[@Image = 'Enumerated']' /> </properties> </rule> </ruleset>As you see we are using net.sourceforge.pmd.rules.XPathRule as the rule class, and define xpath property for this rule holding our XPath Query. Priority in the above example means: 1 – error, high priority, 2 – error, normal priority, 3 – warning, high priority, 4 – warning, normal priority and 5 – information. We will add another rule to our JPA ruleset, responsible for reporting a warning when @Enumerated is used with explicit ORDINAL EnumType – it can be either @Enumerated(EnumType.ORDINAL) or @Enumerated(value = EnumType.ORDINAL), therefore we need an alternative of two XPath expressions now: <rule name='EnumeratedAsOrdinal' message='Enumeration constants shouldn''t be persisted using ordinal.' class='net.sourceforge.pmd.rules.XPathRule'> <priority>4</priority> <properties> <property name='xpath' value=' //SingleMemberAnnotation/Name[@Image = 'Enumerated']/following-sibling::MemberValue//Name[@Image = 'EnumType.ORDINAL'] | //NormalAnnotation/Name[@Image = 'Enumerated']/following-sibling::MemberValuePairs/MemberValuePair[@Image = 'value']//Name[@Image = 'EnumType.ORDINAL']' /> </properties> </rule>Now, when we have ruleset holding those two rules, we will import it into Eclipse IDE. At this point I’m assuming that you have already installed PMD plugin for Eclipse (see: PMD – Integrations with IDEs). Open Eclipse Preferences, find the PMD section and expand it, you should see:click on ‘Import rule set …’select the file holding the ruleset, choose if you want to import it by reference or copy (in this case your ruleset name will be ignored and ‘ pmd-eclipse‘ name will be used), and you should see our two rules added to the list:Perform the necessary build when asked by eclipse, and before you’ll start enjoying our new rules, check the project properties:‘Enable PMD’ option should be turned on to let PMD check your code on-the-fly, our newly added rules should be active for this project (they will be by default). Let’s write some ‘bad code’ now, matching the first rule defined by us:When you point the red marker on the left with your mouse you will see the rule message, as defined in XML:The second rule matching:and the message, as defined in XML:Few links for the dessert:How to write a PMD rule XPath Rule Tutorial How to make a new rule setReference: Customize PMD in Eclipse with your own rules from our JCG partner Micha? Ja?tak at the Warlock’s Thoughts blog....
agile-logo

Using Story Mapping For Defining Business Requiremets

Story mapping is a lightweight and collaborative approach to defining and structuring user requirements. Story mapping involves describing the system as a list of features that provide a sequential story of requirements in a user-centric way. It supports iterative delivery where the story is divided into Features which can be prioritized and grouped by planned Releases/Minimum Marketable Features. Approach To come up with a Story Map, start out by identifying user personas or the major categories of users that gain value from the system. Next, identify the business/user goals or the major objectives that the system must support. For each goal, determine the user activities or the sequential events that the user needs to do in order to get value. Finally, break the activities down into explicit system Features that have real tangible business value.Once the overall narrative of the system is understood, the Story Map can be used to prioritize the Features. For each of the activities, vertical component can be added to define the priority of the features with respect to each other. Each set of Features for a particular user activity are reshuffled and stacked vertically according to their relative priority. The top row of the Features on the story map represent the backbone of the product, which is the Minimum Marketable Features (MMFs) that are required in order to have a functional product. Features that may be delivered later (or sometimes never) are placed lower down.Once overall prioritization of Features necessary to support each user activity is understood, the entire Story Map can be divided by planned Releases/Minimum Marketable Features. Horizontal lanes can be used to divide different MMFs from each other. The Story Map can then be used to tell a narrative for a particular MMF. This is done by traversing the map from left to right and only looking at the Features within a particular lane.Story Mapping enables both a top-down and bottom-up perspective of the system to emerge. It facilitates understanding of the system from the users’ perspective. It also lends itself to iterative delivery in that prioritization and grouping of Features into Releases/Minimum Marketable Features is supported. Don’t forget to share! Reference: Using Story Mapping For Defining Business Requiremets from our JCG partner Alexis Hui at the Lean Transformation blog....
java-logo

JavaOne 2012: Mastering Java Deployment

After grabbing an Italian Classic Combo for another JavaOne 2012 lunch, I headed to Hilton Imperial Ballroom B to see the presentation ‘Mastering Java Deployment.’ The speakers, both from Oracle, were Mark Howe and Igor NekrestyanoHowe stated that a goal of the deployment team is to help Java developers deploy their applications to platforms of choice. He started by discussing ‘feature deprecation.’ In some cases, there are multiple ways to do the same thing. An example of this is jarjar and pack200. By deprecating redundant (especially older) approaches, they don’t have to spend as much time supporting and fixing bugs on these seldom used things. Howe showed a table of features being deprecated and removed in JDK 7, JDK 8, and JDK 9. In general, anything being deprecated and/or removed has alternatives and folks using the deprecated/removed features should start looking at which alternative works best for them. As of JRE 7 Update 6, a totally Oracle-supported JRE will be issued for Mac OS X. Oracle’s intention is to fix bugs and add features across JVMs for all deployment environments at the same time. The JRE 7 is ‘mostly compatible’ with Apple’s JRE 6. One change is to be more aligned with Oracle’s JVM support for other platforms and have Oracle’s updated update the JRE on Mac OS X rather than using the Mac ‘Software Update.’ One caveat is that ‘Chrome on Mac is currently unsupported (32-bit only).’ In continuing the theme of platform JVM feature polarity, JavaFX is now delivered with JRE for Linux. Howe’s ‘Convergence of Java and JavaFX’ slide showed a table indicating the progress of converging Java and JavaFX versions. The goal is for JavaFX to be one of the core libraries in the Java specification. Plans for JDK 8 include ‘Java launcher able to run JavaFX applications’ and ‘jfxrt.jar on boot classpath for java and javac.’ Howe introduced the Java Deployment Toolkit and described it as a ‘tool to simplify deployment of Java content in the browser.’ He contrasted deployJava.js (‘original version’) with dtjava.js (‘better JavaFX support and portability’). The dtjava.js version ‘supports all deployment scenarios on all platforms’ though there is no autostart on Mac or Linux. Howe talked about WebStart and explained that ‘user experience is not quite as nice as you’d like it to be.’ He contrasted this with use of dtjava.js that allows developer to set parameters for control of launching from JavaScript. It makes for more control and better user experience. This also removes need for fixed code base. The code shown in a slide for using dtjava.launch requires JRE 7 Update 6 or later. The goal of packaging tools is to ‘simplify deployment for application developers.’ The command-line tool bin/javfxpackager (or set of Ant tasks lib/ant-javafx.jar) can be used with JDK 7 Update 6. The ‘latest release of NetBeans‘ supports these. Howe covered several motivations for completely self-contained applications. A self-contained applications contains ‘all the artifacts necessary to run your application.’ It has a private copy of the Java runtime and removes the dependency on the external JRE. Many of the motivations for self-contained applications revolved around issues of acquiring a current JRE to run the application. Benefits of self-contained applications include the feeling of a native application, improved compatibility, easier deployment on a fresh system, optional administrative privileges, and support of newer distribution channels such as the Apple Apps Store. The caveats of self-contained applications include larger size (JRE included), ‘download and run’ instead of WebStart’s ‘click and launch,’ need to build package per platform, and other current limitations such as package needing to be built on the target platform and application updates being the responsibility of the developer.’ To create a self-contained application, one needs JDK 7 Update 6 as well as optional third party tools such as WiX to build MSI on Windows. Howe showed a slide with Ant code for generating the self-contained application. The Developer Preview will allow a developer to select target version of JVM (current choices are JRE 7 Update 6 or JRE Update 10). The Developer Preview is expected to be available with JRE 7 Update 10. JDK 7 Update 10 is also anticipated to support Mac App Store support. Like so many other presentations at JavaOne 2012, community feedback was solicited. In this case, the deployment team would like to know what people want and need for more effective web deployment of Java applications. Howe had a nice slide comparing executable JAR to WebStart to self-contained application. Mac App Store does not allow applications to ‘rely on optionally-installed technology.’ Other requirements include need for application to ‘run in a sandbox’ and ‘follow UI guidelines.’ Certain APIs (FileChooser) should be avoided. See JavaOne 2012 slides for ‘Deploy Your Application with OpenJDK 7 on Mac OS X’ and future version of JavaFX Deployment Guide for more details. Howe’s ‘key points to remember’ include merging of Java with JavaFX, new platforms for Java, new deployment options (self-contained application bundle and deployment to Mac App Store), and deprecation of old deployment features. One of the attendees asked if there is a way to share a single JRE among multiple shared self-contained applications. The answer is that there currently is not a way to do this, but that a JRE can optionally not be included in the otherwise self-contained application. In responses to another question, the speakers stated they are not aware of any plans to deprecate Swing. They also responded to yet another question that there is currently no Maven support for building self-contained applications (use Ant or NetBeans). There were several good slides shown in this presentation that I’d like to look at more closely in the future. Fortunately, Howe stated that these will be made available. Much of what was covered in this session will be open source and audience members were encouraged to contribute to the open source projects. Reference: JavaOne 2012: Mastering Java Deployment from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
java-interview-questions-answers

Your first Juzu portlet on eXo platform

Juzu is a Buddhist prayer bead. One sentence and I am sure you have already learnt something, impressive no? Ok, I won’t speak about Buddhism here. Juzu is also a new framework for developing portlets (and standalone applications soon) very quickly. You can find all the information you need on the Juzu website. Now let’s create our first portlet with Juzu !Creating a new project Juzu comes with a maven archetype. We can use it to quickly create our first application : mvn archetype:generate \ -DarchetypeGroupId=org.juzu \ -DarchetypeArtifactId=juzu-archetype \ -DarchetypeVersion=0.5.1 \ -DgroupId=org.example \ -DartifactId=myapp \ -Dversion=1.0.0-SNAPSHOT This creates a juzu project in a myapp folder.Deploying the Juzu portlet Before deploying the application, you need to build it. Simply run mvn clean package in the myapp folder. It will generate a myapp.war under your myapp/target folder. We are now ready to deploy the portlet in a portal container. We will use the latest GateIn release (3.4), the tomcat bundle version. Once downloaded, install it by unzipping it in the location of your choice. The only thing you need to do is to drop the myapp.war file in the webapps folder, and start GateIn with bin/gatein.sh run. Once started, add your portlet in a page. You should see :Great ! You just finished your first Juzu portlet ! Let’s explore the project before enhancing it.Exploring the project The project structure looks like this :The mandatory web.xml is there. It does not contain anything. portlet.xml The archetype generates a basic portlet.xml with some juzu init parameters : <?xml version='1.0' encoding='UTF-8'?> <portlet-app xmlns='http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd' version='2.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsdhttp://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd'><portlet> <portlet-name>SampleApplication</portlet-name> <display-name xml:lang='EN'>Juzu Sample Application</display-name> <portlet-class>juzu.portlet.JuzuPortlet</portlet-class> <init-param> <name>juzu.run_mode</name> <value>prod</value> </init-param> <init-param> <name>juzu.inject</name> <value>weld</value> <!-- <value>spring</value> --> </init-param> <supports> <mime-type>text/html</mime-type> </supports> <portlet-info> <title>Sample Application</title> </portlet-info> </portlet> </portlet-app> The portlet-class is the generic Juzu portlet class juzu.portlet.JuzuPortlet. This class declares 2 init parameters :juzu.run_modedev : changes made on source files are automatically hot recompiled and reloaded, so you don’t need to redeploy your application to test them. This is a real productivity boost while developing an application ! prod : “classic” mode, where you need to recompile and redeploy your application to apply your changes.juzu.inject – defines the inject implementation. Two implementations are currently supported : weld (CDI Reference Implementation) and spring.The Juzu portlet class uses the package-info.java file to gather needed extra information. The portlet.xml file also contains basic information about the portlet : portlet-name, display-name and portlet-info. You can change them or add some others if needed. package-info.java This file contains all the configuration of the application. The file allows to activate plugins, add JS/CSS resources, … but let’s keep it simple for now. The only mandatory configuration is the declaration of the application, thanks to the @juzu.Application annotation. You have to declare the base package of your application, in our case org.sample. Controller.java This class is a Juzu controller. It is composed of a view method index (annotated with @View) which allows to render the index template. The path of the index template is set with the @Path annotation. By default, Juzu uses the templates package of the application as its root path. So in our case, the template is located at org/sample/templates/index.gtmpl.Switching to dev mode Now that we know a little bit more about what is a Juzu application, let’s improve a little bit our basic helloworld application. First of all, we will switch from prod to dev mode, in order to quickly test our changes. For that, edit your portlet.xml file and change the value of the init-param juzu.run_mode to dev. Then build your application and drop the war in the webapps folder of GateIn. Here you don’t need to stop/start GateIn as the webapp will be automatically redeployed. As we did not change anything in the source files of our application, you should see the same “Hello World” message in your portlet. In order to test the dev mode, you can for instance rename the file webapps/myapp/WEB-INF/src/org/sample/templates/index.gtmpl to index2.gtmpl. After refreshing your page, you will get the following message :Now edit webapps/myapp/WEB-INF/src/org/sample/Controller.java and change @Inject @Path('index.gtmpl') Template index; by @Inject @Path('index2.gtmpl') Template index; and refresh your page once again. Everything back to normal ! Pretty cool, isn’t it ?Forms, Actions and type safe template parameters We will create an application which displays the map of the location choosen by the user. Firstly, update your index.gtmpl template : #{param name=location/} #{param name=mapURL/}Location : <form action='@{updateLocation()}' method='post'> <input type='text' name='location' value='${location}'/> <input type='submit'/> </form> <br/> <%if(location) {%> <div id='map'> </div> <%}%>#{param name=location/} and #{param name=mapURL/} declares 2 type safe template parameters which will be used latter in our Controller the form contains a input text, and submit to our juzu controller action updateLocation finally, if a location is specified, the maps is displayedNow, let’s update update our Controller.java : package org.sample;import juzu.Action; import juzu.Path; import juzu.Resource; import juzu.Response; import juzu.View; import juzu.template.Template;import javax.inject.Inject; import java.io.IOException; import java.util.HashMap; import java.util.Map;public class Controller {@Inject @Path('index.gtmpl') org.sample.templates.index index;@View public void index() throws IOException { index('', ''); }@View public void index(String location, String mapURL) throws IOException { index.with().location(location).mapURL(mapURL).render(); }@Action public Response updateLocation(String location) throws IOException { String mapURL = 'https://maps.google.fr/maps?f=q&source=s_q&hl=en&geocode=&q=' + location + '&aq=&t=m&ie=UTF8&hq=&hnear=' + location + '&z=12&output=embed';return Controller_.index(location, mapURL); } }the index template is now of type org.sample.templates.index. This class is generated thanks to the annotations, and is a subclass of Template. Using this specific type will allow us to leverage declared template parameters, location and mapURL in our case. the default index View now calls a new index View which accepts the location and mapURL arguments. This new view uses the index template class and its fluent syntax (do you like it ? Personnaly I do). Thanks to the declaration of the location and mapURL parameters in the template, the org.sample.templates.index template class accepts a location method and a mapURL method to set their values. the updateLocation method is defined as an action thanks to tthe @Action annotation. It is called by the form to retrieve the correct URL (building the map URL is a basic example, generally you will call your services here). Then it redirects to the index View method in order to render the index template. Note the _ at the end of the Controller name. The class Controller_ is the “annotations processed” version of the Controller class.If you did all these changes in the deployed version of your application (in webapps/myapp), you just need to refresh, and you should be able to enter a location and then see the corresponding map :Ajax Juzu provides some ease to use Ajax in your application. We will use them to avoid reloading our page when submitting a new location in our form. The Ajax plugin needs JQuery. We can add it to our application by simply dropping the JQuery js file in the project and declare it in the package-info.java file with the Asset plugin (I dropped the JQuery js file in public/scripts) : @juzu.plugin.asset.Assets( scripts = { @juzu.plugin.asset.Script( id = 'jquery', src = 'public/scripts/jquery-1.7.1.min.js') } ) We will now update our controller in order to add a new method which will only provide the map URL : @Ajax @Resource public Response.Content<Stream.Char> getMapURL(String location) throws IOException { String mapURL = 'https://maps.google.fr/maps?f=q&source=s_q&hl=en&geocode=&q=' + location + '&aq=&t=m&ie=UTF8&hq=&hnear=' + location + '&z=12&output=embed';return Response.ok('{\'mapURL\': \'' + mapURL +'\'}').withMimeType('application/json'); } Note that this new method is not annotated with @Action anymore. Annotating a method with @Ajax will make it accessible for Ajax calls. The @Resource annotation makes this method send the entire response to the client. That’s what we want as this method simply creates the new URL and sends it back to the client as a JSON response. Finally, we have to update our template file to add the Ajax call : #{param name=location/} #{param name=mapURL/}<script> function submitLocation(location) { $('#map').jzAjax({ url: 'Controller.getMapURL()', data: {'location': location} }).done(function(data) { $('#map > iframe').attr('src', data.mapURL); }); return false; } </script>Location : <form onsubmit='return submitLocation(this.location.value)'> <input type='text' name='location' value='${location}'/> <input type='submit'/> </form> <br/><div id='map'> </div> The submission of the form now calls the submitLocation javascript function. This function uses the juzu Ajax function jzAjax (which uses the ajax JQuery function under the hood). This function calls the URL provided in the url param with the parameters provided in data. So here it will call the newly created method of our Controller and receive the new map URL in JSON : {'mapURL': 'https://maps.google.fr/maps?f=q&source=s_q&hl=en&geocode=&q=nantes&aq=&t=m&ie=UTF8&hq=&hnear=nantes&z=12&output=embed'} Then we just use JQuery to update the map. Once again, simply refresh your page to see it in action ! You can now learn more on Juzu by going to the website or watching the screencasts. Happy coding and don’t forget to share! Reference: Your first Juzu portlet from our JCG partner Thomas Delhimenie at the T’s blog blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

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