What's New Here?


How Agile is a Scrum team?

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));Most teams I meet today are agile. Or, so they proclaim to be. All of these teams do Scrum, and that makes them agile. Doesn’t it? If I look back at the 12 practices the Agile Manifesto is build on (short: the Agile practices) I conclude that Scrum values a subset: the planning game, on-site customer, small releases and whole team. Yet most of the teams doing Scrum that I meet have no customer on-site, although the teams do value this practice. Furthermore I mostly see a formal separation of developers and QA, and more often than not these teams use large releases (more than a few months). On the up side, most teams use Continuous Integration and have a set of coding standards, often formal. The average of applying 3 out of the 12 Agile practices makes me wonder. Are these teams actually agile? Or maybe they are just a “little agile”. Is that a thing? Agile Principles Let’s take a look at the Principles behind the Agile Manifesto. The number one priority is “to satisfy the customer through early and continuous delivery of valuable software”. Closely followed by the importance to (even late in development) embrace changing requirements and the notion that working software is the primary measure of progress. These may seem to be supported by the planning game with user stories, doing the most valuable story first. That way the customer gets the most value out of each sprint, right? While that’s true, I believe there’s more to it. While valuable software is very important, I think the key is in the early and continuous delivery of software. We add value to software by changing and extending it. This is what the planning game and user stories won’t help us with. But changing software is highly valued by the Agile Principles. Rest of the Agile Practices And therefore there are Agile Practices that support us in changing software, enabling us to embrace change of requirements. These practices include automation of acceptance tests, test-driven development, pair programming, simple design and refactoring (not in any specific order). I wonder how well Scrum teams can keep up the agile principles if they don’t follow any other of these practices. I’ve seen teams respond to new requirements by demanding a “refactor sprint” to clean up the mess they made. Because there was no way to incorporate the changes otherwise. I’ve been on such teams years ago. I won’t state that it’s impossible for teams to continuously deliver valuable software without following most of the agile practices. But I do wonder how they at all could. I mean, without simple design and constantly keeping the code clean, how well can code be changed, even in a few months from creating it? What raises a flag for a broker feature when lacking stable unit and acceptance test suites? So without most of the agile practices, can you really get into a stable and continuous delivery of value? Scrum I don’t think Scrum is to blame here. Don’t get me wrong. I like Scrum. Scrum mostly embodies the planning and management rules of Extreme Programming (XP). I believe it’s thanks to Scrum that much of the planning and management practices have made their way into mainstream today. It’s just because Scrum doesn’t include the other Agile practices many folks doing Scrum think that those are somehow unimportant. The most successful teams I’ve seen are all doing most, if not all, of the other Agile practices as well. This is also totally possible for a Scrum team. You’re mileage may vary Over the past years I’ve been practicing different ways to write software, but every time I got back to the agile practices as I find them to work best. You’re mileage may vary, of course. If you use different practices that even better support the Agile principles I would love to hear about them and try them myself.Reference: How Agile is a Scrum team? from our JCG partner Bart Bakker at the Software Craft blog....

Effective learning techniques for software craftsmen

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));Go in one ear and out the other Programming languages, operating systems, SQL, NoSQL, web frameworks, Spring, Java EE, HTML, JavaScript, Agile methodologies , you name it. A developer must know a ridiculous amount of things to become effective. There’s no wonder many of us are struggling to keep pace with the ever-changing programming landscape. When you’re a kid, doing stuff is the most natural way of learning, but then you go to school and you’re brainwashed into thinking that reading is the only way of studying. Become an active learner Ever since I started writing this blog I began to question my old ways of learning. I used to be a passive learner, reading books, articles or watching videos. But I realized this is not working the way it should, so I started looking for alternatives. Edgar Dale‘s evaluated the most common learning techniques and came up with the famous Cone of experience. Basically, if you want to be a better developer you need to become an active learner. Writing a blog Until you start writing, you don’t really appreciate the actual effort put into coming up with a decent article. Writing down your findings not only helps the community, it helps your too. The writing process is going to teach you more about a given subject. You want to publish quality articles and the upcoming critique is going to be a good motivator. Contributing to your favourite frameworks The customer doesn’t want you to spend his money on writing frameworks, so your company makes use of high-quality open source frameworks. This is cost effective, but someone has to write those frameworks after all. It’s time for our employers to realize that contributing is a form of investment. Getting involved is the best way to master a given technology. Passionate developers will allocate their spare time in this purpose, but it doesn’t always have to be that way. What if all employers will allocate developers some hours for contributing to those open source projects they’ve been employing? You’ll meet other great guys with solid developing skills and this is probably a cheaper way of training your developers. Contributing to your own frameworks If you want developers to appreciate all the effort put into managing, testing or marketing, the best way is to have them lead their own open source project. Starting your own GitHub project is going to teach you a lot about Product ownership, software design or marketing techniques. Writing frameworks is so much different than the current enterprise developing experience. You need to pay extra attention to your framework programming usability for your adopters to spend the minimum amount of time while employing your software. Conclusion Getting involved is the true way of the software craftsman. A pragmatic programmer never bashes his tools, giving a helping hand instead. Helping building a better software community is the most effective way of becoming a better developer.Reference: Effective learning techniques for software craftsmen from our JCG partner Vlad Mihalcea at the Vlad Mihalcea’s Blog blog....

