Featured FREE Whitepapers

What's New Here?

oracle-weblogic-logo

Dealing with Weblogic Stuck Threads

Definition or What is a Stuck Thread?   WebLogic Server diagnoses a thread as stuck if it is continually working (not idle) for a set period of time. You can tune a server’s thread detection behavior by changing the length of time before a thread is diagnosed as stuck ( Stuck Thread Max Time), and by changing the frequency with which the server checks for stuck threads. Check here to see how to change the Stuck Thread Max Time. The problem or Why are Stuck Threads evil?   WebLogic Server automatically detects when a thread in an execute queue becomes “stuck.” Because a stuck thread cannot complete its current work or accept new work, the server logs a message each time it diagnoses a stuck thread. If all threads in an execute queue become stuck, the server changes its health state to either “warning” or “critical” depending on the execute queue:If all threads in the default queue become stuck, the server changes its health state to “critical.” (You can set up the Node Manager application to automatically shut down and restart servers in the critical health state. For more information, see “Node Manager Capabilities” in Configuring and Managing WebLogic Server.) If all threads in weblogic.admin.HTTP, weblogic.admin.RMI, or a user-defined execute queue become stuck, the server changes its health state to “warning.”So practically, a couple of Stuck Threads might not crash your server preventing it from serving request, but it is a bad sign. Usually, the number of stuck threads will increase and your server will eventually crash. What you can do to avoid your application completely fail?   WebLogic Server checks for stuck threads periodically (this is the Stuck Thread Timer Interval and you can adjust it here). If all application threads are stuck, a server instance marks itself failed, if configured to do so, exits. You can configure Node Manager or a third-party high-availability solution to restart the server instance for automatic failure recovery.You can configure these actions to occur when not all threads are stuck, but the number of stuck threads have exceeded a configured threshold:Shut down the Work Manager if it has stuck threads. A Work Manager that is shut down will refuse new work and reject existing work in the queue by sending a rejection message. In a cluster, clustered clients will fail over to another cluster member.Shut down the application if there are stuck threads in the application. The application is shutdown by bringing it into admin mode. All Work Managers belonging to the application are shut down, and behave as described above. Mark the server instance as failed and shut it down it down if there are stuck threads in the server. In a cluster, clustered clients that are connected or attempting to connect will fail over to another cluster member.How to identify the problem?   The most recommended way is to check the thread dumps. Check Sending Email Alert For Stuck Threads With Thread Dumps post of Middleware magic, to have Thread Dumps mailed to you automatically when they occur. Tools to help you with analyzing the Thread Dumps can be:TDA – Thread Dump Analyzer SamuraiHow to workaround the problem?   After you have identify the code that causes the Stuck Thread, that is the code which execution takes more than the Stack Thread Max Time, you can use Work Manager to execute your code. Work Managers have a Ignore Stuck Thread options that gives the ability to execute long running jobs. See below:Below are some posts on how to create a Work Managerhttps://blogs.oracle.com/jamesbayer/entry/work_manager_leash_for_slow_js http://jdeveloperfaq.blogspot.com/2011/05/faq-34-using-weblogic-work-managers-to.htmlTest: How to create a Stuck Thread?   How to create a Stuck Thread in order to test your weblogic settings? Put a breakpoint in a backing bean or model method that is called with you request. If you wait in the breakpoint for Stuck Max Thread Time, you notice a Stuck Thread trace will be shown in servers log: <16 =?? 2011 12:28:22 ?? EET><Error><WebLogicServer><BEA-000337><[STUCK] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)' has been busy for "134" seconds working on the request "weblogic.servlet.internal.ServletRequestImpl@6e6f4718[ GET /---/---/----/---/days.xhtml HTTP/1.1 Connection: keep-alive User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-GB,en-US;q=0.8,en;q=0.6 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: JSESSIONID=DYG5TDTZSnKLTFw5CMMdLCD9sPsZS4Jqlmxj9wdGNyt1BnPcfNrR!-1520792836]", which is more than the configured time (StuckThreadMaxTime) of "60" seconds. Stack trace: --------------------------------------------(--------------------.java:83) javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:823) com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:285) com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185) com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129) javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848) org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:55) org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:43) org.primefaces.component.fieldset.FieldsetRenderer.encodeContent(FieldsetRenderer.java:95) org.primefaces.component.fieldset.FieldsetRenderer.encodeMarkup(FieldsetRenderer.java:76) org.primefaces.component.fieldset.FieldsetRenderer.encodeEnd(FieldsetRenderer.java:53) javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:878) javax.faces.component.UIComponent.encodeAll(UIComponent.java:1620) javax.faces.render.Renderer.encodeChildren(Renderer.java:168) javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848) org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:55) org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:43) org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:229) org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:152)More digging:Excellent post by Frank Munz: WebLogic Stuck Threads: Creating, Understanding and Dealing with them. Updated for Weblogic 12c. Includes sample app for creating Stuck Thread too. http://stackoverflow.com/questions/2709410/weblogic-stuck-thread-protectionsrc:Maxence Button excellent post: http://m-button.blogspot.com/2008/07/using-wlst-to-perform-regular.html http://download.oracle.com/docs/cd/E13222_01/wls/docs81/perfor/WLSTuning.html#1125714 http://download.oracle.com/docs/cd/E21764_01/web.1111/e13701/overload.htm http://java.sys-con.com/node/358060?page=0,0Reference: Dealing with Weblogic Stuck Threads from our JCG partner Spyros Doulgeridis at the ADF & Weblogic How To blog....
java-logo

Type Inference from Java 7