Common Misconceptions About Java

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));Java is the most widely used language in the world ([citation needed]), and everyone has an opinion about it. Due to it being mainstream, it is usually mocked, and sometimes rightly so, but sometimes the criticism just doesn’t touch reality. I’ll try to explain my favorite 5 misconceptions about Java.              Java is slow – that might have been true for Java 1.0, and initially may sounds logical, since java is not compiled to binary, but to bytecode, which is in turn interpreted. However, modern versions of the JVM are very, very optimized (JVM optimizations is a topic worth not just an article, but a whole book) and this is no longer remotely true. As noted here, Java is even on-par with C++ in some cases. And it is certainly not a good idea to make a joke about Java being slow if you are a Ruby or PHP developer. Java is too verbose – here we need to split the language from the SDK and from other libraries.There is some verbosity in the JDK (e.g. java.io), which is: 1. easily overcome with de-facto standard libraries like guava 2. a good thing As for language verbosity, the only reasonable point were anonymous classes. Which are no longer an issue in Java 8 with the the functional additions. Getters and setters, Foo foo = new Foo() instead of using val – that is (possibly) boilerplate, but it’s not verbose – it doesn’t add conceptual weight to the code. It doesn’t take more time to write, read or understand. Other libraries – it is indeed pretty scary to see a class like AbstractCommonAsyncFacadeFactoryManagerImpl. But that has nothing to do with Java. It can be argued that sometimes these long names make sense, it can also be argued that they are as complex because the underlying abstraction is unnecessarily complicated, but either way, it is a design decision taken per-library, and nothing that the language or the SDK impose per-se. It is common to see overengineered stuff, but Java in no way pushes you in that direction – stuff can be done in a simple way with any language. You can certainly have AbstractCommonAsyncFacadeFactoryManagerImpl in Ruby, just there wasn’t a stupid architect that thought it’s a good idea and who uses Ruby. If “big, serious, heavy” companies were using Ruby, I bet we’d see the same.Enterprise Java frameworks are bloatware – that was certainly true back in 2002 when EJB 2 was in use (or “has been”, I’m too young to remember). And there are still some overengineered and bloated application servers that you don’t really need. The fact that people are using them is their own problem. You can have a perfectly nice, readable, easy to configure and deploy web application with a framework like Spring, Guice or even CDI; with a web framework like Spring-MVC, Play, Wicket, and even the latest JSF. Or even without any framework, if you feel like you don’t want to reuse the evolved-through-real-world-use frameworks. You can have an application using a message queue, a NoSQL and a SQL database, Amazon S3 file storage, and whatnot, without any accidental complexity. It’s true that people still like to overeingineer stuff, and add a couple of layers where they are not needed, but the fact that frameworks give you this ability doesn’t mean they make you do it. For example, here’s an application that crawls government documents, indexes them, and provides a UI for searching and subscribing. Sounds sort-of simple, and it is. It is written in Scala (in a very java way), but uses only java frameworks – spring, spring-mvc, lucene, jackson, guava. I guess you can start maintaining pretty fast, because it is straightforward. You can’t prototype quickly with Java – this is sort-of related to the previous point – it is assumed that working with Java is slow, and that’s why if you are a startup, or a weekend/hackathon project, you should use Ruby (with Rails), Python, Node JS or anything else that allows you to quickly prototype, to save & refresh, to painlessly iterate. Well, that is simply not true, and I don’t know even where it comes from. Maybe from the fact that big companies with heavy processes use Java, and so making a java app is taking more time. And Save-and-Refresh might look daunting to a beginner, but anyone who has programmed in Java (for the web) for a while, has to know a way to automate that (otherwise he’s a n00b, right?). I’ve summarized the possible approaches, and all of them are mostly OK. Another example here (which may be used as an example for the above point as well) – I made did this project for verifying secure password storage of websites within a weekend + 1 day to fix stuff in the evening. Including the security research. Spring-MVC, JSP templates, MongoDB. Again – quick and easy. You can do nothing in Java without an IDE – of course you can – you can use notepad++, vim, emacs. You will just lack refactoring, compile-on-save, call hierarchies. It would be just like programming in PHP or Python or javascript. The IDE vs Editor debate is a long one, but you can use Java without an IDE. It just doesn’t make sense to do so, because you get so much more from the IDE than from a text editor + command line tools.You may argue that I’m able to write nice and simple java applications quickly because I have a lot of experience, I know precisely which tools to use (and which not) and that I’m of some rare breed of developers with common sense. And while I’ll be flattered by that, I am no different than the good Ruby developer or the Python guru you may be. It’s just that java is too widespread to have only good developers and tools. if so many people were using other language, then probably the same amount of crappy code would’ve been generated. (And PHP is already way ahead even with less usage). I’m the last person not to laugh on jokes about Java, and it certainly isn’t the silver bullet language, but I’d be happier if people had less misconceptions either because of anecdotal evidence, or due to previous bad experience a-la “I hate Java since my previous company where the project was very bloated”. Not only because I don’t like people being biased, but because you may start your next project with a language that will not work, just because you’ve heard “Java is bad”.Reference: Common Misconceptions About Java from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog....