Every good programmer likes to write a concise but effective and optimized code. Type Inference is a way introduced in JDK 7 which will surely give you benefits of less typing. Its been a long time that you have using the java code in following manner. But have you ever thought of code duplication while initializing the specific implementation of Collections? Why there is a need to write the parameters two times during an intialization? List<string> names = new ArrayList<string>(); Map<string, Object> objectMap = new HashMap<string, Object>();  Now most of you would be thinking of initializing as a raw types as you had been doing in previous JDK version. Something like this. List<string> names = new ArrayList(); Map<string, object=""> objectMap = new HashMap(); So whats new in JDK 7? What benefits you will have from the new feature? So first we need to understand the difference between raw type and generic type intialization. A statements like this ensures that the implementation will contain the same parameter as specified during initialization. List<string> names = new ArrayList<string>(); In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map<String, List<String>> type: Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warningDiamond Operator   Okay Now I will introduce the new feature of JDK 7. So we have something called Diamond operator in JDK 7 which reduces your extra typing while initialization. Syntax: List<string> names = new ArrayList<>(); So it not only reduces your code but also ensures the type checking. Here is a more clear example explaining the benefits of type inference. Advanced Example: class Demo { void printStudentNames(List<string> names) { for(String name:names) { System.out.println("String name:"+name); } }public static void main(String[] args) { Demo demo = new Demo(); demo.printStudentNames(new ArrayList<>()); // It saved typing here in a method call too. List<string> names = new ArrayList<>(); printStudentNames(names); List<string> copyOfNames = new ArrayList<>(names); // It saved typing here in a copy contructor invocation too. } } Now what are its limitations? It won’t work in the case you use wildcards. Something like this Class Tree<t> {public void demoFunction(List<t> objList) { List<t> copyOfNames = new ArrayList<t>(objList); //This is not gonna work. } } In the above case the arguments passed in the copy constructor should be Collection<? extends T> So it wont accept the above inference type. Reference: Why do we need Type Inference from Java 7? from our JCG partner Saurab Parakh at the Coding is Cool blog....
specs2-logo

ScaTDD: Casting an eye over three major Test frameworks in Scala

Testing has traditionally been the gateway process for Scala development at a number of Java shops looking to evolve their tech stack with minimal disruption or committment. This posts hopes to cover three of the main testing frameworks in the Scala landscape, ( Specs2, Scalatest and Scalacheck) with an example of the classic FizzBuzz test, for how they can be used for fun and profit. So, the brief outline of the FizzBuzz requirement are that given a sequence of numbers:Any number divisible by 3 should return the String “Fizz” Any number divisible by 5 should return the String “Buzz” Any number divisible by both 3 and 5 should return the String “FizzBuzz” Otherwise the number should be returned as a StringAs a comparison, I’ve also included a sample Java JUnit test for this. The actual implementation code (included here) for this is trivial, (partly by design) as it is just to show illustrate the libraries being used.              My setup for this was using Eclipse v3.7.2 on Windows 7 with the  Scala IDE v2.0.1.v-2_09 plugin and Scala version 2.9.0.1. SPECS2 In a nutshellA meta framework for writing unit and acceptance tests by specification. Supports concurrent execution, mocking, reporting, scalatest and scalacheck feature support, datatable style testing and form based specification tests. The propject emerged from the original, (and now deprecated) Scala Specs BDD testing framework.Link http://etorreborre.github.com/specs2/ Version v2.9.2_v1.10 Ohloh http://www.ohloh.net/p/specs2 Active community Yes.A project initiated as Specs (v1) in mid 2007 and later evolving to a more general framework as Specs2 in 2010. The project has a number of comitters (though primarily driven by Eric Torreborre) and supporting resources such as a google group, blog and corporate backing for the project. Example package org.scalabound.scatdd.specs2import org.scalabound.scatdd.FizzBuzz import org.junit.runner.RunWith import org.specs2.runner.JUnitRunner// package unitTest { |> Scala IDE will not pick the class up as runnable if I sub-package it like this :-( @RunWith(classOf[JUnitRunner]) class FizzBuzzJUnitSpec extends org.specs2.mutable.Specification { "Multiples of both three and five" should { "print 'FizzBuzz'" in { FizzBuzz.eval(15) must_== "FizzBuzz" } } "Multiples of three only" should { "print 'Fizz'" in { FizzBuzz.eval(12) must_== "Fizz" } } "Multiples of five only" should { "print 'Buzz'" in { FizzBuzz.eval(10) must_== "Buzz" } } "Non multiples of five or three" should { "print the number back" in { FizzBuzz.eval(11) must_== "11" } } }// package acceptanceTest { |> Scala IDE will not pick the class up as runnable if I sub-package it like this :-( @RunWith(classOf[JUnitRunner]) class FizzBuzzUATSpec extends org.specs2.Specification { def is = "This specification is to check the FizzBuzz evaluator" ^ p^ "The FizzBuzz evaluator should" ^ "process a multiple of both three and five to return FizzBuzz" ! e1^ "process a multiple of three only to return Fizz" ! e2^ "process a multiple of five only to return Buzz" ! e3^ "process a non multiple of three or five to return the input" ! e4^ end def e1 = FizzBuzz.eval(15) must_== "FizzBuzz" def e2 = FizzBuzz.eval(12) must_== "Fizz" def e3 = FizzBuzz.eval(10) must_== "Buzz" def e4 = FizzBuzz.eval(11) must_== "11" }@RunWith(classOf[JUnitRunner]) class FizzBuzzDataTableSpec extends org.specs2.Specification with org.specs2.matcher.DataTables { def is = "Fizz Buzz testing with DataTables" ! e1// note: when the first column of a DataTable is a String, '!!' needs to be used instead of '!' // see: http://etorreborre.github.com/specs2/guide/org.specs2.guide.Matchers.html#DataTables def e1 = "spec name" || "input val" | "expected output" | "Multiple of both three and five" !! 15 ! "FizzBuzz" | "Multiple of three only" !! 12 ! "Fizz" | "Multiple of five only" !! 10 ! "Buzz" | "Non multiple of five or three" !! 11 ! "11" |> { (a, b, c) => FizzBuzz.eval(b) must_== c // (a, b, c) is a structural match on the table } }Feedback Generally the pain points I encountered were with Scala IDE rather than Specs2. Specifically, I had originally wanted to include the different types of tests in the same source file, but differentiated by different subpackages. Unfortunately, Scala IDE didn’t pickup the sub packages so this was a non starter. One minor weirdness was the inability to reorder my arguments for the DataTable spec test. Update: Thanks to Eric Torreborre this was solved using !! instead of ! when a String type is used for the first column in the DataTable !! It was a minor annoyance though. Otherwise, Specs 2 looks mature, with good tooling support and would likely be me go to choice as a ‘wrapper’ framework for testing. I found the default API for specifications clear and easy to use, and liked the seperation of tests to the expressions evaluated to support or refute them. Nice. Comparisons RSpec, JBehave, easyb, Instinct, JUnit < SCALATEST In a nutshellA generalised framework for Java and Scala which uses a variety of traits to mixin a number of different test styles and strategies. Out of the box, TDD, BDD, functional, integration TestNG and JUnit tests are supported.Link http://www.scalatest.org/ Version v1.7.2 Ohloh http://www.ohloh.net/p/scalatest Active community Yes. This is a second generation framework spawned from a project called SuiteRunner by Bill Venners in 2001. There are actively maintained forum groups accessible via: http://www.scalatest.org/community Example package org.scalabound.scatdd.scalatest import org.junit.runner.RunWith import org.scalatest.FunSpec import org.scalatest.junit.JUnitRunner import org.scalabound.scatdd.FizzBuzz @RunWith(classOf[JUnitRunner]) class FizzBuzzScalaTest extends FunSpec {      describe('A FizzBuzz processor') {          it('should return 'FizzBuzz' from a mulitple of three and five') { assert(FizzBuzz.eval(15) == 'FizzBuzz') }          it('should return 'Fizz' from a multiple of three only') { assert(FizzBuzz.eval(12) == 'Fizz') }          it('should return 'Buzz' from a multiple of five only') { assert(FizzBuzz.eval(10) == 'Buzz') }          it('should return the stringified input from a non multiple of three or five') { assert(FizzBuzz.eval(11) == '11') }        } }Feedback I only used one spec type and it seemed both clear and concise. The language dictated by this API ( describe.. it..) was straightforward it not slightly awkward at first site. I also prefer a clearer distinction between my tests and assertions, (which is a matter of taste). Still, it’d be hard to find a more straightforward and ‘friendly’ framework to get a Java team up and running with first time around. Comparisons JUnit, TestNG SCALACHECK In a nutshellA specification based test generation framework for Scala and Java. The library was originally inspired by QuickCheck in Haskell.Link https://github.com/rickynils/scalacheck#readme Version v2.9.0-1-1.9 Ohloh http://www.ohloh.net/p/scalacheck Active community Yes, but primarily stemming from Rickard Nilsson. There doesn’t appear to be any forum support for this project. Update: Thanks to @Daniel Sobral there is (in fact) a google group in support of ScalaCheck here !                Example package org.scalabound.scatdd.scalacheck import org.scalabound.scatdd.FizzBuzz import org.scalacheck.ConsoleReporter.testReport import org.scalacheck.Prop.forAll import org.scalacheck.Prop.propBoolean import org.scalacheck.ConsoleReporter import org.scalacheck.Test object FizzBuzzScalaCheck {      val propFizzBuzzCheck = forAll { n: Int =>{ if(n % 15 == 0) FizzBuzz.eval(n) == 'FizzBuzz' else if(n % 3 ==0) FizzBuzz.eval(n) == 'Fizz' else if(n % 5 ==0) FizzBuzz.eval(n) == 'Buzz' else '' + n == FizzBuzz.eval(n)    }   }       def main(args : Array[String] ) = {     ConsoleReporter.testStatsEx('blah', testReport(Test.check(propFizzBuzzCheck)))   }    }Feedback Compared to the other frameworks, this one took me a while to get running with, (bear in mind, I was running with the others in minutes though !). The main sources of my pain were:No obvious out of the box JUnit support I originally ran my tests as a Scala App (i.e. something that extended App), though kept getting GenException(java.lang.NullPointerException)from the ConsoleReporter whenever I tried to run my tests.Whenever I tried to add too many conditions to my implication operator, I found not enough tests were generated to validate my property, (hence the somewhat cludgy example I present).Having said all that, I still find this framework unique and really valuable. On a few test runs I logged the inputs generated and Scalacheck really is great, (a fair span of inputs generated and passed through). This was probably the most challenging framework of the three, but also offered the sort of features I’d certainly want to use again and again. Likely next time I’d run this via Specs though ! Comparisons Java QuickCheck, JUnit quickcheck Conclusion In conclusion all three frameworks are much clearer, (or expressive) than comparative frameworks that I have personally used in Java previously. If I was trying to get a team to ‘evovle’ to Scala, I’d choose ScalaTest. If I was working with a team who were slightly more comfortable with Scala I’d go the Specs2 route. In any event I’d try to use ScalaCheck for test generation, (ideally abstracted away through one of the other frameworks though). Either way I can see why using Scala test frameworks helps to sway opinion towards teams progressing towards Scala in the enterprise. I hope this feedback was useful and not too dry. As ever, the best ‘validation’ is in walking the path yourself (unless ScalaCheck will do it for you !). Good luck with your TDD and Happy hacking ! Reference: ScaTDD: Casting an eye over three major Test frameworks in Scala from our JCG partner Kingsley Davies at the Scalabound blog....
software-development-2-logo

Pragmatic Thinking: Novice vs Expert

Recently I started reading Andy Hunt’s fine book ” Pragmatic Thinking And Learning.” Hunt is notorious for writing books which offer practical, insightful advice in which developers can apply to their work on a daily basis. His most famous book is “The Pragmatic Programmer”, widely considered one of the top agile programmer books of all time. Even after reading the book 7 years ago, I still refer to it a few times a month. My colleagues and I bring up the “broken window” theory, or often throw out the phrase “Don’t Assume, Prove it,” sometimes to the chagrin of the unfamiliar. :) The Book Pragmatic Thinking and Learning is a different type of book, however. It explores the human mind and how it relates to learning and cognitive thought. To my surprise, it is very well researched and touches on psychology and neuroscience. Hunt brings the concepts home by relating them to the software industry and the toils and travails of an agile developer. Dreyfus Model: Journey from Novice to Expert One of the more interesting parts of the book is Hunt’s exploration of the Dreyfus Model. He defines the stages a person goes through on the journey from novice to expert, regardless of the field of study or activity. These are summarized below:Novice – individuals who have little or no evolved experience in a skill area. By evolved, I mean their mode of thinking has not changed over the years. They have have 10 years of experience, but it might be doing something the same way for 10 years (one year of experience, ten times). Novices can be effective with context free rules to follow. They need recipes. They don’t know why the rules exists or what to do if the rules don’t apply. Advanced Beginner – advanced beginners can apply the rules consistently and can recognize the problem context. They want information fast and do not contemplate the big picture. They focus only at the task at hand and are bound to repeatable problems and solutions. Competent – competent individuals can troubleshoot problems on their own and can solve problems they have not faced before. They have initiative and are resourceful. However, they still have issues focusing on the correct details and still lack a holistic picture of the problem. Proficient – the proficient skill worker needs the big picture. They seek it out and aim to solve the problem with a deeper understanding. They have the ability to not only solve problems, but improve poor situations for the better. Instead of rules to follow, they operate under maxims; heuristics and rules of thumbs that generally apply, but may not always fit. They have enough experience to identify context. They take full advantage of self-reflection and feedback to become more effective in the future. Expert – experts are primary sources of knowledge and information in a field. The expert knows the difference between irrelevant details and very important details. Their judgment is logical yet derived from intuition. They are the ones the write the books, articles, travel the circuit with presentations, and are often times the inventor or contributor of the software you use. Experts don’t follow rules, they follow intuition and evolved experience.Takeaways What is interesting about the Dreyfus model is not just the definition of these stages, but how they apply to the workplace. Especially applicable to the agile developer context, as an individual moves up the Dreyfus model from Novice into the Proficient realm, rules and regulations can actually stifle a developer’s productivity. Hunt actually specifies that ignorance of the Dreyfus model can rob excellent developer’s of the expertise and choke their performance. “But worse than that, by misunderstanding the Dreyfus model, we can rob them of their expertise. It’s actually easy to derail an expert and ruin their performance. All you have to do is force them to follow the rules.”  Hunt gives a great analogy of how teams may misapply the model. “Hearding Racehorses and Racing Sheep.” This basically means a team can be slowed down by applying rules to proficient level or above members, or a team can burn up by throwing less skilled members into an arena where they cannot handle the load. To me this concept is the heart of agile. Agile definitely has its structure and framework, i.e., a set of practices and patterns that have proven successful in the past: TDD, Continuous Integration, Iterative Releases, and Refactoring, just to name a few. But Agile methodologies are not prescriptive. It emphasizes continuous improvement. Agile frowns upon context-free rules. Another quote: Rules ruin experts. Obviously this is stark and cannot always apply. Any group has rules, every organization has standards. However the book gives a great overview of the skill model of developers and can give leaders good insight of how to best harness the talent of a team. Reference: Pragmatic Thinking: Novice vs Expert from our JCG partner Nirav Assar at the Assar Java Consulting blog....
eclipse-logo

Writing Eclipse Plugins Tutorial – Part 1

Eclipse is one of three most popular java development IDEs. One reason for its success is its extensibility. Writing eclipse plugins can be very fast and easy for anyone who knows what to do and already done it. Unfortunately, doing something in Eclipse for the first time can be very time consuming and frustrating. Eclipse framework is huge, powerful and sometimes complicated. It may be difficult to figure out which features are available and how to use them. This tutorial explains basics of all eclipse features needed to automate a simple java refactoring task. It shows how to add new items into the menu and how to analyze, modify and format java source code. It also shows how to use dialogs to communicate with users. It is split into two parts. This post explains all needed theory. By the end of this part, you will already know enough about Eclipse framework to be able to finish the plugin with just a little searching. Practically speaking, we will create a plugin that adds new items into the menu and collects all information needed to perform the refactoring. Next part of this tutorial will show how to create dialogs and how to modify java sources from the plugin. It was not released yet. Sample Plugin We create sample plugin with two features:check non-null parameters – modifies selected method to check whether its parameters are not null, custom generate toString – adds toString method to selected class.Both features will add a new item into the source menu. Check non-null parameters item will be enabled only if user selects a java method. The feature shows a dialog which allows user to choose a subset of method arguments. Selected method is then modified to check whether chosen arguments are null: if (arg1==null || arg2==null || ... || argn==null) throw new IllegalStateException("The parameter may not be null."); Custom generate toString item will be enabled only if user selects a java class. It will show a dialog with list of all its properties. The user selects which properties belongs to toString method. If user selected less than four properties, the feature adds following code to the class: @Override public String toString() { StringBuilder builder = new StringBuilder(this.getClass() .getSimpleName()); builder.append(" [ "); builder.append(b).append(", ").append(c).append(" ]"); return builder.toString(); } If user selected less four of more properties, the feature adds following code to the class: public String toString() { StringBuilder builder = new StringBuilder(this.getClass() .getSimpleName()); builder.append(" [ \n"); builder.append(" a" + ": ").append(a).append("\n"); builder.append(" b" + ": ").append(b).append("\n"); builder.append(" c" + ": ").append(c).append("\n"); builder.append(" d" + ": ").append(d).append("\n"); builder.append(" ]"); return builder.toString(); } That is all. The plugin is available on Github. IDE Each Eclipse release comes in multiple flavors. The version best suitable for plugin writers is called ‘Eclipse for RCP and RAP Developers’. The RCP stands for ‘rich client platform’ which is just another name for Eclipse platform. Download and install ‘Eclipse for RCP and RAP Developers’ from the download page. Target Platform First thing to do is to configure target platform. Target platform is another instance of eclipse. It represents the minimal configuration your plugin will work with. Your plugin will be compiled against the target platform. It will also be installed into it and will run inside it whenever you will want to test it. The whole workspace can have only one active target platform. It is not project specific, although it would make more sense. Easiest Target Platform The easiest is to develop for the same eclipse version as you are running on. This is the default option. If this is the case, all you have to do is to add eclipse SDK into it. Install Eclipse SDK:Go to ‘Help’ -> ‘Install New Software…’. Choose your eclipse update site, in our case the ‘The Eclipse Project Updates’ http://download.eclipse.org/eclipse/updates/3. update site. Check both Eclipse SDK and Eclipse Platform SDK. Click next, accept license and finish the installation.That is it. Nothing else is necessary, you are ready to create first plugin project. Advanced Target Platform It is possible to download and maintain the target platform separately. Use this option if you want to be compatible with an older release or if you want to have greater control over the target platform configuration. If you are not interested, skip to the next chapter. Create Target Platform Find and download SDK of whatever you assume your users will have. You may use also a ‘regular’ version if you can not find the SDK. However, if you download SDK, you will have source code and javadocs available. For example, our plugin requires Eclipse Indigo release. The version number of Eclipse Indigo is 3.7, therefore we have to download Eclipse 3.7 SDK. The complete list of even older Eclipse SDKs versions is available on archived releases page. Our plugin will depend only on the eclipse itself, so all we have to do is to unpack downloaded SDK somewhere. If it would require additional plugins, we would have to hunt and download their SDKs too. We would also unpack them and copy into the same directory as eclipse SDK. Configure Target Platform Now, we have to configure our RCP eclipse to use prepared target platform. Define and activate the target platform:Go to ‘Window’ -> ‘Preferences’ -> ‘Plug-in development’ -> ‘Target Platform’. Click Add. Choose ‘Nothing: Start with an empty target definition’ and click next. Fill in target name. Click Add, choose directory, browse to the unpacked eclipse SDK and finish. Check new target platform as ‘Active’.Finally, go to ‘Plug-in Development’ preference page and check ‘Include all plug-ins from target in Java search’. Simple Plugin Project This chapter shows how to create a simple plugin project and how to debug it. The simple plugin does nothing useful. It is only able to show a message to prove that it exist. In the end of this chapter, we will remove the sample message and end up with an empty plugin skeleton. Create Plugin Project We will use Eclipse wizard to generate the plugin. Invoke the wizard from the package explorer:right click in the package explorer, choose ‘New’ -> ‘Other..’., select ‘Plug-in Project’ and click Next.The wizard has multiple pages. Configure the project name and target platform on the first one. You can use any project name as you want, but the convention is to name the project after the root java package. For example, as we want to put all classes into the org.meri.eclipse.defensiveapitools package, our project name will be org.meri.eclipse.defensiveapitools The target platform field contains a version of Eclipse you are developing for. If someone wants to use your plugin, he will be required to download Eclipse with equal or bigger number. An old incompatible Eclipse will refuse to load it. We are fine with developing for current Eclipse, so we will choose 3.7.Click ‘Next’. Second page contains basic project information. Fill in the id, plugin version, name and provider however you like. The first important parameter is the execution environment. The plugin will run only on the specified or never java. An eclipse running on older JVM will simply ignore it. We have chosen J2SE-1.6. Verify that:check-box ‘Generate an activator, a Java …’ is checked, check-box ‘This plugin will make contributions to the UI’ is checked, the answer to ‘Would you like to create a rich client platform application’ is no.Click ‘Next’. Choose ‘Hello, World Command’ template and click ‘Finish’. This will create new plugin with sample menu item. Debug The Plugin The plugin works only inside a running Eclipse. Eclipse supports both manual and automatic JUnit testing. In both cases, the plugin is installed and run inside the target platform configured in the first chapter. This chapter shows only how to do the manual testing. Refer to other resources to learn how to write junit tests for eclipse plugins. Install and run the plugin:right click on the plugin project, click ‘Debug As’ -> ‘Eclipse Application’.The system will start new eclipse instance. Its main menu has a new entry called ‘Sample Menu’. Now, you have two running eclipse instances. One is for development and another is for testing. The testing eclipse runs inside the development one. All debugging tools are available. You can place breakpoints, inspect variables and so on:open generated SampleHandler class in the development eclipse, put breakpoint inside the execute method, go back to the test eclipse, choose ‘Sample Menu’ and ‘Sample Command’The execution will stop on the new breakpoint. Clean the Plugin We have seen that the plugin works, so we can remove generated sample menu from it. Remove sample menu item and its handler:Open plugin.xml file, go to extensions tab and remove all extensions. Locate and delete generated SampleHandler class.The plugin tag inside the plugin.xml should be empty now. Open plugin.xml file and go to the plugin.xml tab: <?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.4"?> <plugin> </plugin>Adapter Pattern Eclipse is a huge framework and there is an infinite amount of plugins you can install into it. This creates a huge system of features and plugins that have to cooperate with each other. To keep this system as decoupled and as extensible as possible, Eclipse framework uses adapter design pattern. This pattern is so common that you will probably run into it no matter what plugin you will write. This design pattern converts a class or interface into another class or interface. The class that performs the conversion is called an adapter. The pattern has two different flavors and eclipse framework supports both. The difference between those two flavors is in who creates the adapter. It can be done either directly by the object to be converted or by an independent adapter factory. First sub-chapter shows how to write an adapter. Second sub-chapter is about objects able to create their own adapters and third is about independent adapter factories. Last sub-chapter puts everything together and shows how to convert an object of unknown type. Adapter Adapter is an object that converts one type into another type. It must represent the other type e.g., if it converts objects to a class, then it must extend that class. If it converts them to an interface, then it must implement that interface. Typically, an adapter converts object that has all needed functionality, but does not have the right API. Otherwise said, typical adapter contains very little logic. It only wraps the original object and delegates all work to it. Following adapter is able to convert an implementation of Minus interface into the Plus interface: public class MinusToPlusAdapter implements Plus {private final Minus adaptee; public MinusToPlusAdapter(Minus minus) { super(); this.adaptee = minus; }@Override public int plus(int x, int y) { return adaptee.minus(x, -y); }}Adaptable Objects In a simpler version of this design pattern, the object to be converted creates its own adapters. We will show how to create adaptable objects compatible with eclipse framework. The rest of this sub-chapter lists advantages and disadvantages of this adapter pattern flavor. Eclipse Implementation An adaptable object must implement IAdaptable interface. The interface has only one method getAdapter(Class type). It returns either an adapter to the requested type or a null. An adaptable object: public class MinusImpl implements Minus, IAdaptable {public int minus(int x, int y) { return x - y; }public Object getAdapter(Class type) { if (Plus.class.equals(type)) return new MinusToPlusAdapter(this);return null; }} The getAdapter method may or may not call the global adapter manager to create an adapter. Some Eclipse objects call it, some do not. When To Use It Adaptable objects are easy to use and debug. The pattern helps to keep class and interface hierarchies clean. It also provides some decoupling between converted type and required type. Use it when:Converted type already implements too many interfaces. Converted type have to be compatible with two different features and each requires it to extend another class. You want to keep the converted type and required interface/class separated. The adapter needs access to private fields of methods.Limitations Plugin that relies only on this version of the pattern is not extensible. Third party plugins are not going to be able to add new adapters into it. Third Party Adapter Second version of this pattern uses an independent factory to create adapters. We will show how to call adapter factories within eclipse framework. The rest of this sub-chapter lists advantages and disadvantages of this adapter pattern flavor. Eclipse Implementation Adapters are created by adapter factories. To achieve their independence, adapter factories are hidden behind global adapter manager. Client code never communicates directly with an adapter factory. Adapter manager exposes a getAdapter(Object obj, Class type) method which delegates calls to installed adapter factories. This method returns either an adapter or a null. Use adapter manager to create an adapter: (Plus) Platform.getAdapterManager().getAdapter(minus, Plus.class);Adapter factories are registered into adapter manager either programmatically or in plugin.xml. As our plugin does not need to do this, we will omit that information. Read either eclipse corner article or Eclipse Adapters tutorial for further information. Note: the adapter factory is not allowed to call the getAdapter(Class type) method of converted object. It would cause an infinite loop, because the getAdapter method of an adaptable object may call adapter manager. When To Use It Adapter factories lead to high decoupling and extensibility. The decoupling of the original object and required type is absolute. There is no dependency between them. Instead, an independent adapter factory depends on both. Asking an adapter manager for adapter makes your feature extensible. Anyone can contribute adapters to integrate his objects with your plugin. Use it to:make your plugin extensible by third party plugin writers, integrate two plugins.Limitations The decoupling comes with a higher complexity. If something goes wrong, it may be difficult to find out where the faulty adapter came from. Similarly, finding out which adapters are available is more time consuming than in the ‘adaptable objects’ version of this pattern. If you expect others to extend your plugin, document which adapters are expected. Document also adapter factories you are adding into the system. Hunting down all that information in xml files can be very time consuming. Adapt an Object The most correct way of adapting an object to the desired interface makes no assumptions about the adapter pattern version used by the object. Follow three steps to adapt the object to the needed interface or class:If the object implements or extends the desired interface, use the object. If the object can adapt itself, use the adapter provided by the object. Use the global adapter manager to adapt the object.Adapt an object to a type, full implementation: public static Object getAdapter(Object obj, Class type) { // if the object implements or extends the desired interface, use it if (type.isInstance(obj)) return obj;// if the object is able to adapt itself, let it do it if (obj instanceof IAdaptable) { IAdaptable adaptable = (IAdaptable) obj; Object adapter = adaptable.getAdapter(type); if (adapter != null) return adapter; }// delegate to the global adapter manager return Platform.getAdapterManager().getAdapter(obj, type); }Abstract Syntax Tree vs Java Model Eclipse framework uses two different hierarchies to represent java source code. First is called java model and second is called abstract syntax tree. These hierarchies are mostly independent and have different purposes and usage. Java model hierarchy is lightweight, fault tolerant, fast to re-create and its abilities are limited. Abstract syntax tree provides full control over java source code, but is much slower to recreate. For these reasons, Eclipse framework uses java model hierarchy wherever possible. Abstract syntax tree is used only if necessary. First sub-chapter shows how to enable these hierarchies in the plugin. Second sub-chapter contains overview of java model and last contains overview of abstract syntax tree. Plugin Dependency Both hierarchies belong to the org.eclipse.jdt.core plugin. We have to add jdt core plugin to plugin dependencies if we want to use them:Open plugin.xml and go to the ‘Dependencies’ tab. Click Add button in the Required Plug-ins section. Select the org.eclipse.jdt.core plugin.Eclipse will automatically add plugin dependency into Require-Bundle section of MANIFEST.MF file. Java Model Java model is a set of interfaces that represent java methods, classes, interfaces and other elements. It is lightweight, fault tolerant and fast to re-create. Java model hierarchy provides basic information about java code structure. It is also able to make simple changes on it. For example, it is possible to use it to rename or add new methods, classes or interfaces. The main disadvantage of the java model hierarchy is that it does not contain full information about underlying source code. For example, it does not contain methods bodies. As a result, it is not possible to perform more complicated source code changes. The root of the java model hierarchy is IJavaElement interface. All interfaces that extend it belong to this hierarchy. Abstract Syntax Tree Abstract syntax tree is a set of classes that represent java methods, classes, interfaces and other elements. It provides full information about java code structure and is able to make any changes on it. The main disadvantage of the abstract syntax tree hierarchy is that it is slower to re-create than java model. It is also less fault tolerant. The root of the abstract syntax hierarchy is ASTNode class. All classes that extend it belong to this hierarchy. User Interface This chapter contains quick overview of eclipse user interface. We will explain only absolute basics of those parts of the UI that are going to be needed later in this post. First sub-chapter is about the most prominent part of Eclipse UI: views and editors. Second sub-chapter deals with the selection service. Parts, Views and Editors Two most important visual components of Eclipse user interface are views and editors. Both editors and views can show any content and present it in any form. Both can be editable or read-only, but only editor is able to keep the content in an unsaved dirty state. Common Properties Both editors and views are called parts. Eclipse documentation uses the word part as a shortcut for ‘an editor or a view’. Each part must have unique id. Technically, the id is an arbitrary string. However, the convention followed by all official plugins is to prefix the id with the plugin name. As the plugin name is usually equal to plugin root package name, the convention guarantees id uniqueness. Each part must implement IWorkbenchPart interface. The interface was extended twice, leading to IWorkbenchPart2 and IWorkbenchPart3 interfaces. You may either implement them directly, or extend the default implementation called WorkbenchPart. All parts are adaptable. The interface IWorkbenchPart extends the IAdaptable interface. The default implementation delegates the getAdapter method to the global adapter manager. Editors An editor is typically used to edit or browse a document or input object. Changes made in editor are not stored immediately. An editor with changed content is in dirty state until the save operation is invoked. If the editor is closed without saving, all unsaved changes are lost. Its default implementation is called EditorPart. All editors appear in the same region of the page and can not be minimized. There can be several instances of the same type of editor. Editors toolbar is shown together with the global toolbar and their menu appears to be a part of the main menu. A document or input object edited by the editor is identified using an instance of IEditorInput interface. Views A view is typically used to navigate a hierarchy of information, open an editor, or display additional information for the thing opened in an active editor. Modifications made in a view are saved immediately. Its default implementation is called ViewPart. Views can be moved to any part of the page and can be minimized. There is generally only one instance of a given view per workbench page. Each view has its own local toolbar and menu. They are also allowed to contribute buttons to the global toolbar and menu items to the main menu. Selection Eclipse selection system is fairly standard. Each view and editor generates its own selection. The framework has also a global selection. It usually contains selection of the active part. If the plugin needs to know selected objects no matter where they come from, it has to use the global selection. If the plugin wants to integrate itself only with few views and editors, it may listen to their selections only. This chapter shows how to interpret the selection once you get it. How to get the current selection is described in an Eclipse corner article. Selected Objects Current selection always implements the ISelection interface. That interface is extremely minimalistic. Its only method is able to tell whether the selection is empty of not. To get more detailed information, you have to cast it to one of its subtypes. Two sub-types are interesting for our plugin:ITextSelection – information about selected text. If no text is selected, contains the cursor position. IStructuredSelection – contains a list of selected objects.Structured selection can contain any types of objects. The best way to convert them to required classes or interfaces is to use the adapter pattern. Simple instanceof and cast may not be enough. Objects flying in eclipse are often adaptable to many types, but they implement or extend only some of them. Eclipse Menus Eclipse menu system is surprisingly rich and complicated. There are at least five menu types. The same or similarly looking menu can be invoked in multiple ways. To make it even more interesting, Eclipse has two different frameworks able to contribute new items into all those menus. Each eclipse menu framework has its own chapter and those two chapters follow this one. This chapter contains only an overview of various menu types, an overview of the menu where our plugin adds its items and overview of those two menu frameworks. Menus Types Eclipse has five menu types:Context menu – menu invoked by a mouse right click. Sometimes called also popup menu. Main menu – menu always visible on the top of GUI. Main toolbar – always visible toolbar available under the main menu. View menu – menu available in a view. Click on a white down arrow in a view to invoke it. View toolbar – a little toolbar available in most views.Unlike views, editors do not have their own menu or toolbar. They always contribute to the main menu or to the main toolbar. Source Menu Source menu contains items like ‘Organize Imports’ or ‘Generate Delegate methods…’ and is a logical place for our two features. It was contributed by java development tools plugin (JDT). This menu is located either in the main menu or in the context menu. Both locations show it only under some circumstances. Main menu contains source menu item only if the active view or editor supports it. Following list contains examples of views and editors that causes the source menu to appear. Activate any of them to see it in main menu:Java Editor, Type Hierarchy View, Package Explorer View, Project Explorer View.Context menu contains source menu item if at least one selected item represents java file, class, package method or other java item. Of course, that includes text selection inside java source editor. Activate context menu with source sub-menu:open java source file in an editor and right click inside, select java file or class in package explorer and right click.The source menu can be invoked also with shortcut ‘Alt+Shift+S’. Menu Frameworks Eclipse has two different frameworks able to contribute new items into menus:the actions framework, the command framework.The actions framework is older and deprecated. The command framework is newer, flexible and little bit more complicated. It is superior and should be used for any new functionality. The command framework is compatible with most, but not all menus. Some menus have not been rewritten yet, so you have to use the actions framework to contribute to them. For example, the source sub-menu in the main menu is compatible only with the actions framework. Some menus are incompatible with both frameworks. The source menu invoked by the shortcut CTRLS + ALT + S is such menu. It is impossible to contribute to it. Note: Impossible to contribute to menus are rare. The Command Framework The command framework is able to add items into most eclipse menus. It was designed as mini model view controller and separates UI from actions to be performed. This chapter contains command framework basics. We will explain command framework components and use them to add new items into the source menu. Then, we will show how to make menu items enabled and disabled. New menu items are going to be enabled only if they would be useful on the current selection. Overview New addition to the menu is called a menu contribution. Each menu contribution needs to know where to draw new items, which items to draw and what should happen when someone clicks them. Most Eclipse menus have unique id assigned. If you want to contribute to the menu, you have to find that id, compose so-called location URI from it and assign it to the menu contribution. Among other things, each menu contribution can add separators and commands into the menu. Separators are those grey lines between different menu parts. Commands placed inside a menu represent clickable menu items. Each has a label, may have an icon and can be either enabled or disabled. However, the command is not able to perform an action. It is only an abstract thing meant to separate GUI from the real action. Real work is done inside command handlers. Menu Id Menu id is an arbitrary string assigned to the menu or sub-menu. Each menu may have multiple ids. Finding menu id of an Eclipse menu can get very frustrating and difficult. If you are lucky, the id will be revealed with the Plugin Spy available in Eclipse RCP. It is able to show information about menu items, UI elements and running Eclipse plugins. If you are unlucky, you will have to find the id on your own. Top Level Things are easy if you wish to add an item to the menu or toolbar top level. List of general application menus:The main Eclipse menu uses org.eclipse.ui.main.menu. The id refers only to the menu top level, e.g. the item will be placed together with ‘File’, ‘Edit’ and ‘Help’. The Eclipse toolbar uses org.eclipse.ui.main.toolbar. The context menu uses org.eclipse.ui.popup.any id.If you wish to contribute to menu or toolbar inside some view, use the view id. Luckily, the Plugin Spy can help to find the view id. Open the view in an RCP Eclipse and press ‘Alt + Shift + F1′. Plugin Spy will open a popup with view information:Sub-menu With Plugin Spy Finding an id of a sub-menu can be more complicated because the Plugin Spy may not be able to find it. Use ‘Alt + Shift + F2′ shortcut to start the Plugin Spy and open menu you want to contribute to. Click on any menu item and Plugin Spy will show various information about it. Use Plugin Spy to get the source menu location URI:open any java file in the development eclipse, press ‘Alt + Shift + F2′, right click inside the java file hover over the ‘Source’ menu item, click on the ‘Clean Up…’ item.Eclipse will show following pop-up:If the popup contains location URI, then we are almost there. Copy and paste it somewhere. Warning: Plugin Spy popup adds new line before and after copied text, so it may look like nothing was copied. The part between : and ? is the menu id. For example, if the plugin spy shows menu:org.eclipse.jdt.ui.source.menu?after=CleanUp, the menu id is org.eclipse.jdt.ui.source.menuThe Other Way If the Plugin Spy does not show the location URI, it means that menu item or the menu itself was not rewritten into command framework yet. This is how Plugin Spy popup of an old menu item looks like:Your best bet is to google around and look into plugin.xml of plugins that contribute to that menu. Chances are, that someone had the same problem and managed to solve it. You can start with an old but still good list of context menus available on jdg2e. If the menu existed already in Eclipse 3.0, it is listed there along with its menu id. The source menu is not available in that table. However, the id of its parent menu, e.g. the menu available if you right click in any java file, is #CompilationUnitEditorContext. This would be an acceptable second prize. Plan B While the contribution to top level menus with the command framework is easy, unknown menu ids make contributions to various sub-menus difficult or even impossible. If you have no luck finding it, you have to use the old actions framework. Location URI Location URI string has three parts: scheme, menu id and placement modifier: <scheme>:<menu-id>[?<placement-modifier>]Eclipse has three schemes:menu – either main application menu or a view menu, toolbar – either main application toolbar or a view toolbar, popup – a context menu, e.g. any menu invoked by a right click.The placement modifier is optional. It has the form <placement>=<id>. The placement part is either after or before. The id is either separator name, menu ID, or item ID. Be careful, if the menu does not contain specified id, it will ignore your contribution. By convention, each menu should declare a special item with id ‘additions’. This is where menu authors through that you should place your items. You do not have to respect their wish and some menus do not have such item. You can place your items wherever you like, even if the special additions item is in the menu. Few examples:menu:org.eclipse.ui.main.menu?after=file – add item to the main menu, between File and Edit sub-menus. toolbar:org.eclipse.ui.main.toolbar – add item to the main toolbar. menu:org.eclipse.ui.navigator.ProjectExplorer – add item to the menu available in the project explorer view. toolbar:org.eclipse.ui.navigator.ProjectExplorer – add item to the toolbar available in the project explorer view. popup:org.eclipse.ui.popup.any – add item to the context menu.Place the item into the source menu without being picky about the exact location: popup:org.eclipse.jdt.ui.source.menuNote: We omitted the optional exact location in our location URI, because it can be tricky. If you wish to specify also the exact location, you have to be sure that selected place exists every time the menu is invoked. Unfortunately, just because the menu item looks the same, it does not mean that it really is the same menu item. For example, if we would add ?after=CleanUp in the end of the previous location, our menu item would be placed right after the ‘Clean Up…’ item in the sources sub-menu invoked by right click in java editor. However, it would be invisible in the source sub-menu invoked by right click in package explorer view. Command A command is an abstract thing that represents an action and has an unique id. It can be placed into the menu and you can assign a shortcut to it. Commands are configured in plugin.xml file. Open it and go to extensions tab. Use the left part named ‘All Extensions’:Click ‘Add’ and choose org.eclipse.ui.commands extension point. Right click on the new extension point and choose ‘New’ -> ‘command’. Fill in the id. The convention is to use plugin name as prefix of the command id. Fill in the name.We created two commands. One named ‘Generate Custom toString’ and another is named ‘Check Non-Null Parameter’. Their ids are:org.meri.eclipse.defensiveapitools.generatetostring org.meri.eclipse.defensiveapitools.checknonnullparameterEclipse automatically generates corresponding xml and places it to the plugin.xml file. Go to the plugin.xml tab to see it: <extension point="org.eclipse.ui.commands"> <command id="org.meri.eclipse.defensiveapitools.generatetostring" name="Generate Custom toString"> </command> <command id="org.meri.eclipse.defensiveapitools.checknonnullparameter" name="Check Non-Null Parameter"> </command> </extension> Menu Contribution Menu contribution is an addition to menu. It knows where to draw itself and contains list of items that should be drawn. All items placed into the menu contribution are shown together, in the order defined by their position in that list. We will configure a new menu contribution and add two menu items and two separators in it. Adding other element types into it is analogical. Menu Contribution Menu items are configured in plugin.xml file. Open it and go to extensions tab. Use the left part named ‘All Extensions’:Click ‘Add’ and choose org.eclipse.ui.menus extension point. Right click on the new extension point and choose ‘New’ -> ‘menuContribution’. Fill in the locationURI. Set allPopups to true.Recall, that the source context menu location uri is:popup:org.eclipse.jdt.ui.source.menuCommand Add commands to the menu contribution:Right click on the menu contribution and choose ‘New’ -> ‘command’. Click Browse and find previously created command. Fill in label.Eclipse automatically generates corresponding xml and places it to the plugin.xml file. Go to the plugin.xml tab to see it: <extension point="org.eclipse.ui.menus"> <menuContribution allPopups="true" locationURI="popup:org.eclipse.jdt.ui.source.menu"> <command commandId="org.meri.eclipse.defensiveapitools.generatetostring" label="Generate Custom toString" style="push"> </command> <command commandId="org.meri.eclipse.defensiveapitools.checknonnullparameter" label="Check Non-Null Parameter" style="push"> </command> </menuContribution> </extension> Test the menu. Run or debug the plugin and open any java file in the test Eclipse. Right click and choose the Source sub-menu. The menu contains two new items. As our commands have no handlers assigned, both items are disabled. Separator Add separator to the menu contribution:Right click on the menu contribution and choose ‘New’ -> ‘separator’. Set visible to true. Fill in name.The order of elements in the menu contribution defines the order of corresponding items in the menu. Drag and drop new separator to the place where you would like to see it. Eclipse automatically generates corresponding xml and places it to the plugin.xml file. Go to the plugin.xml tab to see it: <menuContribution allPopups="true" locationURI="popup:org.eclipse.jdt.ui.source.menu"> <separator name="org.meri.eclipse.defensiveapitools.begin" visible="true"> </separator> ... commands ... <separator name="org.meri.eclipse.defensiveapitools.end" visible="true"> </separator> </menuContribution> Test the menu again. Run or debug the plugin and open any java file in the test Eclipse. Right click and choose the Source sub-menu. Our menu items are surrounded by menu separators. Command Handler The command handler is the class that executes an action whenever users clicks on the menu item. Once we assign it to the command, the menu item created in previous chapter will be enabled. This section is divided into three part. First two sections show how to create and configure a dummy handler. Third section explains where the handler can get the information about currently selected items, active editor and other UI state. Simplest Command Handler A command handler must implement the IHandler2 interface. The easiest way to implement it is to extend the abstract AbstractHandler class. This class provides standard implementation of all necessary methods except the execute method. The execute method is called whenever user invoked the command. It has one parameter which contains information about the current state of the application. The execute method must return null. Our first command handler is very simple: public class GenerateToStringHandler extends AbstractHandler {@Override public Object execute(ExecutionEvent event) throws ExecutionException { System.out.println("GenerateToStringHandler"); // must return null return null; }}Basic Configuration The only thing we have to configure is which commands should be handled by our handler. Note: It is also possible to assign multiple handlers to one command, but we will not do it. It is an advanced topic discussed in additional resources. As usually, command handlers are configured in plugin.xml file. Open it and go to extensions tab. Use the left part named ‘All Extensions’:Click ‘Add’ and choose org.eclipse.ui.handlers extension point. Right click on the new extension point and choose ‘New’ -> ‘handler’. Browse for the command id. Browse for the class implementing the command handler.Eclipse automatically generates corresponding xml and places it to the plugin.xml file. Go to the plugin.xml tab to see it: <extension point="org.eclipse.ui.handlers"> <handler class="org.meri.eclipse.defensiveapitools.generatetostring.GenerateToStringHandler" commandId="org.meri.eclipse.defensiveapitools.generatetostring"> </handler> <handler class="org.meri.eclipse.defensiveapitools.checknonnullparameter.CheckNonNullParameterHandler" commandId="org.meri.eclipse.defensiveapitools.checknonnullparameter"> </handler> </extension> Run or debug the plugin and open any java file in the test Eclipse. Right click and choose the Source sub-menu. The ‘Generate Custom toString’ menu item is enabled. If you click on it, the command handler will print ‘GenerateToStringHandler’ into console in RCP Eclipse. Implementation As we are going to invoke our feature from two different places, our command handler will delegate all real functionality to yet another class. That another class will need some information about the context surrounding the command. Namely, ‘Generate Custom toString’ needs to know which class was selected and ‘Check Non-Null Parameters’ needs to know which method was selected. Note: Eclipse generates mini-selection every time you place the cursor somewhere. You do not have to highlight the text inside editor. The execute method obtains an instance of ExecutionEvent as a parameter. The execution event has reference to application context which contains various information about the state of the eclipse. Use the HandlerUtil to get that information out of the execution event. Handler util is a static class and has a lot of getWHATEVER methods. We will need four of them:getCurrentSelection – returns current selection, getActivePartId – returns id of active view or editor, getActiveEditorInput – returns object edited by the opened editor, getActiveShell – returned object will be needed for our plugin dialog.private static final String JAVA_EDITOR_ID = "org.eclipse.jdt.ui.CompilationUnitEditor";public Object execute(ExecutionEvent event) throws ExecutionException { //this object is needed to render wizards, messages and so on Shell activeShell = HandlerUtil.getActiveShell(event); //get selected items or text ISelection currentSelection = HandlerUtil.getCurrentSelection(event);//identify active GUI part String activePartId = HandlerUtil.getActivePartId(event); if (JAVA_EDITOR_ID.equals(activePartId)) { //get edited file IEditorInput input = HandlerUtil.getActiveEditorInput(event); //currentSelection contains text selection inside input file //... locate class selected in that file ... } else { //currentSelection contains all selected classes //... collect all selected classes ... }return null; } Enabling, Disabling and Visibility The menu item does not have to be visible and enabled all the time. Most commands are not universally usable. Both our features are going to be visible all the time. However, we will have them enabled only under some conditions. ‘Check Non-Null Parameters’ will be enabled:inside java editor, if the current selection contains only modifiable java methods.‘Generate Custom toString’ will be enabled:inside java editor, if the current selection contains only modifiable java classes or source files.First, shortest section shows where to configure visibility and enablement. Next one describes xml language used to define visibility and enable conditions. Third section uses that language to test active editor and fourth tests selected objects. Final two sections put everything together and show conditions needed for our plugin. Visible vs Hidden If you want to make the menu item invisible, use the visibleWhen tag on a command reference inside a menu contribution. If you want to make the item disabled, use the enabledWhen tag on the command handler. Both tags works exactly the same way. Open plugin.xml in an editor and go to the extensions tab. Right click either on the reference inside a menu contribution or command handler and choose either visibleWhen or enabledWhen. Expression Language If you right click on visibleWhen or enabledWhen tag, Eclipse will show a list of possible sub-tags. All those tags are part of xml boolean expression language and we will use them to define a condition. If the condition is satisfied, the menu item will be visible or enabled. If the condition is not satisfied, the menu item is either disabled or invisible. One warning: not each tag shown on the list is directly usable. In this case, Eclipse simply shows all tags that defines a condition. Usage of all listed tags is described on Eclipse help page. We will explain only five tags needed for our conditions:or – logical or, with – specify the object under condition, iterate – iterator over a collection, equals – compares object under condition with a value, adapt – adapts object under condition to the specified one.Or The element or does logical or. Its child tags must represent conditions. If at least one of them returns true, the result is true. With The element with specifies the object under condition. This tag can access various variables that describe Eclipse state. Each variable has a name. All childs of the with tag will test their condition against the value of the specified variable. This tag has one mandatory property variable. Use it to specify the variable name. We will use two variables:activeMenuSelection – collection of all objects selected by the user, activePartId – the id of currently active GUI part (view, editor, preference page …).As any plugin can add its own variable, the complete list of all variables is impossible to find. The list of default variables is available on Eclipse wiki page. Iterate The element iterate is usable only inside the with tag and only if this tag specified a collection as the object under the test. Its child tags must represent conditions. Iterate iterates through all objects inside the collection and runs all child conditions on those objects. The iterate tag has two arguments: operator and ifempty. The first argument value can be either and or or. Selected operator will be applied to evaluated conditions results. If no operator is specified, the iterator uses and. The ifempty can be either true or false. This value will be returned if the collection under test is empty. If not specified then true is returned when the operator equals and and false is return if the operator equals or. Equals The element equals compares the object under test with its value argument. As the object under test may not be a string, the value argument is converted into the object. The exact conversion algorithm is described in Eclipse manual. Adapt The element adapt adapts the object under test to the interface or class specified in its type argument. It may have child tags that may process it further, but we will use it solely to check whether the object under test is adaptable to the desired interface. Test Current Editor If the menu was invoked from java editor, then id of the active part is the same as id of java editor. Therefore, we have to get java editor id and compare it to the value of activePartId expression variable. To get the id, open any java file in RCP eclipse and press ALT + SHIFT + F1. Plugin Spy will show popup with various information about active GUI part. According to this popup, the java editor id is org.eclipse.jdt.ui.CompilationUnitEditor. Combine the with and equals tags to compare the id: <with variable="activePartId"> <equals value="org.eclipse.jdt.ui.CompilationUnitEditor" /> </with>Test Selected Objects Current selection can contain multiple items and all of them should represent something we can work with. The adapter pattern and java model hierarchy have been designed exactly for these kind of situation. Three interfaces from java model hierarchy are relevant to our features:org.eclipse.jdt.core.IMethod – represents java methods, org.eclipse.jdt.core.IType – represents java classes and interfaces, org.eclipse.jdt.core.ICompilationUnit – represents java source file.Therefore, we will iterate over the activeMenuSelection variable and check whether each selected object is adaptable to one of needed types. If no item is selected, the condition should return false. A method is selected if it is possible to adapt all selected objects into the IMethod interface: <with variable="activeMenuSelection"> <iterate ifEmpty="false" operator="and"> <adapt type="org.eclipse.jdt.core.IMethod" /> </iterate> </with> A java source file or a class is selected if it is possible to adapt all selected objects into either ICompilationUnit or ITypeinterface: <with variable="activeMenuSelection"> <iterate ifEmpty="false" operator="and"> <or> <adapt type="org.eclipse.jdt.core.IType" /> <adapt type="org.eclipse.jdt.core.ICompilationUnit" /> </or> </iterate> </with> Note 1: Unfortunately, the xml expression language is not expressive enough to distinguish between classes and interfaces. An instance of IType interface represents class if its isClass method returns true, but xml language does not support method calls. Note 2: We are cheating little bit here. It is not possible to modify compiled java methods and classes inside jar packages, but they are adaptable to java model interfaces too. Those objects are modifiable only if the method getCompilationUnit does not return null. As with the previous note, this is not possible to check from the xml expression language. Fortunately, we are contributing to the source sub-menu which is available only on modifiable java elements, so we do not have to solve this problem. Note 3: In both cases, the correct solution would be to create own with variable and handle both problems in java. This is possible and easy, but out of scope of this article. If you wish to know how to do it, read the post on Lars Vogel blog. Check Non-Null Parameters Enablement To reiterate, the menu item ‘Check Non-Null Parameters’ will be enabled:inside java editor, if the current selection contains only modifiable java methods.Use or to combine conditions created in previous chapters. This is the final condition: <enabledWhen> <or> <with variable="activePartId"> <equals value="org.eclipse.jdt.ui.CompilationUnitEditor" /> </with> <with variable="activeMenuSelection"> <iterate ifEmpty="false" operator="and"> <adapt type="org.eclipse.jdt.core.IMethod" /> </iterate> </with> </or> </enabledWhen>Generate Custom toString Enablement Recall, that the menu item ‘Generate Custom toString’ will be enabled:inside java editor, whenever java class is selected, whenever java file is selected.Use or to combine conditions created in previous chapters. This is the final condition: <enabledWhen> <or> <with variable="activePartId"> <equals value="org.eclipse.jdt.ui.CompilationUnitEditor" /> </with> <with variable="activeMenuSelection"> <iterate ifEmpty="false" operator="and"> <or> <adapt type="org.eclipse.jdt.core.IType" /> <adapt type="org.eclipse.jdt.core.ICompilationUnit" /> </or> </iterate> </with> </or> </enabledWhen>Expression Language – Additional Resources The complete explanation on how those conditions work is out of scope of this post. If you wish to read more, the basic and short article is on eclipse-tips blog and a detailed one is on Lars Vogel blog. The detailed post explains also how to reuse conditions and how to create new with variable. It is definitely worth reading, especially if you plan to do something complicated. Command Framework – Additional Resources We simplified things a little in this chapter. The full functionality and possibilities of the command framework are out of scope of this article. If you wish to know more, good tutorials are available on Lars Vogel blog or in IBM library. The Actions Framework Theoretically speaking, the actions framework is old and has been deprecated. The newer commands framework should be used for most purposes. Unfortunately, not all menus have been rewritten yet. If the menu you are interested in has not been rewritten yet, you have to use the old actions framework to contribute to it. As most menus are already compatible with the new command framework, we will show only the part of actions framework that is able to contribute to the source sub-menu in main menu. If you wish to read more about the actions framework, the last sub-chapter links to more detailed articles. Overview Two most important elements in the actions framework are action and action delegate. An action is assigned to menu items and knows the menu where it should be drawn. Action delegate is a class that does all the work whenever a menu item is invoked. Each action delegate can be assigned to any number of actions. However, each action can have only one action delegate. Items and menus definitions are kept either inside an action set or inside something called a contribution. There is not much difference between them, both action set and contribution contain list of actions and sub-menus to be drawn within menu system. Eclipse framework has three types of actions contributions and each is able to specify a simple condition that must be satisfied to have a visible action:viewerContribution – an action is available only inside specified view, objectContribution – an action is available only if specified object type has been selected, editorContribution – an action is available only inside editor menu or toolbar.Note: it is also possible to assign a condition to an action. Action conditions are powerful, but out of scope of this article. Both contribution and action set are placed directly inside an extension point. Each menu type has its own extension point:org.eclipse.ui.actionSets – main menu or main toolbar, org.eclipse.ui.popupMenus – context menu, org.eclipse.ui.viewActions – local menu or toolbar in a view, org.eclipse.ui.editorActions – local menu or toolbar in an editor (recall that the editors menu is shown inside the main menu/toolbar), org.eclipse.ui.perspectiveExtensions – we will ignore that.So, we have to create action delegate class, identify the menu we want to contribute to and configure an action inside a action set. Implementing Action Delegate Action delegate implementation depends on where you want to place the associated action. Menus supply the action delegate with additional information that depends on the menu type. Therefore, each menu type requires it to implement different interface. Common Each action delegate must implement IActionDelegate interface. That interface was later extended with some lifecycle methods, so if you need to initialize your action delegate or know when it is disposed, implement also IActionDelegate2 interface. Which method is invoked when a menu item is clicked depends on implemented interfaces. An action delegate that does NOT implement IActionDelegate2 interface must place all the work inside the run method. However, an action delegate that implements the IActionDelegate2 interface must place all the work inside the runWithEvent. In this case, the run method is never called. Menu Types and Sub-Interfaces Which sub-interfaces of IActionDelegate interface you should use depends on where do you want to place the action. Some parent menus send additional information about active parts and the action delegate must be able to acquire it. List of eclipse menus and expected action delegate interfaces:main menu or toolbar – IWorkbenchWindowActionDelegate, view menu or toolbar – IViewActionDelegate, view context menu – IViewActionDelegate or IObjectActionDelegate, editor menu or toolbar – IEditorActionDelegate, editor context menu – IObjectActionDelegate.Selection Parent menu uses the method selectionChanged to inform the action delegate about current selection changes. However, selection changes are sent to the action delegate only after it was invoked for the first time. All prior selection changes are ignored. The selectionChanged method is called for the first time right before the first call of run or runWithEvent method. Implementation We are ready to implement our action delegates. As it was with the command handler in command framework, our action delegate will only collect information about current editor and selected objects or text. The real work is delegated to yet another class. As we want to put our action to the main menu, we have to implement the IWorkbenchWindowActionDelegate interface. Main menu sends changes of current selection it to its action delegates, so all we have to do is to store it: private ISelection selection;public void selectionChanged(IAction action, ISelection selection) { this.selection = selection; } Getting current editor is little bit more complicated. Main menu does not inform its items about active UI parts. However, it sends them an instance of IWorkbenchWindow upon initialization. Fortunately, the workbench window object is aware of almost everything that is going on in the eclipse. The explanation of the workbench window object would take too much space and it is not that important. The important is, that it provides access to all kind of information about eclipse user interface. Use workbench window to get active editor and its id: private IWorkbenchWindow window;public void init(IWorkbenchWindow window) { this.window = window; }private String getActivePartId() { return window.getPartService().getActivePartReference().getId(); }private IEditorPart getActiveEditor() { return window.getActivePage().getActiveEditor(); } Finally, we are ready to implement the run method: public class GenerateToStringActionDelegate implements IWorkbenchWindowActionDelegate {private static final String JAVA_EDITOR_ID = "org.eclipse.jdt.ui.CompilationUnitEditor";public void run(IAction action) { //this object is needed to render wizards, messages and so on Shell activeShell = window.getShell(); //get selected items or text ISelection currentSelection = selection; //identify active GUI part String activePartId = getActivePartId(); //java editor must be handled differently than view selection if (JAVA_EDITOR_ID.equals(activePartId)) { //get edited file IEditorInput input = getActiveEditor().getEditorInput(); //currentSelection now contains text selection inside input file //... locate class selected in that file ... } else { //currentSelection now contains all classes inside //... collect all selected classes ... }System.out.println("GenerateToStringActionDelegate"); }}MenubarPath and ToolbarPath Before you configure the action, you have to find the menu or toolbar path. It identifies a menu or toolbar where your action will be shown. Each menu or sub-menu has its name and menu or toolbar path navigates those names. It starts with the top level menu name and continues with all sub-menu names. The final part is optional and specifies a location in the final menu. If it is missing, the item is placed to the end of the specified menu. For example, the menu path #menuName/subMenuName/additions should be read as “place the item in the end of the additions group which is located inside the sub-menu subMenuName of the #menuName menu”. Or, the menu path #menuName/subMenuName/ should be read as “place the item in the end of the sub-menu subMenuName of the #menuName menu”. Important: Menu ids are the same as described in the command framework chapter. The id of the source menu id is org.eclipse.jdt.ui.source.menu. As the main source menu is a top level menu, menubarPath is: org.eclipse.jdt.ui.source.menu/Configuring an Action Action configuration is quite simple. Add an extension point, put either action set or contribution into it and place the action. Which one of five extension points should be used depends on the menu. We want to add an action to the main menu, so we have to use the action sets extension point. Open plugin.xml file and go to extensions tab. Use the left part named ‘All Extensions’. First, configure an action set:Click ‘Add’ and choose org.eclipse.ui.actionSets extension point. Right click on the new extension point and choose ‘New’ -> ‘actionSet’. Fill in the action set id. The convention is to use plugin name as its prefix. Important: This field has some strange limitations. We could not really figure them out, so all we can say is that:org.meri.eclipse.defensiveapitools.mainmenucontrib works org.meri.eclipse.defensiveapitools.sourcemenu works, org.meri.eclipse.defensiveapitools.mainsource does not work, org.meri.eclipse.defensiveapitools.actionset does not work.In any case, if nothing shows up in the menu, try to change this id. Fill in label. It can be anything. Set visible to true.Second, add actions to the action set:Right click on the action set and choose ‘New’ -> ‘action’. Fill in the action id. The convention is to use plugin name as id prefix. Fill in label. It can be anything. Fill in either menubarPath or toolbarPath. Scroll down and browse for the action delegate in class field.Eclipse automatically generates corresponding xml and places it to the plugin.xml file. Go to the plugin.xml tab to see it: <extension point="org.eclipse.ui.actionSets"> <actionSet id="org.meri.eclipse.defensiveapitools.sourcemenu" label="Defensive API Tools " visible="true"> <action class="org.meri.eclipse.defensiveapitools.generatetostring. GenerateToStringActionDelegate" id="org.meri.eclipse.defensiveapitools.generatecustomtostring" label="Generate Custom toString" menubarPath="org.eclipse.jdt.ui.source.menu/" style="push"> </action> <action class="org.meri.eclipse.defensiveapitools.checknonnullparameter. CheckNonNullParameterActionDelegate" id="org.meri.eclipse.defensiveapitools.checknonnullparameters" label="Check Non-Null Parameters" menubarPath="org.eclipse.jdt.ui.source.menu/" style="push"> </action> </actionSet> </extension> Run or debug the plugin and open any java file in the test Eclipse. Click on the Source main menu item. The menu contains two new items. Click on the Generate Custom toString’ menu item, the action delegate will print ‘GenerateToStringActionDelegate’ into console in RCP Eclipse. Additional Resources Walkthrough of all types of actions contributions is available in an eclipse corner article. Easy to read FAQ article explains actions in the main menu. Actions framework supports also complicated conditions and filters to show actions only under some circumstances. If you have a reason to use that, the best starting point is in eclipse documentation. Useful Resources Everything directly related to chapters in this post was already linked. We will add only a link on a very good series with various eclipse development tips. If you have a problem and can not find an answer, you can also ask questions on official freenode #eclipse IRC channel. To Be Continued Although we added only some new items into the menu so far, almost everything needed to finish the plugin is already there. If you do not insist on having the generated code formatted, you should be able to finish the generate toString feature just by browsing through java model hierarchy API. Next part of this tutorial will show how to finish both features, including the formatting of the generated code. It will also explain how to create and work with abstract syntax tree and how to create a dialog to communicate with user. Reference: Writing Eclipse Plugins Tutorial – Part 1 from our JCG partner Maria Jurcovicova at the This is Stuff blog....
eclipse-logo

Top 10 Most Popular New Eclipse Plugins

Eclipse Marketplace continues to be the place to discover interesting and relevant Eclipse plugins. There are over 100,000 successful installs/month of Eclipse-based products via the Eclipse Marketplace client. We have a list of the most popular plugins over the last 30 days and all time. I thought it would be interesting to look at what are the most popular new plugins in the last 12 months. Below is the list of the top 10 most popular new Eclipse plugins that did not existing on Marketplace in April 2011 but are now very popular in April 2012. 1. Maven Integration for Eclipse WTP - Maven integration with WTP. Also #4 on the most popular chart 2. JSDT jQuery - jQuery autocompletion support for Eclipse JSDT 3. Groovy-Eclipse - Groovy IDE 4. ZK Studio - Eclipse plugin for ZK framework 5. Run-Jetty-Run - Running a web application in Eclipse should be as simple as ‘clicking run’. 6. ObjectAid UML Explorer - UML class and sequence diagram editor 7. P4Eclipse - Eclipse plugin for Perforce code management 8. Bracketeer for C/C++ (CDT) - Extends CDT to show more context around C/C++ brackets 9. Vrapper - Imitate vim within Eclipse editors 10. Bytecode Visualizer - Inspect, understand and debug Java bytecode Reference: Top 10 Most Popular New Eclipse Plugins from our JCG partner Ian Skerrett at the Ian Skerrett’s blog blog....
java-logo

About Java Packages

I hope we all agree that methods an classes should be small and have only few dependencies. This point of view is widely accepted, while the interpretation of “small” varies. There is lots of literature out there about this. But what about packages? Some people consider packages just as namespaces. So packages are just things that allow you to reuse names for classes!? I thought so about methods a couple of years ago: Just containers for reusable code. Today I disagree with both statements. Methods are a very important tool to name a thing, to separate it from the rest, even when it is called only once. Likewise packages have an important role even when we ignore the issue of names. Packages bundle together some functionality. They name that functionality and they should encapsulate it so we might reuse it. And just as with methods a package should have single purpose. It is probably a ‘bigger’ purpose than that of a method but still it should do only stuff directly related to that purpose. Unfortunately in many projects this doesn’t work out well. Here is a challenge. Pick a random package out of your current project. For this package answer the following questionsWhat is the purpose of that package? Please use a single simple sentence. Does this sentence match the name of the package? Go through the classes of that package do they all work together to achieve the purpose of the class? Or are there classes in there that just ended up there by accident? Go through all the other classes of your system. Is none of them concerned with the single purpose of your package? Or are there classes that float around somewhere else that really should be in the package you are looking at? If your coworker in the next project needs basically the same package, how difficult would it be to extract the package from your code base and build it as a standalone jar?In my experience it is very likely that the answers to the questions above are rather depressing. They certainly are in most projects I worked with. Even when the classes and methods in that project are reasonable clean. Why is that? I think the reason is that problems with packages are not as obvious as with methods or classes. If a methods spans across the complete monitor you see that every time all the time you are working with the method. And since the method is long there is probably much work to be done in it. Same for classes. But with packages is different. I spend whole days coding without looking what is inside a package . I open my classes with shortcuts and name based search, no need to look inside packages. So you won’t notice that classes concerned with completely different issues are together in one package. You won’t notice that the number of classes in a package exceeds any reasonable threshold. And if it comes to the last question, the question about dependencies it becomes really ugly. What other packages does a package depend on? Which class contains that dependency? There is very limited tool support for this kind of question. And the question only gets asked late in a project, maybe when a sister project gets spawned that should reuse some of the code base so it should move in a common base project. Since I have been there a couple of times I recommend to implement a couple of tests right in the beginning of a project using either JDepend or Dependency Finder:No cyclic dependencies between packages A maximum number of classes per package A fixed naming schema like <domain>.<project>.<module>.<layer>.<rest-of-package-name> A fixed direction of dependencies between modules (modules are vertical slices, often based on some domain concept) A fixed direction of dependencies between layers ( gui, presentation, domain, persistence are typical examples)But be warned: these tests tend to be hard to keep satisfied. But if you put in the extra effort to keep your packages clean it has a significant positive impact on your application structure. Reference: About Packages from our JCG partner Jens Schauder at the Schauderhaft blog....
netbeans-logo

NetBeans 7.2 beta: Faster and More Helpful

There has been significant excitement about the beta release of NetBeans 7.2. In this post, I look briefly at what makes this release so exciting (including better performance, providing more hints, and integrating FindBugs). NetBeans 7.2 beta is available in the typical download bundles, ranging from the smaller Java SE, C/C++, and PHP bundles to the larger Java EE and “All” bundles. Installation of NetBeans 7.2 is as easy as ever and there are installation instructions for multiple platforms. Speed! The NetBeans IDE 7.2 Beta Release Notes include a section called What’s New in 7.2 Beta which states of NetBeans 7.2, “Significant performance increase on remote filesystems, improved project scanning speed, and background project scanning.” As I discussed in my recent post NetBeans Usability Tips, larger projects or numerous associated projects can lead to significant NetBeans performance degradation. In that post, I looked at how one can turn off that background source scanning to avoid this when necessary. The NetBeans development team has apparently heard many others wish for quicker scanning and they have focused on this and quicker startup for NetBeans 7.2 beta The NetBeans 72 NewAndNoteworthy page provides additional information on the quicker performance. It states, “The indexes and indexing infrastructure were rewritten to use transactions. The project scanning and up to date check do not block editor features nor navigation. These features use the previous committed index. Also the write transactions are suspended by read transactions, so the background indexing has lower priority than user actions.” That same page also states, “The binary indexers run in parallel which makes indexing of java project faster.” New NetBeans Hints I like NetBeans’s hints so much that I have written multiple posts about them: Seven Indispensable NetBeans Java Hints, Seven NetBeans Hints for Modernizing Java Code, and Creating a NetBeans 7.1 Custom Hint. NetBeans 7.2 adds several new hints including “Generate Implementing/Extending Class,” “Zero Element Array Passed to Collection.toArray,” “Method Result not Checked” (uses the FindBugs annotation @CheckReturnValue), “Generate switch Clauses,” and “Fix Missing return Statement.” One of the new hints added in NetBeans 7.2 would have fit nicely in my post Seven NetBeans Hints for Modernizing Java Code. The “Add Underscores to Integer Literals” hint can help “modernize” Java code bases to leverage this new Java 7 feature. The following screen snapshots demonstrate the utility of the new NetBeans 7.2 hint for including underscores in integer literals to improve readability. As the first screen snapshot indicates, there is some configuration available related to this hint. Also note that in my case of upgrading from NetBeans 7.1.1 to NetBeans 7.2 beta, this hint was not enabled (not checked) in the Tools | Options | Editor | Hint area.FindBugs Integration NetBeans 7.2 beta integrates FindBugs into the IDE. This makes it even easier and more intuitive to apply FindBugs to Java code in NetBeans than use of the Software Quality Environment I discussed in the post NetBeans 7 and Software Quality Environment. The FindBugs Integration Plugin can be installed on NetBeans 7.2 beta using the Tools | Plugins | Available Plugins approach shown in the next screen snapshot.An alternative approach for acquiring and installing the FindBugs Integration Plugin is through the source code inspection process. This can be done by selecting Source | Inspect (shown in next two images).Note that FindBugs Integration is one of the items that can be explicitly selected, but I prefer to use “All Analzyers.” Click on the “Install” button to see what “additional plugins [are] required for the selected configuration.” In the case of the newly installed NetBeans 7.2 beta, the following appeared when I clicked on that “Install” button.Once FindBugs Integration 1.8 plugin is installed, NetBeans begins reported FindBugs findings.As noted in this post’s section on the new NetBeans hints, the FindBugs annotation @CheckReturnValue is also now supported by a NetBeans hint. JavaFX SceneBuilder Support The SceneBuilder tool is an IDE-independent standalone tool announced at JavaOne 2011 for generating JavaFX interfaces that was released to the public earlier this year. As Cindy Castillo states in the post JavaFX Scene Builder Docs Updated, the Getting Started with JavaFX Scene Builder documentation now discusses (in fact, requires) use of NetBeans 7.2 beta for the tutorial. The SceneBuilder is still a separate tool, but it can be opened from NetBeans by simply clicking on an FXML file. The clicked-on FXML file will be loaded in the SceneBuilder instance that is started. Miscellaneous Improvements NetBeans 7.2 beta includes several other improvement including supporting and bundling of Ant 1.8.3, bundling Maven 3.0.4, C++11 support, support for Java 7 Update 4, and support for Oracle Cloud. The NetBeans 7.2 integration of TestNG is also interesting. Conclusion There’s a lot to like about NetBeans 7.2, even in its beta release. It is faster and more helpful than its direct predecessors and integrates with many of the most popular Java and software tools and frameworks available today. The NetBeans 7.2 beta fanfare even attracted a self-proclaimed Eclipse user to try it out. There is substance behind the fanfare in this case. As Chris Mayer has stated regarding NetBeans 7.2 beta, “The most inclusive IDE just got a little bit sweeter.” Reference: NetBeans 7.2 beta: Faster and More Helpful from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
software-development-2-logo

Consumerization of IT – What it means for the Architect

Consumerization is described as the trend for IT to first emerge in the Consumer space and subsequently makes its way into the enterprise world. But what exactly in the consumer world, that is making the users, demand the similar things from the enterprise IT. To understand the underlying need, we need to first examine the basic requirements of the user.Kathy Sierra, co-creator of the Head First series of books and founder of javaranch.com, describes the hierarchy of needs from the user(s) perspective. The needs are stacked in the order of increasing engagement from the user. Starting with the basic needs of a defined functionality and its correctness, moving on to the learnability, efficiency & usability and finally culminating in intuitiveness and enchantment. Merely provision of correctly working functionality is not guarantee of the success of the application(s). The idea is to hook the user; the application needs to do something extra. Using the hierarchy of needs as the background, we will see how the applications in the consumer and enterprise world stack up. Now, in the consumer world, the advent of Consumerization started with the proliferation of the mobile devices. In the connected world, the device (smartphone or tablet) imposed certain constraintsScreen size is small and limited Processing power of the device is limited Interface is touch enabled Connectivity is not constant (read patchy) and speed/data is limited (no unlimited data plans) User audience demography not knownNow, the Apps needed to be designed keeping in mind the constraints, which meant that the Apps areFocused on providing only one functionality Have simple and intuitive messages/steps in the absence of any help/guides Providing simple interfaces (cater to worldwide audience) Having uncluttered screens as real estate is limited Using UI Controls that are big and usable (touch interface) Having intuitive workflows Engaging to stand apart among the millions of other AppsThis meant that the functionality does not require the user to be a geek. The average individual user can understand and use the App functionality without any external help. Majority of the Consumer Apps are heavily focused on the Efficiency and Usability part. Few of the Apps have been able to enchant and engage the user (e.g. Angry Birds). In the enterprise world, the device is most likely to be powerful desktop/laptop with a large screen. The connectivity is via LAN or broadband. As a result the Enterprise Applications are more industrial with high focus on providing long list of functionality and ensuring the correctness of the same. Consumers facing business applications usually focused on usability, Specialized enterprise applications (e.g. Call Center Applications) focus on the overall workflow efficiency, but majority of the applications are resource intensive, lack efficiency and have high learnability curves. The enterprise user experiences the simple, intuitive consumer apps on their mobile devices. With the advent of BYOD (Bring Your Own Device), enterprise user’s started bringing their smart devices into the enterprise. Soon the users are comparing the experience of consumer apps with the enterprise business apps; they wonder why the enterprise apps can’t provide a similar experience. Why are the enterprise apps so low on learnability, efficiency, intuitiveness factors? The whole idea behind the Consumerization of IT is not just measures like BYOD but to bring the missing intuitiveness, usability and efficiency into the enterprise applications. So, what does Consumerization means for the Architect? When designing and architecting enterprise business applications, following considerations need to be kept in mindConnected users means the applications need to be available 24 X 7 ( Always On, Always Available), 24 X 7 availability requires application solution(s) to be elastic – expand or shrink based on the load Intuitiveness and Usability have to be high on the agenda when designing the interface and workflows Solution needs offer APIs for additional applications to be build Integration with systems and other applications (including SaaS) need to be simple, straight forward and well documented User experience is the key to successful business application (it was always the key) but need to be (re)designed for the connected & mobile devices Product evaluation(s) will now include SaaS applications that can provide the functionality Saas adoption will increase leading to newer challenges in integration, data security and privacy measures Applications need to be designed/tested keeping in mind various devices/OS combinations (days of designing apps that worked on IE6 only are over)The impact of consumerization on the Enterprise IT will be felt in the years to comes, BYOD is just the harbinger of things to come. Reference: Consumerization of IT – what it means for the Architect from our JCG partner Munish K Gupta at the Tech Spot blog....
enterprise-java-logo

ADF Task Flow: Managed bean scopes for page fragments

Introduction When we work with ADF Task Flows and need to implement some flow specific business logic or store some information connected with the flow, we usually use pageFlowScope managed beans. And when we need to service view activities of the flow (pages or page fragments) we use shorter scopes for such managed beans. The common practice is to use requestScope, backingBeanScope and viewScope scopes for pages/fragments backing beans. In this post I’m going to play with these three options and discover the differences in the behavior of fragment based Task Flow. Let’s say I have some simple task flow template task-flow-template.xml: <managed-bean id="__5"> <managed-bean-name id="__3">viewBean</managed-bean-name> <managed-bean-class id="__2">com.cs.blog.ViewBean</managed-bean-class> <managed-bean-scope id="__4">request</managed-bean-scope> </managed-bean> <managed-bean id="__15"> <managed-bean-name id="__13">flowBean</managed-bean-name> <managed-bean-class id="__12">com.cs.blog.FlowBean</managed-bean-class> <managed-bean-scope id="__14">pageFlow</managed-bean-scope> </managed-bean><view id="MainView"> <page>/MainView.jsff</page> </view>It has one view activity MainView and two backing beans. The flowBean has pageFlow scope and is responsible to store flow information. The viewBean has request scope (we will play with that) and it services the ManView view activity. The flowBean has the following method returning the tittle of the task flow: public String getFlowTitle() { return null; }The viewBean has some string field testString to store input value: protected String testString; public void setTestString(String testString) { this.testString = testString; }public String getTestString() { return testString; }The MainView shows the task flow’s title and has an inputText for the testString. It looks like this:We also have two task flows built on the task-flow-template – first-flow-definition and second-flow-definition. They have overridden managed beans. For the first-flow-definition: <managed-bean id="__5"> <managed-bean-name id="__3">viewBean</managed-bean-name> <managed-bean-class id="__21">com.cs.blog.FirstViewBean</managed-bean-class> <managed-bean-scope id="__4">request</managed-bean-scope> </managed-bean> <managed-bean id="__15"> <managed-bean-name id="__13">flowBean</managed-bean-name> <managed-bean-class id="__12">com.cs.blog.FirstFlowBean</managed-bean-class> <managed-bean-scope id="__14">pageFlow</managed-bean-scope> </managed-bean>public class FirstFlowBean extends FlowBean { public FirstFlowBean() { super(); } public String getFlowTitle() { return "FirstFlow"; } }public class FirstViewBean extends ViewBean { public FirstViewBean() { super(); } @PostConstruct public void init() { testString = "FirstFlow"; } }So the title and default value for testString is “FirstFlow”. For the second-flow-definition: <managed-bean id="__5"> <managed-bean-name id="__3">viewBean</managed-bean-name> <managed-bean-class id="__21">com.cs.blog.SecondViewBean</managed-bean-class> <managed-bean-scope id="__4">request</managed-bean-scope> </managed-bean> <managed-bean id="__15"> <managed-bean-name id="__13">flowBean</managed-bean-name> <managed-bean-class id="__12">com.cs.blog.SecondFlowBean</managed-bean-class> <managed-bean-scope id="__14">pageFlow</managed-bean-scope> </managed-bean>public class SecondFlowBean extends FlowBean { public SecondfFowBean() { super(); } public String getFlowTitle() { return "SecondFlow"; } }public class SecondViewBean extends ViewBean { public SecondViewBean() { super(); } @PostConstruct public void init() { testString = "SecondFlow"; } }So the title and default value for testString is “SecondFlow”. Ok. It’s time to experiment. Let’s put on our page two regions with first-flow-definition and second-flow-definition task flows: <af:region value="#{bindings.firstflowdefinition1.regionModel}" id="r1"/> <af:separator id="s1"/> <af:region value="#{bindings.secondflowdefinition1.regionModel}" id="r2" />requestScope Leaving the scope for the viewBean as requestScope we will get the following result:In the SecondFlow we see the testString from the FirstViewBean instance. We can have only one instance of the requestScope bean per request. The viewBean was created for the FirstFlow task flow and the same instance was used again for the SecondFlow. backingBeanScope   Somebody could recommend to use backingBeanScope for the viewBean instead of requestScope. The backingBeanScope is commonly used to manage regions and declarative components. It has the same length of life as the requestScope but for different instances of regions/declarative components you will have separate instances of backingBean scoped managed beans. In our case we have two different regions, so let’s try:And, Yes, the backingBeanScope has fixed the problem. We have two instances of the viewBean – for the regions r1 and r2. But let’s make the first-flow-definition task flow a bit more complicated:Now we can call child task flow (of the same definition) from the MainView. And let’s repeat the experiment. On the initial rendering:   So far, so good. Let’s input something in the input text of the FirstFlow and press “call child task flow”:Oooops! We have only one instance of the viewBean for the region r1 during the request. So, value “FirstFlow111111″ entered in the parent task flow was rendered again in the child task flow. viewScope   And now let’s change the viewBean’s scope to the viewScope and have the same experiment. On the initial rendering:   Ok. Inputting the same garbage in the inputText:And pressing the “call child task flow”:And everything is ok. We have not only separate viewScope beans instances for different viewport IDs (for different regions and task flow instances), but additionally the controller is resetting the viewScope during the navigation process. But the cheese is not free. You have to pay by memory. If requestScope or backingBeanScope live not longer than the request, viewScope lives in memory until the viewport ID is changed. Perhaps in my further posts I will show how to manage the issue with the backingBeanScope. So, when you choose the appropriate scope for your fragment managed beans, consider how the task flow is going to be used. Probably, in order to get really high reusable task flow, using the viewScope is the best approach for fragment beans. That’s it! Reference: Managed bean scopes for page fragments in ADF Task Flow from our JCG partner Eugene Fedorenko at the ADF Practice blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books