Using Android Location API in Weather App – Search city

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));In this post I would like to describe how to search a city using openweathermap to get weather conditions. There are two way we can use to find a city:Using name pattern Using geographic coordinates (Android Location API)We will introduce, moreover, some concepts about Android location API and Location-based service.   Searching city by name In this kind of search, an user inserts a part of city name and the app will show all the possible result matching the pattern. From the UI perspective, we want to obtain something like the image shown below:  As first step, we can use EditText so that the user can insert the city name: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >.... <EditText android:id="@+id/cityEdtText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="5dp" android:imeOptions="actionSearch" android:inputType="text" > <requestFocus /> </EditText> ....<ListView android:id="@+id/cityList" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/txt1" android:layout_marginTop="3dp"/></RelativeLayout> Notice that at line 13, we used imeOptions with “actionSearch” value to specify search action when user completes inserting the city name pattern. Now in the Activity that holds this layout we have: final EditText edt = (EditText) findViewById(R.id.cityEdtText);edt.setOnEditorActionListener(new TextView.OnEditorActionListener() {@Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { bar.setVisibility(View.VISIBLE); JSONSearchTask task = new JSONSearchTask(); String pattern = edt.getEditableText().toString(); task.execute(new String[]{pattern}); return true; }return false; } }); So when user clicks on search icon, we starts searching for matching city names and at the end we will populate a ListView (line 18) . As you can notice, we start an AsyncTask, because the search operation can require quite long time and we don’t want to have ANR problems. Now it is time to implement the logic that calls the remote openweathermap service and retrieve the cities. We know from API that the URL to call is: http://api.openweathermap.org/data/2.5/find?mode=json&type=like&q=...&cnt=10 where after q we will add our pattern name and cnt represents the number of items we want to get (in our case we want 10 results at maximum). Once we have the data, we parse it. We look for list tag that holds the result and for each item in the result we look for name tag that holds the name, the id and the country. The parser is very simple: public static List<City> getCityList(String data) throws JSONException { JSONObject jObj = new JSONObject(data); JSONArray jArr = jObj.getJSONArray("list"); List<City> cityList = new ArrayList<City>(); for (int i=0; i < jArr.length(); i++) { JSONObject obj = jArr.getJSONObject(i); String name = obj.getString("name"); String id = obj.getString("id"); JSONObject sys = obj.getJSONObject("sys"); String country = sys.getString("country"); City c = new City(id,name,country); cityList.add(c); } return cityList; }..and finally we populate the ListView to show the results to the user. This happen in  onPostExecute method of the AsyncTask. Notice that you can create a custom Adapter to show this information or you can use a standard Adapter. Search city using geographic coordinates: Android Location API Another way to look for the city is using the current user position. We can use Location based service to find the current device position using GPS or WI-FI or cell network. There are two main element when implementing Location based service:Location Manager that is the entry point to the Location based service Location Provider representing the location technology used to find the device positionThe first step is getting the LocationManager reference. This is a system service, then we can use: LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); once we have our Location Manager reference we can find the provider. In our case, we don’t want to specify a specific provider (like GPS for example) but let the system find the best matching the search criteria we set: private static Criteria searchProviderCriteria = new Criteria();// Location Criteria static { searchProviderCriteria.setPowerRequirement(Criteria.POWER_LOW); searchProviderCriteria.setAccuracy(Criteria.ACCURACY_COARSE); searchProviderCriteria.setCostAllowed(false); } and then we are ready to get the provider: String provider = locManager.getBestProvider(searchProviderCriteria, true); and: Location loc = locManager.getLastKnownLocation(provider); Now we have to check if the location is null or is too old, in this case we get a new position: if (loc == null || (SystemClock.elapsedRealtime() - loc.getTime()) > timeOut) { // We request another update Location Log.d("SwA", "Request location"); locManager.requestSingleUpdate(provider, locListener, null); } else { JSONSearchTask task = new JSONSearchTask(); task.execute(new Location[]{loc}); } otherwise we simply call the service to get the city. Notice at line 4, that we need a listener that implements some callback methods, that will be called when the current position is available: private LocationListener locListener = new LocationListener() {@Override public void onStatusChanged(String provider, int status, Bundle extras) { }@Override public void onProviderEnabled(String provider) { }@Override public void onProviderDisabled(String provider) { }@Override public void onLocationChanged(Location location) { Log.d("SwA", "Location changed!"); String sLat = "" + location.getLatitude(); String sLon = "" + location.getLongitude(); Log.d("SwA", "Lat ["+sLat+"] - sLong ["+sLon+"]");LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locManager.removeUpdates(locListener); JSONSearchTask task = new JSONSearchTask(); task.execute(new Location[]{location}); } }; The last step is creating the URL that will be called to retrieve the city from the geographic coordinates. In this case the url to call is: http://api.openweathermap.org/data/2.5/find?lat=%lat%&lon=%lon% where the %lat% and &lon% will be substituted by the real value extracted from the current position. Using emulator to test the app The last step is testing the app passing the coordinates. We can use DDMSDDMS and pass the coordinates:  Please notice that you should separate the decimal part according to your language and number format. Another way is using telnet iphost port and when connected send geo fix <longitude value> <latitude value>Reference: Using Android Location API in Weather App – Search city from our JCG partner Francesco Azzola at the Surviving w/ Android blog....

Consume Webservice in Android using intentService

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));In this post, I will explain how to consume Restful Webservice using IntentService. We know we can consume a Webservice directly in the UI using for example Volley lib or a simple Http client, but there are some cases when we prefer to consume a Webservice in an Android Service. We know that Android Service has a “longer” life than an Android Activity and if we want a task is completed even if the app UI is no longer available we should use a Service. We can consider for example the download scenario: let’s suppose we want to download some information from a remote server; we can do it in the UI (i.e Activity) but if the user, for example, moves to another app the download will be interrupted. If we want to be sure that the download continues even if the app isn’t anymore active we can use Service. IntentService description When we want to consume a Webservice, we have to be aware that the time required to contact the server and get the response can be quite long. Even if we execute this logic is a separate service, the service itself runs in the main thread, so that the calling activity can lag, waiting for the response from the service, and the OS can kill it showing the annoying ANR message. We can avoid this problem handling a separate thread inside the service, but Android SDK provides a specialized class, derived from the Service class, called IntentService defined as (from Android API docs): “IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.This “work queue processor” pattern is commonly used to offload tasks from an application’s main thread.” Considering that the heavy work is made in a separate thread we don’t know when it will finish and the calling Activity is unaware of it. We will describe how to get back the information as the service retrieved data from the remote Webservice. Creating the IntentService As example we will use Yahoo! Finance Service to retrieve the current Ask and Bid value for a Stock. At the end we will build an app like this:  The first step is creating a service: public class QuoteService extends IntentService {@Override protected void onHandleIntent(Intent intent) { // Here we do the heavy work } }At line 4, in onHandleIntent we do the “heavy work”, so we call the remote Webservice and parse the response. In this case we can simply use XmlPullParser to parse the data: // Here we retrieve the stock quote using Yahoo! Finance Log.d("Srv", "Get stock"); String url = YAHOO_FINANCE_URL.replaceAll("#sym#", stock.getSymbol()); try { HttpURLConnection con = (HttpURLConnection) ( new URL(url)).openConnection(); con.setRequestMethod("GET"); con.connect(); InputStream is = con.getInputStream();// Start parsing XML XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); parser.setInput(is, null); int event = parser.getEventType(); String tagName = null; String currentTag = null; Stock stockResult = new Stock();while (event != XmlPullParser.END_DOCUMENT) { tagName = parser.getName(); Log.d("Srv", "Tag:" + tagName); if (event == XmlPullParser.START_TAG) { currentTag = tagName; } else if (event == XmlPullParser.TEXT) { if ("ASK".equalsIgnoreCase(currentTag)) // else if ("BID".equalsIgnoreCase(currentTag)) { // } }event = parser.next();}} catch (Exception e) { e.printStackTrace(); } Then we define our service in the Manifest.xml: <service android:name=".QuoteService" /> Activity: Webservice client The next step is creating the client activity that invokes the service. We are using an IntentService then the calling Activity calls the service and then forget it. The activity is quite trivial, because as soon as the user clicks “Get quote!” button we invoke the service using: startService(service_intent); Anyway, there are two aspects we should consider:How we pass the data to the service How we get the data back from the service and show the information in UITo pass data to the service we can create a simple java class that holds the stock symbol and the values we want to be filled by the service as we get the response. Our class should be a Parcelable class: public class Stock implements Parcelable {private String symbol; private double askValue; private double bidValue;public Stock() {}public Stock(String symbol, double askValue, double bidValue) { this.symbol = symbol; this.askValue = askValue; this.bidValue = bidValue; }// get and set method@Override public void writeToParcel(Parcel dest, int flags) { // We write the stock information in the parcel dest.writeString(symbol); dest.writeDouble(askValue); dest.writeDouble(bidValue); }public static final Creator<Stock> CREATOR = new Creator<Stock>() {@Override public Stock createFromParcel(Parcel source) { Stock stock = new Stock(); stock.setSymbol(source.readString()); stock.setAskValue(source.readDouble()); stock.setBidValue(source.readDouble()); return stock; }@Override public Stock[] newArray(int size) { return new Stock[0]; } };@Override public int describeContents() { return 0; } } At line 18 and 25, we implement the two methods required to marshal and unmarshal our class. Retrieve data from service using ResultReceiver Another interesting aspect is how we can get the values back from the IntentService. As we, already, know the calling activity doesn’t wait for the result, so we have to find another way. Generally speaking there are different ways to solve this problem, in this post I will explain how to use ResultReceiver. This method is quite simple and elegant in my opinion. The first step is creating a class that extends ResultReceiver, that we call QuoteServiceReceiver: public class QuoteServiceReceiver extends ResultReceiver {private Listener listener;public QuoteServiceReceiver(Handler handler) { super(handler); }public void setListener(Listener listener) { this.listener = listener; }@Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (listener != null) listener.onReceiveResult(resultCode, resultData); }public static interface Listener { void onReceiveResult(int resultCode, Bundle resultData); }} This class is very simple. At line 19 we define an interface that the calling activity has to implement to get notified when the data isavailable. In this interface we define a Bundle that holds the data retrieved. Then at line 14 we override the onReceiveResult and call our callback method defined in the previous interface. From the client point of view (so our Activity) we simply have to implements the interface defined and pass the QuoteServiceReceiver to the IntentService: private Intent createCallingIntent(Stock stock) { Intent i = new Intent(this, QuoteService.class); QuoteServiceReceiver receiver = new QuoteServiceReceiver(new Handler()); receiver.setListener(this); i.putExtra("rec", receiver); i.putExtra("stock", stock); return i; } and when we call the service: startService(createCallingIntent(stock)); ..and in the callback method: @Override public void onReceiveResult(int resultCode, Bundle resultData) { Stock stock = resultData.getParcelable("stock"); Log.d("Srv", "Stock ["+stock+"]");askValue.setText("" + stock.getAskValue()); bidValue.setText("" + stock.getBidValue()); } ..and here we update the UI, with the data received. In the service that consumes the remote Webservice: @Override protected void onHandleIntent(Intent intent) {Stock stock = intent.getParcelableExtra("stock"); final ResultReceiver rec = (ResultReceiver) intent.getParcelableExtra("rec"); .... // When data is ready if ("BID".equalsIgnoreCase(currentTag)) { stockResult.setBidValue(Double.parseDouble(parser.getText())); Bundle b = new Bundle(); b.putParcelable("stock", stockResult); rec.send(0, b); } .... }Source code available @ githubReference: Consume Webservice in Android using intentService from our JCG partner Francesco Azzola at the Surviving w/ Android blog....

Spring Test Context Caching + AspectJ @Transactional + Ehcache pain

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));Are you using AspectJ @Transactionals and Spring? Do you have multiple SessionFactory’s maybe one for an embedded database for unit testing and one for the real database for integration testing? Are you getting one of these exceptions?org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.service.UnknownServiceException: Unknown service requestedorjava.lang.NullPointerException at net.sf.ehcache.Cache.isKeyInCache(Cache.java:3068) at org.hibernate.cache.ehcache.internal.regions.EhcacheDataRegion.contains(EhcacheDataRegion.java:223)Then you are running in to a problem where multiple, cached application contexts are stepping on each other. This blog post will describe some strategies to deal with the problems that we have encountered. Background Spring’s Text Context framework by default tries to minimize the number of times the spring container has to start by caching the containers. If you are running multiple tests that all use the same configuration, then you will only have to create the container once for all the tests instead of creating it before each test. If you have 1000′s of tests and the container takes 10-15 seconds to startup, this makes a real difference in build/test time. This only works if everyone (you and all of the libraries that you use) avoid static fields (global state), and unfortunately there are places where this is difficult/impossible to avoid — even spring violates this! A few places that have caused us problems:Spring AspectJ @Transactional support EhCache cache managersAspects are singletons by design. Spring uses this to place a reference to the BeanFactory as well as the PlatformTransactionManager. If you have multiple containers each with their “own” AnnotationTransactionAspect, they are in fact sharing the AnnotationTransactionAspect and whichever container starts up last is the “winner” causing all kinds of unexpected hard to debug problems. Ehcache is also a pain here. The ehcache library maints a static list of all of the cache managers that it has created in the VM. So if you want to use multiple containers, they will all share a reference to the same cache. Spring Test gives you a mechanism to indicate that this test has “dirtied” the container and that it needs to be created. This translates to destroying the container after the test class is finished. This is fine, but if your container has objects that are shared by the other containers, then destroying that shared object breaks the other containers. Solutions The easiest solution is to basically disable the application context caching entirely. This can be done simply by placing @DirtiesContext on every test or (better) you probably should use super classes (“abstract test fixtures”) to organize your tests anyways, in which case just add @DirtiesContext on the base class. Unfortunately you also lose all of the benefit of caching and your build times will increase. There is no general mechanism for the spring container to “clean itself up”, because this sharing of state across container is certainly an anti-pattern. The fact that they themselves do it (AnnotationTransactionAspect, EhCacheManagerFactoryBean.setShared(true), etc.) is an indication that perhaps they should add some support. If you want to keep caching, then step 1 is making sure that you don’t use any “static field” singletons in your code. Also make sure that any external resources that you write to are separated so that multiple containers can co-exist in the same JVM. To address the AspectJ problem, the best solution that I have found is to create a TestExecutionListener that “resets” the AnnotationTransactionAspect to point to the correct bean factory and PTM before test execution. The code for such a listener is in this gist. To then use the listener you put @TestListeners on your base class test fixture so that all tests run with the new listener. Note that when you use the @TestListeners annotation you then have to specify all of the execution listeners, including the existing Spring ones. There is an example in the gist. The workaround for Ehcache is to not allow CacheManager instances to be shared between containers. To do this, you have to ensure that the cache managers all have unique names. This is actually pretty easy to configure. @org.springframework.context.annotation.Configuration public class CacheBeans {private static final AtomicInteger cacheCounter = new AtomicInteger(0); @Bean public EhCacheManagerFactoryBean ecmfb() { EhCacheManagerFactoryBean ecmfb = new EhCacheManagerFactoryBean(); // cannot share the cache managers ecmfb.setShared(false); // if you are using ehcache.xml on the classpath then there's nothing more to do than just make it // a unique name. If you are using a different config file then use ecmfb.setConfigLocation() ecmfb.setCacheManagerName("ehCache-" + cacheCounter.incrementAndGet()); return ecmfb; } // more @Bean defs } Related Issues Here are some links to spring jira issues covering this problem: https://jira.spring.io/browse/SPR-6121 https://jira.spring.io/browse/SPR-6353Reference: Spring Test Context Caching + AspectJ @Transactional + Ehcache pain from our JCG partner Steve Ash at the Many Cups of Coffee blog....

Apache CXF 3.0: JAX-RS 2.0 and Bean Validation 1.1 finally together

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));The upcoming release 3.0 (currently in milestone 2 phase) of the great Apache CXF framework is bringing a lot of interesting and useful features, getting closer to deliver full-fledged JAX-RS 2.0 support. One of those features, a long-awaited by many of us, is the support of Bean Validation 1.1: easy and concise model to add validation capabilities to your REST services layer. In this blog post we are going to look how to configure Bean Validation 1.1 in your Apache CXF projects and discuss some interesting use cases. To keep this post reasonably short and focused, we will not discuss the Bean Validation 1.1 itself but concentrate more on integration with JAX-RS 2.0 resources (some of the bean validation basics we have already covered in the older posts). At the moment, Hibernate Validator is the de-facto reference implementation of Bean Validation 1.1 specification, with the latest version being 5.1.0.Final and as such it will be the validation provider of our choice (Apache BVal project at the moment supports only Bean Validation 1.0). It is worth to mention that Apache CXF is agnostic to implementation and will work equally well either with Hibernate Validator or Apache BVal once released. We are going to build a very simple application to manage people. Our model consists of one single class named Person. package com.example.model;import javax.validation.constraints.NotNull;import org.hibernate.validator.constraints.Email;public class Person { @NotNull @Email private String email; @NotNull private String firstName; @NotNull private String lastName;public Person() { }public Person( final String email ) { this.email = email; }public String getEmail() { return email; }public void setEmail( final String email ) { this.email = email; }public String getFirstName() { return firstName; }public String getLastName() { return lastName; }public void setFirstName( final String firstName ) { this.firstName = firstName; }public void setLastName( final String lastName ) { this.lastName = lastName; } } From snippet above we can see that Person class imposes couple of restrictions on its properties: all of them should not be null. Additionally, email property should contain a valid e-mail address (which will be validated by Hibernate Validator-specific constraint @Email). Pretty simple. Now, let us take a look on JAX-RS 2.0 resources with validation constraints. The skeleton of the PeopleRestService class is bind to /people URL path and is shown below. package com.example.rs;import java.util.Collection;import javax.inject.Inject; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo;import org.hibernate.validator.constraints.Length;import com.example.model.Person; import com.example.services.PeopleService;@Path( "/people" ) public class PeopleRestService { @Inject private PeopleService peopleService;// REST methods here } It should look very familiar, nothing new. The first method we are going to add and decorate with validation constraints is getPerson, which will look up a person by its e-mail address. @Produces( { MediaType.APPLICATION_JSON } ) @Path( "/{email}" ) @GET public @Valid Person getPerson( @Length( min = 5, max = 255 ) @PathParam( "email" ) final String email ) { return peopleService.getByEmail( email ); } There are a couple of differences from traditional JAX-RS 2.0 method declaration. Firstly, we would like the e-mail address (email path parameter) to be at least 5 characters long (but no more than 255 characters) which is imposed by @Length( min = 5, max = 255 ) annotation. Secondly, we would like to ensure that only valid person is returned by this method so we annotated the method’s return value with @Valid annotation. The effect of @Valid is very interesting: the person’s instance in question will be checked against all validation constraints declared by its class (Person). At the moment, Bean Validation 1.1 is not active by default in your Apache CXF projects so if you run your application and call this REST endpoint, all validation constraints will be simply ignored. The good news are that it is very easy to activate Bean Validation 1.1 as it requires only three components to be added to your usual configuration (please check out this feature documentation for more details and advanced configuration):JAXRSBeanValidationInInterceptor in-inteceptor: performs validation of the input parameters of JAX-RS 2.0 resource methods JAXRSBeanValidationOutInterceptor out-inteceptor: performs validation of return values of JAX-RS 2.0 resource methods ValidationExceptionMapper exception mapper: maps the validation violations to HTTP status codes. As per specification, all input parameters validation violations result into 400 Bad Request error. Respectively, all return values validation violations result into 500 Internal Server Error error. At the moment, the ValidationExceptionMapper does not include additional information into response (as it may violate application protocol) but it could be easily extended to provide more details about validation errors.The AppConfig class shows off one of the ways to wire up all the required components together using RuntimeDelegate and JAXRSServerFactoryBean (the XML-based configuration is also supported). package com.example.config;import java.util.Arrays;import javax.ws.rs.ext.RuntimeDelegate;import org.apache.cxf.bus.spring.SpringBus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.interceptor.Interceptor; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor; import org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor; import org.apache.cxf.jaxrs.validation.ValidationExceptionMapper; import org.apache.cxf.message.Message; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn;import com.example.rs.JaxRsApiApplication; import com.example.rs.PeopleRestService; import com.example.services.PeopleService; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;@Configuration public class AppConfig { @Bean( destroyMethod = "shutdown" ) public SpringBus cxf() { return new SpringBus(); }@Bean @DependsOn( "cxf" ) public Server jaxRsServer() { final JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); factory.setAddress( factory.getAddress() ); factory.setInInterceptors( Arrays.< Interceptor< ? extends Message > >asList( new JAXRSBeanValidationInInterceptor() ) ); factory.setOutInterceptors( Arrays.< Interceptor< ? extends Message > >asList( new JAXRSBeanValidationOutInterceptor() ) ); factory.setProviders( Arrays.asList( new ValidationExceptionMapper(), new JacksonJsonProvider() ) );return factory.create(); }@Bean public JaxRsApiApplication jaxRsApiApplication() { return new JaxRsApiApplication(); }@Bean public PeopleRestService peopleRestService() { return new PeopleRestService(); }@Bean public PeopleService peopleService() { return new PeopleService(); } } All in/out interceptors and exception mapper are injected. Great, let us build the project and run the server to validate the Bean Validation 1.1 is active and works as expected. mvn clean package java -jar target/jaxrs-2.0-validation-0.0.1-SNAPSHOT.jar Now, if we issue a REST request with short (or invalid) e-mail address a@b, the server should return 400 Bad Request. Let us validate that. > curl http://localhost:8080/rest/api/people/a@b -iHTTP/1.1 400 Bad Request Date: Wed, 26 Mar 2014 00:11:59 GMT Content-Length: 0 Server: Jetty(9.1.z-SNAPSHOT) Excellent! To be completely sure, we can check server console output and find there the validation exception of type ConstraintViolationException and its stacktrace. Plus, the last line provides the details what went wrong: PeopleRestService.getPerson.arg0: length must be between 5 and 255 (please notice, because argument names are not currently available on JVM after compilation, they are replaced by placeholders like arg0, arg1, …). WARNING: Interceptor for {http://rs.example.com/}PeopleRestService has thrown exception, unwinding now javax.validation.ConstraintViolationException at org.apache.cxf.validation.BeanValidationProvider.validateParameters(BeanValidationProvider.java:119) at org.apache.cxf.validation.BeanValidationInInterceptor.handleValidation(BeanValidationInInterceptor.java:59) at org.apache.cxf.validation.AbstractValidationInterceptor.handleMessage(AbstractValidationInterceptor.java:73) at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307) at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121) at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240) at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:197) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:149) at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:167) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:286) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:211) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:262) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:711) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:552) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1112) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:479) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1046) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) at org.eclipse.jetty.server.Server.handle(Server.java:462) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:281) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:232) at org.eclipse.jetty.io.AbstractConnection$1.run(AbstractConnection.java:505) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:607) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:536) at java.lang.Thread.run(Unknown Source)Mar 25, 2014 8:11:59 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.getPerson.arg0: length must be between 5 and 255 Moving on, we are going to add two more REST methods to demonstrate the collections and Response validation in action. @Produces( { MediaType.APPLICATION_JSON } ) @GET public @Valid Collection< Person > getPeople( @Min( 1 ) @QueryParam( "count" ) @DefaultValue( "1" ) final int count ) { return peopleService.getPeople( count ); } The @Valid annotation on collection of objects will ensure that every single object in collection is valid. The count parameter is also constrained to have the minimum value 1 by @Min( 1 ) annotation (the @DefaultValue is taken into account if the query parameter is not specified). Let us on purpose add the person without first and last names set so the resulting collection will contain at least one person instance which should not pass the validation process. > curl http://localhost:8080/rest/api/people -X POST -id "email=a@b3.com" With that, the call of getPeople REST method should return 500 Internal Server Error. Let us check that is the case. > curl -i http://localhost:8080/rest/api/people?count=10HTTP/1.1 500 Server Error Date: Wed, 26 Mar 2014 01:28:58 GMT Content-Length: 0 Server: Jetty(9.1.z-SNAPSHOT) Looking into server console output, the hint what is wrong is right there. Mar 25, 2014 9:28:58 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.getPeople.[0].firstName: may not be null Mar 25, 2014 9:28:58 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.getPeople.[0].lastName: may not be null And finally, yet another example, this time with generic Response object. @Valid @Produces( { MediaType.APPLICATION_JSON } ) @POST public Response addPerson( @Context final UriInfo uriInfo, @NotNull @Length( min = 5, max = 255 ) @FormParam( "email" ) final String email, @FormParam( "firstName" ) final String firstName, @FormParam( "lastName" ) final String lastName ) { final Person person = peopleService.addPerson( email, firstName, lastName ); return Response.created( uriInfo.getRequestUriBuilder().path( email ).build() ) .entity( person ).build(); } The last example is a bit tricky: the Response class is part of JAX-RS 2.0 API and has no validation constraints defined. As such, imposing any validation rules on the instance of this class will not trigger any violations. But Apache CXF tries its best and performs a simple but useful trick: instead of Response instance, the response’s entity will be validated instead. We can easy verify that by trying to create a person without first and last names set: the expected result should be 500 Internal Server Error. > curl http://localhost:8080/rest/api/people -X POST -id "email=a@b3.com"HTTP/1.1 500 Server Error Date: Wed, 26 Mar 2014 01:13:06 GMT Content-Length: 0 Server: Jetty(9.1.z-SNAPSHOT) And server console output is more verbose: Mar 25, 2014 9:13:06 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.addPerson.<return value>.firstName: may not be null Mar 25, 2014 9:13:06 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.addPerson.<return value>.lastName: may not be null Nice! In this blog post we have just touched a bit the a topic of how Bean Validation 1.1 may make your Apache CXF projects better by providing such a rich and extensible declarative validation support. Definitely give it a try!A complete project is available on GitHub.Reference: Apache CXF 3.0: JAX-RS 2.0 and Bean Validation 1.1 finally together from our JCG partner Andrey Redko at the Andriy Redko {devmind} blog....

Slim Down SWT FormLayout Usage

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));Always on the quest for efficiency I reconsidered the usability of SWT FormLayout lately. Although it is one of my favored core layouts with respect to flexibility, I had to recognize that it is only reluctantly used by most of my fellow workers. Proposing it for an appropriate task sometimes actually seems to inflict real physical pain, considering the facial reactions… Indeed, upon closer examination one have to admit that the usage is at least a bit cumbersome. Not so much the layout itself as the FormData configuration for each control under its reach. The following snippet shows a simple use case that – well, I will not spoil the enjoyment of finding out by yourself what it does:   Label label = new Label( composite, SWT.NONE ); FormData labelData = new FormData(); label.setLayoutData( labelData ); labelData.top = new FormAttachment( 0 ); labelData.right = new FormAttachment( 100 ); labelData.bottom = new FormAttachment( 100 ); labelData.left = new FormAttachment( 0 ); Of course everyone is able to figure out the functionality of the code. But it really has the notion of actually figuring it out – and I guess this is part of the problem. So how about programming this less verbose but nevertheless more expressive in the following way: Label label = new Label( composite, SWT.NONE ); attach( label ).atTop().atRight().atBottom().atLeft(); While it is definitely more compact, expressiveness is, at least to some extend, in the eye of the beholder and depends strongly on the metaphor one have of the task at hand. In my imagination FormLayout basically attachs the control boundaries at certain reference points, i.e. the top side atTop, meaning it always keeps the top side of the control at the upper bound of the parent’s client area. Or it attachs a control atTopTo another control, meaning the control’s upper side is always aligned to the bottom of the other control. Furthermore a side can be attached to a percentage range from the respective client area bound, which all could be expressed like this: attach( control ).atLeftTo( otherControl ).fromTop( 20 ); With this mindset I developed a little utility class I called FormDatas to put the outlined ideas into practice. The class provides a static method attach to create a new instance of FormData, which is registered at the control given as parameter. The layout data instance is returned wrapped by a FormDatas object to enable the fluent interfaces style of the configuration methods1. Additionally there are overloaded method variants to handle e.g. the notion of margin or alignment. The margin is based on the underlying Attachment#offset attribute, but actually respects the side of the attachment. Therefore a margin of 5 atRight corresponds to the offset of -5 of an Attachment that has been assigned to the FormData#right attribute with a numerator of 100: attach( label ).atRight( 5 ); is short for FormData formData = new FormData(); label.setLayoutData( formData ); formData.right = new FormAttachment( 100, -5 ); Alignment is backed by the Attachment#alignment attribute and uses the corresponding SWT constants. To adjust a control’s top attachment to the center of another control for example use the following code: attach( control ).atTopTo( otherControl, MARGIN, SWT.CENTER ); And here is yet another scenario that shows how to work with a width hint instead of opposing side attachments: attach( control ).atTop().atRight().atBottom().withWidth( WIDTH ); It is important to mention that the FormDatas implementation does not cover all possibilities of FormData and FormAttachment. But as I was able to replace all use cases in a current project, I hopefully managed to meet the more common ones. From the IDE point of view the best way to integrate the FormDatas is to configure it as favorite. This way the FormDatas.attach(Control) method is available via content assist that automatically handles static imports and the like.If you want to have a look at FormDatas by yourself there is a GitHub gist containing the implementation. However keep in mind that I did not spent any time on documentation, parameter verification or the like. In this regard the utility is a pretty rough cut version that might evolve over time. https://gist.github.com/fappel/9867945 The gist contains the FormDatas and a JUnit test case, as the implementation is meant to be used in production environment and therfore should be tested.FormDatas#attach(Control) is basically a factory method. Because of this it might look a bit strange returning actually an instance of FormDatas. However introducing a new type just for the sake of the fluent interfaces style also seemed a bit odd to me – so if you have a better idea… ↩Reference: Slim Down SWT FormLayout Usage from our JCG partner Frank Appel at the Code Affine blog....

How not to use Java 8 default methods

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));Warning: you can not make this unseen once you have read I was talking about the multiple inheritance of default methods in the last blog article and how they behave during compilation and run time. This week I look at how to use default methods to do real inheritance, which actually, default methods were not designed for. For this very reason, please read these lines at your own risk, and do not imply that this is a pattern to be followed, just as well do not imply the opposite. What I write here are some coding technics that can be made using Java 8 but their usability is questionable at least for me. I am also a bit afraid to let some ifrit out of the bottle , but on the other hands those ifrits just do not stay there anyway. Some day somebody would let it out. At least I attach the warning sign. Sample problem A few years ago I worked on an application that used a lot of different types of objects that each had a name. After many classes started to contain public String getName(){...} public void setName(String name){...} methods that were just setters and getters the copy paste code smell just filled the room unbearable. Therefore we created a class class HasName { public String getName(){...} public void setName(String name){...} } and each of the classes that had name were just extending this class. Actually it was not working for a long time. There were classes that extended already other classes. In that case we just tried to move the HasName upward in the inheritance line, but in some cases it just did not work. As we went up the line reaching for the top we realized that those classes and their some other descendant do not have a name, why to force them? To be honest, in real life it was bit more complex than just having name. If it were only names, we could live with it having other classes having names. It was something more complex that would just make the topic even more complicated and believe me: it is going to be complex enough. Summary: we could not implement having the name for some of the objects implemented in some spare classes. But now we could do that using default methods. HasName interface with default implementation Default methods just deliver default functionality. A default method can access the this variable, which is always the object that is implementing the interface and on which behalf the method was invoked. If there is an interface I and class C implements the interface, when a method on a C c object is invoked the variable this is actually the object c. How would you implement getName() and setName()? These are setters and getters that accessing a String variable that is in the object. You can not access that from the interface. But it is not absolutely necessary that the value is stored IN the object. The only requirement is that whatever is set for an object the same is get. We can store the value somewhere else, one for each object instance. So we need some value that can be paired to an object and the lifetime of the value has to be the same as the lifetime of the object. Does it ring the bell? It is a weak hash map! Yes, it is. And using that you can easily implement the HasName interface. public interface HasName { class Extensions { private static final WeakHashMap<HasName, String> map = new WeakHashMap<>(); } default void setName(String name) { Extensions.map.put(this, name); } default String getName() { return Extensions.map.get(this); } } All you have to do is write at the end of the list of interfaces the class implements: ,HasName and it magically has. In this example the only value stored is a String. However you can have instead of String any class and you can implement not only setters and getters but any methods that do something with that class. Presumably these implementations will be implemented in the class and the default methods will only delegate. You can have the class somewhere else, or as an inner class inside the interface. Matter of taste and style. Conclusion Interfaces can not have instance fields. Why? Because in that case they were not interfaces but classes. Java does not have multiple implementation inheritance. Perhaps it has but “please don’t use it” kind of. The default method is a technological mistake. You can call it compromise. Something that was needed to retain backward compatibility of JDK libraries when extended with functional methods. Still you can mimic the fields in interfaces using weak hash maps to get access the inherited class “vtable” of fields and methods to delegate to. With this you can do real multiple inheritance. The type that your mother always warned you about. I told you mate! Another warning: the above implementation is NOT thread safe. If you try to use it in multithread environment you may get ConcurrentModificationException or it may even happen that calling get() on a weak hash map gets into infinite loop and never returns. I do not tell how to fix the usage of weak hash maps in this scenario. Or, well, I changed my mind, and I do: use default methods only the they were designed for.Reference: How not to use Java 8 default methods from our JCG partner Peter Verhas at the Java Deep blog....

Java 8 default methods: what can and can not do?

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));What default method is With the release of Java 8 you can modify interfaces adding new methods so that the interface remains compatible with the classes that implement the interface. This is very important in case you develop a library that is going to be used by several programmers from Kiev to New York. Until the dawn of Java 8 if you published an interface in a library you could not add a new method without risking that some application implementing in the interface will break with the new version of the interface. With Java 8 this fear is gone? No. Adding a default method to an interface may render some class unusable. Let’s see first the fine points of the default method. In Java 8 a method can be implemented in an interface. (Static methods can also be implemented in an interface as of Java8, but that is another story.) The method implemented in an interface is called default method and is denoted by the keyword default as a modifier. When a class implements an interface it may, but does not need to implement a method implemented already in the interface. The class inherits the default implementation. This is why you may not need touch a class when an interface it implements changes. Multiple inheritance? The things start to get complicated when a concrete class implements more than one (say two) interfaces and the interfaces implement the same default method. Which default method will the class inherit? The answer is none. In such a case the class has to implement the method itself (directly or by inheritance from a higher class). This is also true when only one of the interfaces implement the default method and the other one only declares it as abstract. Java 8 tries to be disciplined and avoid “implicit” things. If the methods are declared in more than one interfaces then no default implementation is inherited, you get a compile time error. However you can not get a compile time error if you have your class already compiled. This way Java 8 is not consistent. It has its reason, which I do not want to detail here or get into debate for various reasons (e.g.: the release is out, debate time is long over and was never on this platform).Say you have two interfaces, and a class implementing the two interfaces. One of the interfaces implement a default method m(). You compile all the interfaces and the class. You change the interface not containing the method m() to declare it as an abstract method. Compile the modified interface only. Run the class.In this case the class runs. You can not compile it again with the modified interfaces, but if it was compiled with the older version: it still runs. Nowmodify the interface having the abstract method m() and create a default implementation. Compile the modified interface. Run the class: failure.When there are two interfaces providing default implementation for the same method the method can not be invoked in the implementing class unless implemented by the class (again: either directly or inherited from another class).  The class is compatible. It can be loaded with the new interface. It can even start execution so long as long there is no invocation to the method having default implementation in both interfaces. Sample codeTo demonstrate the above I created a test directory for the class C.java and three subdirectories for the interfaces in files I1.java and I2.java. The root directory of the test contains the source code for the class C in file C.java. The directory base contains the interface version that is good for execution and compilation. I1 contains the method m() with default implementation. The interface I2 does not contain any method for now. The class contains a main method so we can execute it in our test. It tests if there is any command line argument so we can easily execute it with and without invoking the method m(). ~/github/test$ cat C.java public class C implements I1, I2 { public static void main(String[] args) { C c = new C(); if( args.length == 0 ){ c.m(); } } } ~/github/test$ cat base/I1.java public interface I1 { default void m(){ System.out.println("hello interface 1"); } } ~/github/test$ cat base/I2.java public interface I2 { } We can compile and run the class using the command lines: ~/github/test$ javac -cp .:base C.java ~/github/test$ java -cp .:base C hello interface 1 The directory compatible contains a version of the interface I2 that declares the method m() abstract, and for technical reasons it contains I1.java unaltered. ~/github/test$ cat compatible/I2.javapublic interface I2 { void m(); } This can not be used to compile the class C: ~/github/test$ javac -cp .:compatible C.java C.java:1: error: C is not abstract and does not override abstract method m() in I2 public class C implements I1, I2 { ^ 1 error The error message is very precise. Even though we have the C.class from the previous compilation and if we compile the interfaces in the directory compatible we will have two interfaces that can still be used to run the class: ~/github/test$ javac compatible/I*.java ~/github/test$ java -cp .:compatible C hello interface 1 The third directory, wrong contains a version of I2 that also defines the method m(): ~/github/test$ cat wrong/I2.java public interface I2 { default void m(){ System.out.println("hello interface 2"); } } We should not even bother to compile it. Even though the method is double defined the class still can be executed so long as long it does not invoke the method, but it fails as soon as we try to invoke the method m(). This is what we use the command line argument for: ~/github/test$ javac wrong/*.java ~/github/test$ java -cp .:wrong C Exception in thread "main" java.lang.IncompatibleClassChangeError: Conflicting default methods: I1.m I2.m at C.m(C.java) at C.main(C.java:5) ~/github/test$ java -cp .:wrong C x ~/github/test$ Conclusion When you start to move your library to Java 8 and you modify your interfaces adding default implementations, you probably will not have problems. At least that is what Java 8 library developers hope adding functional methods to collections. Applications using your library are still relying on Java 7 libraries that do not have default methods. When different libraries are used and modified, there is a slight chance of conflict. What to do to avoid it? Design your library APIs as before. Do not go easy relying on the possibility of default methods. They are last resort. Choose names wisely to avoid collision with other interfaces. We will learn how Java programming will develop using this feature.Reference: Java 8 default methods: what can and can not do? from our JCG partner Peter Verhas at the Java Deep blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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

15,153 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
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.