What's New Here?


15 Tenets For The Software Engineer

Many people talk about the things a software engineer needs to know in order to be successful in their job. Other people talk about the traits needed to be successful. Typically, these posts may read differently but there are many similarities between the two posts. In reality, a software can never really be successful without looking at both types of posts. The list of 15 tenets below is my hope to consolidate the ideas into one handy list for your review.Remember the basics. If you forget the basics of a programming language, you lose your foundational knowledge. That is never a good thing. Always assume the worst case. If you had formal computer science education, you learned about big-O notation. Knowing why an algorithm has no chance of performing well is a good thing. Figuring out why a particular use case seems much slower than others is how you stay successful. Test your code. Ensure you have tests for your code, whether you follow TDD or any other method. Depending on the type of test, you may want to target a different level of coverage, but you should still write as many tests as you can. Do not employ new technologies because they are new, use them because they solve a problem. As technologists, we tend to follow the hot new tools in the hope of finding a silver bullet. Utility is the key, not coolness. Read, a lot. If you are not reading about our industry, you will fall behind and that could have career threatening complications. Try new techniques and technologies, a lot. Yes, I said not to use new technologies just because they are new, but you do need to try new things in order to determine if something new is useful. Also, trying new things helps you learn and keep current in your industry. Fail, you will learn something. At the minimum, you will learn what does not work and you can refine your solutions. In some case, you can even consider the failure a small success. Ship the damn software. Sometimes you just need to get the job done, but you must be aware of technical debt. If you continuously just ship software without removing technical debt, you are well on your way to creating a nightmare when a major production issue arises. Do it the “right way”. Most developers have an idea of the “right way” to implement a design, but that may not always be what project management wants. This is almost a contradiction to the previous “ship the damn software” rule, but there is a balance that needs to be met. Leave the code better than how you found it. Instead of preaching the benefits of refactoring, think of whether you want to maintain the pile of code that keeps getting worse. If you clean it up a little each time you modify it, then it will not be a terrible mess. Think about concurrent access. If you are building a web application, and I don’t mean the scale of Facebook, weird issues may arise under load. Even an application with 100 concurrent users can start to see weird issues when there is concurrent reads and writes on things like HashMaps. This is just the start of the problems as well. Storage may be free, but I/O sucks. You may think that writing everything to disk is a great way to persist data. Generally it is, but if you use disk storage as a temporary storage area, your application could quickly grind to a slow crawl. Physical storage should be limited to that data that needs to persist for long periods of time, or when the data cannot reside in memory. Memory does not go as far as you may think. To start, many people will have their application and database residing on the same server. This is perfectly acceptable until both require a lot of RAM. As an example, you can easily run a Java application in Tomcat in 528MB. However, once you have to deal with scale of any sort and you add in the RAM required by the persistent storage (RDBMS, NoSQL, etc), you can quickly jump to 8GB. Obviously, this is highly dependent upon the number of users hitting the system and how much data you store in memory. Caching fixes everything until it crashes the server. If you are looking for ways to avoid a lot of database queries, you end up using some form of caching. The problem is that caching requires much more memory than your typical application usage, especially when dealing with data that scales with the number of users (see the previous point on memory). The worst problem with caching is that it can chew up so much memory that you run into an OutOfMemory error in java or similar errors in other languages. At that point, your server will either crash or become unresponsive and caching no longer helps because it has become part of the problem. Think like a consultant. As an employee, there tends to be an unwritten rule that the company can do things they would not do with consultants. Deadlines may be moved, scope may be increased, and the developer needs to find a way to meet these new constraints. As an employee, you need to use your power to state that the deadline can not move due to the amount of work required, or that scope cannot be increased without increasing the number of resources. Consultants tend to be allowed to manage a project differently than employees, and it is our job to change that.I know there are a bunch of other ideas that keep running through my head, but this is the best list I can create for now. What other rules would you include for software engineers? Reference: 15 Tenets For The Software Engineer from our JCG partner Rob Diana at the Regular Geek blog...

Shame driven development

I always aspire to write well-crafted code. During my day job, where all production code is paired on, I think our quality is pretty high. But it’s amazing how easy you forgive yourself and slip into bad habits while coding alone. Is shame the driving force behind quality while pairing? We have a number of archaic unit tests written using Easy Mock; all our more recent unit tests use JMock. This little piece of technical debt means that if you’re changing code where the only coverage is Easy Mock tests you first have to decide: do you fix up the tests or, can you hold your nose and live with / tweak the existing test for your purposes? This is not only distracting, but it means doing the right thing can be substantially slower. Changing our Easy Mock tests to JMock is, in principle, a relatively simple task. Easy Mock declares mocks in a simple way: private PricesService prices = createMock(PricesService.class);These can easily be converted into JMock-style: private Mockery context = new Mockery(); ... private final PricesService prices = context.mock(PricesService.class);EasyMock has a slightly different way of declaring expectations: prices.prefetchFor(asset); expect(prices.for(asset)).andReturn( Lists.newListOf("1.45", "34.74"));These need to be translated to JMock expectations: context.checking(new Expectations() {{ allowing(prices).prefetchFor(asset); allowing(prices).for(asset); will(returnValue(Lists.newListOf("1.45", "34.74"))); }});This process is pretty mechanical, so as part of 10% time I started using my scripted refactoring tool – Rescripter – to mechanically translate our EasyMock tests into JMock. Rescripter let’s you run code that modifies your Java source. But this is more than just simple search & replace or regular expressions: by using Eclipse’s powerful syntax tree parsing, you have access to a fully parsed representation of your source file – meaning you can find references to methods, locate method calls, names, parameter lists etc. This is exactly what you need given the nature of the translation from one library to another. This was inevitably fairly exploratory coding. I wasn’t really sure what would be possible and how complex the translation process would eventually become. But I started out with some simple examples, like those above. But, over time, the complexity grew as the many differences between the libraries made me work harder and harder to complete the translation.After a couple of 10% days on this I’d managed to cobble together something awesome: I’d translated a couple of hundred unit tests; but, this was done by 700 lines of the most grotesque code you’ve ever had the misfortune to lay your eyes upon! And then… and then last week, I got a pair partner for the day. He had to share this horror. Having spent 10 minutes explaining the problem to him and then 15 minutes explaining why it was throwaway, one-use code so didn’t have any unit tests. I was embarrassed. We started trying to make some small changes; but without a test framework, it was difficult to be sure what we were doing would work. To make matters worse, we needed to change core functions used in numerous places. This made me nervous, because there was no test coverage – so we couldn’t be certain we wouldn’t break what was already there. Frankly, this was an absolute nightmare. I’m so used to having test coverage and writing tests – the thought of writing code without unit tests brings me out in cold sweats. But, here I was, with a mess of untested code entirely of my own creation. Why? Because I’d forgiven myself for not “doing it right”. After all, it’s only throwaway code, isn’t it? It’s exploratory, more of a spike than production code. Anyway, once its done and the tests migrated this code will be useless – so why make it pretty? I’ll just carry on hacking away… It’s amazing how reasonable it all sounds. Until you realise you’re being a total and utter fucktard. Even if it’s one-use code, even if it has a relatively short shelf-life the only way to go fast, is to go well So I did what any reasonable human being would do. I spent my lunch hour fixing this state of affairs. The end result? I could now write unit tests in Jasmine to verify the refactoring I was writing. Not only could I now properly test drive new code. I could write tests to cover my existing legacy code, so I could refactor it properly. Amazing. And all of a sudden, the pace of progress jumped. Instead of long debug cycles and trying to manually find and trigger test scenarios, I had an easy to run, repeatable, automated test suite that gave me confidence in what I was doing. None of this is new to me: it’s what I do day-in day-out. And yet… and yet… somehow I’d forgiven myself while coding alone. The only conclusion I can draw is that we can’t be trusted to write code of any value alone. The shame of letting another human being see your sorry excuse for code is what drives up quality when pairing: if you’re not pair programming, the code you’re writing must be shameful. References: Shame driven development from our JCG partner David Green at the Actively Lazy blog....

How should REST services be documented?

REST has become the standard way of creating APIs and exposing resources on the internet. Traditional web services (using SOAP and various sets of WS-* standards) are still used a lot within enterprises, but have pretty much disappeared completely from the public API area and are replaced (or deprecated in favor of) REST based APIs. REST based APIs are generally easier to use and get started with the SOAP based services and usually don’t require all kinds of code generation to create the messages and the envelopes. However, one thing that is often missing or overlooked, when creating REST based APIs or services is the documentation part. REST doesn’t have a WSDL that is used to describe to service (see section on WADL further down in the article) and often it is said REST resources should be self-documenting. Even though this is easy to say, it’s generally a good idea to provide additional documentation. In this article I’ll show you what you should document and how you can provide this documentation together with your resource. Lets first look at an example resource. This resource, shown next, represent a report you can make to your local munipality. For instance you notice that a traffic light isn’t functioning, or there is a hole in the road. Your very modern municipality offers a REST based API you can use to report such events. Content-Type: application/vnd.opengov.org.report+json;charset=UTF-8 {"report": { "self": "report-1", "status": "New", "location": "Corner of ninth street", "x-coordinate": 52.34, "y-coordinate": 4.34, "description": "There is ugly graffiti sprayed on the mailbox at the corner on ninth street", "date": "25-11-2010", "time": "15:46" "images": [ {"href": "images/image1.png"}, {"href": "images/image1.png"} ], "related":[ {"href": "../report-4"}, {"href": "../report-7"}, {"href": "../report-9"} ] "links": [ {"relation": "invalidation", "href": "http://localhost:9002/opengov/invalidations/"}, {"relation": "duplication", "href": "http://localhost:9002/opengov/duplications/"} {"relation": "relation", "href": "http://localhost:9002/opengov/relations/"} ] "comments": [] } }REST services are often said to be self-documenting. If you look at this resource you can quickly pretty much already understand what this resource represents. It contains some general information about the resource: "self": "report-1", "status": "New", "location": "Corner of ninth street", "x-coordinate": 52.34, "y-coordinate": 4.34, "description": "There is ugly graffiti sprayed on the mailbox at the corner on ninth street", "date": "25-11-2010", "time": "15:46"Shows where you can find some related resources such as images related to this report: "images": [ {"href": "images/image1.png"}, {"href": "images/image1.png"} ]Or other reports related to this report: "related":[ {"href": "../report-4"}, {"href": "../report-7"}, {"href": "../report-9"} ]Finally from this resource you can also see how you can traverse the links in this resource to report a duplication, invalidate this report or add a related report: "links": [ {"relation": "invalidation", "href": "http://localhost:9002/opengov/invalidations/"}, {"relation": "duplication", "href": "http://localhost:9002/opengov/duplications/"} {"relation": "relation", "href": "http://localhost:9002/opengov/relations/"} ]As you can see this REST resource explains itself pretty well. For instance if we want to add a comment to this report we could just use a PUT with a comment message to the /reports/report-1/comments/ URL . But what does this comment message look like? How can we use the links? For this we do need some additional documentation to make our intent clear to the users of our service. What you should describe are the following items:URLs used to access or search for a report; Links relations that describe how various resources are linked together. Media Types that are used by this service;Let’s make such a description for this service. The first thing we describe is the URL on which this service can be accessed: URLs:http://localhost:9002/opengov/reports?location=xPos,yPos&radius=rSubmit a GET request to this URL to search for Reports. You can optionally specify a location and a radius to only return reports for a specific area. If no location and radius are specified the first 100 reports, sorted by date (newest first), are returned. The reports that are returned have the application/vnd.opengov.org.report+json media type. xPos: x-coordinate of the location. Accepts GPS coordinates. yPos: y-coordinate of the location. Accepts GPS coordinates. r: radius to search for in meters.This piece of documentation describes how to use our search service. We also explicitly define the media-type that this service returns. This way consumers already know how to act with the results from this search service. Another important aspect of the documentation are the links we’ve defined: Links: self: identifies the current resource. This (relative) URL can be used to directly access or modify a report. http://localhost:9002/opengov/invalidations/: This URL can be used to invalidate this resource. Use an HTTP PUT operation on this URL with media type application/vnd.opengov.org.invalidation+json. http://localhost:9002/opengov/duplications/: This URL can be used to mark a report as a duplicate. Use an HTTP PUT operation on this URL with media type application/vnd.opengov.org.duplication+json. http://localhost:9002/opengov/relations/: This URL can be used to relate two reports to each other. Use an HTTP PUT operation on this URL with media type application/vnd.opengov.org.invalidation+json.Here we describe what a specific link implies, how to use it, and what kind of media-types this link expects. That leaves us with describing the resources themselves. If you’re doing REST with XML, you should describe the message using an XSD. If you’re doing JSON you could use JSON-Schema, but I prefer to just describe the fields per media-type. Media types: application/vnd.opengov.org.report+json - status: The status of this report - location: Readable description of the location of this report - etc.If there are any restrictions on these values, this is a good place to describe them. Remember, we write this documentation for human consumption, we don’t require it to be parsable. With the items described above, you’ve got a very good starting point for creating documentation for REST services. What you should keep in mind are the following items:Follow the basic REST principles for the HTTP PUT, GET, DELETE and POST operations. Use href/links when linking to other resources. It doesn’t really matter if you use relative links or absolute links for this, although relative links are more flexible should you relocate your resource. Use media types to inform your consumer the type of resource they are dealing with. Use links with a specific relation property to tell your consumers what you can do with this resource. Add a simple description of the URLs, media types and links that are supported by your service.Since I expect someone coming with this question, I’ll answer it beforehand. Why not use a WADL to describe your REST API? A couple of reasons:A WADL focusses more on machine-to-machine communication. REST services are more often created to be explored through human interaction. Not by generating a client stub WADL is a good concept but leans to much towards WSDLs. WSDLs are often used to create RPC based services that hide the underlying protocol. REST APIs are used in a different manner where this approach doesn’t fit that well. An old article, but explains the why/why not of a WADL pretty well: http://bitworking.org/news/193/Do-we-need-WADLReference: How should REST services be documented? from our JCG partner Jos Dirksen at the Smart Java blog....

Git Tutorial – Getting Started

I was a long time Subversion user then. So, when I got introduced to Git few months back, I was *really* confused. First of all, I couldn’t visualize some of the concepts that Git talked about. But then, as I started using Git in my day-to-day work, it got much easy to use and understand. Now there isn’t a single day (except some of the weekends!) in which I don’ t use a single Git command. It became an inseparable tool at my work. So, just thought of writing my learning as a Git tutorial series to help a bit my fellow developers who want to switch over to Git. Let’ start. Say Hello to Git First of all, if you are coming from a Subversion/CVS background – mark my words – forget everything you learned about version controlling. Because Git has a completely different approach to version controlling. Lets see how it differs from other systems. Git is distributed. Which means, when you clone a Git repo, you’ll get a your own copy of that repo to work with in your local machine. In Git, you get your own code base, you make changes, commit as many times as you want without the fear of polluting the central repo and once you are confident push the code to central repository. Before diving too much further, let’s look at this awesome diagram which explains the Git workflow (thanks to osteele.com, I have a printout of this pasted at my desk).As you can see in the above diagram, in Git, code lives in 4 different placesremote repository - think of it as a Github repository or a remote server hosted in your company. As the name suggests, this code base does not live your local machine and You don’t talk with remote repository often. Only when you pull a code initially and pushing the changes when you are done with it. local repository – when you clone a remote Git repo / or create a new repo, the code base is created here in the local repository. All commits you do will come here first. This lives in your local machine. index - one of the most confusing thing you’ll ever hear in Git. This is something like a intermediate place between your working copy of code and your local repository. It’s like a staging area for your code. You use it to stage which files you want to track & commit. In my next post about My Git workflow you’ll see how index is used. This code base too, lives in your local machine. workspace - it’s your working directory where you create/edit/delete your files. This code resides in your local machine.Hope you get the basic concepts of Git. It is very important to understand it well before you start using Git. In my next post, I’ll be writing about my Git workflow. Till then, feel free to setup your Git environment. Reference: Git Tutorial – Getting Started from our JCG partner Veera Sundar at the Veera Sundar blog....

Java: Faking a closure with a factory to create a domain object

Recently we wanted to create a domain object which needed to have an external dependency in order to do a calculation and we wanted to be able to stub out that dependency in our tests. Originally we were just new’ing up the dependency inside the domain class but that makes it impossible to control it’s value in a test. Equally it didn’t seem like we should be passing that dependency into the constructor of the domain object since it’s not a piece of state which defines the object, just something that it uses. We ended up with something similar to the following code where we have our domain object as an inner class: public class FooFactory { private final RandomService randomService; public FooFactory(RandomService randomService) { this.randomService = randomService; } public Foo createFoo(String bar, int baz) { return new Foo(bar, baz); } class Foo { private String bar; private int baz; public Foo(String bar, int baz) { this.bar = bar; this.baz = baz; } public int awesomeStuff() { int random = randomService.random(bar, baz); return random * 3; } } }A test on that code could then read like this: public class FooFactoryTest { @Test public void createsAFoo() { RandomService randomService = mock(RandomService.class); when(randomService.random("bar", 12)).thenReturn(13); FooFactory.Foo foo = new FooFactory(randomService).createFoo("bar", 12); assertThat(foo.awesomeStuff(), equalTo(39)); } }It’s a bit of a verbose way of getting around the problem but it seems to work reasonably well. Reference: Java: Faking a closure with a factory to create a domain object from our JCG partner Markh Needham at the Mark Needham Blog....

Android – Load WebView with ProgressBar

Problem: How to load WebView with ProgressBar? Description: Previously, i have published an article for Android – WebViewClient example where we have discussed about how to load URL inside the application instead of opening a native browser. Now, just consider the case where we want to include progress bar to show loading process. At the same time we can either show ProgressDialog or include ProgressBar inside the XML layout. - If we include ProgressBar then we have to make it INVISIBLE or GONE whenever page loading is finished - And if we display ProgressDialog then we have to dismiss it whenever page loading is finished. So in this tutorial, we are going to display ProgressBar. Just check the snap-2 where ProgressBar is invisible as we have made it invisible. Output:Note: Before implementing this solution, make sure you have added INTERNET permission in your AndroidManifest.xml file. <uses-permission android:name="android.permission.INTERNET"> </uses-permission>Solution: WebViewClientDemoActivity.java package com.paresh.webviewclientdemo;import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar;/* * Demo of creating an application to open any URL inside the application and clicking on any link from that URl should not open Native browser but that URL should open in the same screen.- Load WebView with progress bar */ public class WebViewClientDemoActivity extends Activity { /** Called when the activity is first created. */WebView web; ProgressBar progressBar;@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);web = (WebView) findViewById(R.id.webview01); progressBar = (ProgressBar) findViewById(R.id.progressBar1);web.setWebViewClient(new myWebClient()); web.getSettings().setJavaScriptEnabled(true); web.loadUrl("http://www.technotalkative.com"); }public class myWebClient extends WebViewClient { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); }@Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stubview.loadUrl(url); return true;}@Override public void onPageFinished(WebView view, String url) { // TODO Auto-generated method stub super.onPageFinished(view, url);progressBar.setVisibility(View.GONE); } }// To handle "Back" key press event for WebView to go back to previous screen. @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) { web.goBack(); return true; } return super.onKeyDown(keyCode, event); } }main.xml <!--?xml version="1.0" encoding="utf-8"?--> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"><textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="This is the demo of WebView Client" android:textsize="20sp" android:gravity="center_horizontal"> </textview><progressbar android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" android:id="@+id/progressBar1"><webview android:id="@+id/webview01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_weight="1"> </webview> </progressbar></linearlayout>Download Full source code from here: Android – Load WebView with ProgressBar. Feedback and reviews are always welcome. Please Reference: Android – Load WebView with ProgressBar from our JCG partner Paresh N. Mayani at the TechnoTalkative blog....

Isn’t Java a Civilised Language?

A few weeks ago I was given the opportunity to learn iOS programming. My boss decided that I was more of a ‘computer scientist’ rather than a developer, and this meant that I could apply my knowledge to developing an iPad application or two – all I’d need to do was to learn Objective-C and the iOS SDK: after all, how hard can it be? Although I’ve done lots of C/C++ in the past, I’ve been doing Java since 2001, so I’d virtually forgotten much of what I knew, and besides, Objective-C isn’t much like C++ anyway. The result is that you feel like you’ve washed up on a foreign shore unable to speak the language and you’re armed with nothing more than a sun tan and a dictionary. In learning all this new stuff, I came to realise that Java is a VERY good language and the reason is, firstly and foremost, because you don’t have to think about memory allocation and deallocation, you can just get on with writing your application. In writing iOS applications in Objective-C, you have to both allocate memory for your objects and then clear up after yourself, returning your object’s memory back to the free-pool. This seems very old school for the second decade of the 21st century. Furthermore, having allocated memory for an object, you have to keep track of the number of references there are to it – a practice known as reference counting, something I first came across in my previous life as a C++ programmer. The fundamental idea here is that every time you create a new reference to an object, you increment the reference counter and when you’ve finished with the object reference you decrement its reference counter. When the counter reaches zero, the the system releases the memory back to the free pool. In Objective-C, the function to decrement the reference count is called release; hence if Java had reference counting and if I wanted to, for example, ask an AddressService to find me an address, I’d need to do something like this: // create an object and set the reference count to 1 AddressService addressService = new AddressService(); // Use the object Address address = addressService.findAddress(id); // pass it to a method model.addAttribute("address", address); // free the memory addressService.release();That’s the simple scenario, but what happens if some method or other passes you an object reference as a method argument? In that case you have to decide how you’re going to hang on to it and there seem to be two ways of doing this. The first is to make a copy of the object and the second is to increment its reference count. Making a copy is probably the safest idea, but consumes more memory and will be slower, whilst incrementing the reference count is quick but not as safe as some other part of the program may get the reference counting wrong and decrement the count one too many times, which means that you’ve got a reference to some memory that may have been released, and when you try to access your released object your program will crash…. Again, if Java had reference counting then a Spring Controller request handler method would look something like this: @RequestMapping(value = "/find", method = RequestMethod.GET) public String findAddress(@RequestParam("id") int id, Model model) { // increment the reference count - 'retain' is the Objective-C method for doing this. model.retain();// create a new string object - with reference count of one String msg = new String().withFormat("Processing an address page request for address with id: " + id); // pass the string to the logger logger.info(msg); // release the string's memory msg.release();AddressService addressService = new AddressService(); Address address = addressService.findAddress(id); model.addAttribute("address", address); addressService.release();// finished with the model model.release(); return "address-display"; }There are a couple of points to note here – firstly, the handler method is passed a model object, so I increment the reference count by calling retain and then call release on the model when I’m finished with it at the end of the method. Secondly, even when creating trivial objects, like a message string that’s passed to a logger, you have to apply the reference counting rules and free the memory once you’ve finished with it. The example below demonstrates the alternative to incrementing the reference count: making your own copy of an object… @RequestMapping(value = "/find", method = RequestMethod.GET) public String findAddress(@RequestParam("id") int id, Model model) { // increment the reference count - 'retain' is the Objective-C method for doing this. Model myModel = model.copy();// As previous example // finished with the model myModel.release(); return "address-display"; }These examples are only trivial, there’s a whole bunch of reference counting rules that you need to apply and if you get it wrong then Ka-Bam your program crashes and getting it wrong means either you try to access memory that’s already been freed, or slowly die due to a memory leak because you’ve forgotten to release some memory. Although I guess that the key point here is ownership: if you own an object, increment it’s reference count, when you’re finished with an object then decrement its reference count. The code above is just a bit of scribble written to illustrate the point – it won’t compile. The code was actually taken from my Address sample on GitHub and in real life looks like this: @RequestMapping(value = "/find", method = RequestMethod.GET) public String findAddress(@RequestParam("id") int id, Model model) {logger.info("Processing an address page request for address with id: " + id);Address address = addressService.findAddress(id); model.addAttribute("address", address);return "address-display"; }…much smaller neater and more understandable. One last point, some of you will have noticed that in the reference counting example, I allocate (Objective-C word) a new AddressService - this is because iOS programming has nothing like dependency injection or a Spring framework, so you’re back to creating objects for yourself. (Note to the Guys at Spring: ‘Spring iOS’ – sounds like an idea to me…) Those of you in the know will highlight the fact that Apple recently introduced something called ‘Automatic Reference Counting’. Whilst it isn’t garbage collection, it’s simplifies things in that iOS will now automatically keep track of your pointer references and free memory for you when the count reaches zero, which means that you don’t have to bother calling the retain and release methods. Also, this blog isn’t trying to denigrate Objective-C – I quite like Objective-C. Its syntax seems rather arcane and feels verbose when compared to Java, but it forces you to be more disciplined in your programming technique, so if like me you believe that good programming is down to ‘clarity of thought’, then when writing an Objective-C program you have to think a little bit more clearly, and that I really like. I also guess that a lot of readers might come up with a whole bunch of reasons as to why they think Java is a terrible language, and why their preferred language ‘does it better’, whatever it might be, so I’m looking forward to your comments… Finally, I’m just a ‘newbie’ when it comes to iOS programming, so if any iOS/Objective-C masters come across this blog – please let me know where I’m wrong. Reference: Isn’t Java a Civilised Language? from our JCG partner Roger Hughes at the Captain Debug’s Blog ....

Spring MVC and JQuery for Ajax Form Validation

In this tutorial, we will see how to validate a form on server side using Ajax with Spring MVC and JQuery. Spring MVC provides a very convenient process for adoption of Ajax with annotation driven configuration. We will use this annotation driven configuration to send Ajax response in form of JSON data. The response will contain state of the form validation and error messages in any error exist in form data.Tools Used:Spring MVC 3.0.3 JQuery 1.4.2 Jackson 1.5.3In the example, we will add users with name and education to a list using Ajax and Spring MVC. The user data will be send to Spring MVC controller with the help of JQuery and the controller will return the full list of users added till time if there is no validation error in form data or the controller will return validation errors if they present in form data. So, we will learn two important things in this tutorial:How to validate form data using Ajax in Spring MVC with the help of JQuery? and how send back list of objects to Ajax call as response ?Domain Class for User Following is our User domain class that will hold the form data:package com.raistudies.domain;public class User {private String name = null; private String education = null;public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEducation() { return education; } public void setEducation(String education) { this.education = education; } }There are two fields in our User domain object name and education. Ajax response domain class for sending JSON response Following is the domain object that will we use to send response: package com.raistudies.domain;public class JsonResponse { private String status = null; private Object result = null; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; }}It contain two properties, “status” and “result”. “status” field is of type String and will contain “FAIL” or “SUCCESS”. “result” will contain the other data that are to be send back to the browser. UserController.java package com.raistudies.controllers;import java.util.ArrayList; import java.util.List;import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.ValidationUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;import com.raistudies.domain.JsonResponse; import com.raistudies.domain.User;@Controller public class UserController { private List<User> userList = new ArrayList<User>();@RequestMapping(value="/AddUser.htm",method=RequestMethod.GET) public String showForm(){ return "AddUser"; }@RequestMapping(value="/AddUser.htm",method=RequestMethod.POST) public @ResponseBody JsonResponse addUser(@ModelAttribute(value="user") User user, BindingResult result ){ JsonResponse res = new JsonResponse(); ValidationUtils.rejectIfEmpty(result, "name", "Name can not be empty."); ValidationUtils.rejectIfEmpty(result, "education", "Educatioan not be empty"); if(!result.hasErrors()){ userList.add(user); res.setStatus("SUCCESS"); res.setResult(userList); }else{ res.setStatus("FAIL"); res.setResult(result.getAllErrors()); }return res; }}showForm() is used to shoe the Add user form to browser. method addUser() is will handle the ajax request and validate the User object and if there is no validation error in form data it will set the userList object to result property of JsonResponse class with status as “SUCCESS“. But, if there are errors in form data it will extract list of errors from BindingResult object using getAllErrors() method and set to result property of JsonResponse class with status as “FAIL“. AddUser.jsp Following is the jsp page that calls the UserController using Ajax with the help of JQuery:<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Add Users using ajax</title> <script src="<%=request.getContextPath() %>/js/jquery.js"></script> <script type="text/javascript"> var contexPath = "<%=request.getContextPath() %>"; </script> <script src="<%=request.getContextPath() %>/js/user.js"></script> <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/style/app.css"> </head> <body> <h1>Add Users using Ajax ........</h1> <table> <tr><td colspan="2"><div id="error" class="error"></div></td></tr> <tr><td>Enter your name : </td><td> <input type="text" id="name"><br/></td></tr> <tr><td>Education : </td><td> <input type="text" id="education"><br/></td></tr> <tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr> <tr><td colspan="2"><div id="info" class="success"></div></td></tr> </table> </body> </html>The jsp page includes a js file user.js that has been used for holding the definition of the JavaScript method doAjaxPost() which produces the ajax class and also use the response of the Ajax call to dynamically update the page data. user.js Following is the code for ajax class and interpreting the response received from Spring MVC controller: function doAjaxPost() { // get the form values var name = $('#name').val(); var education = $('#education').val();$.ajax({ type: "POST", url: contexPath + "/AddUser.htm", data: "name=" + name + "&education=" + education, success: function(response){ // we have the response if(response.status == "SUCCESS"){ userInfo = "<ol>"; for(i =0 ; i < response.result.length ; i++){ userInfo += "<br><li><b>Name</b> : " + response.result[i].name + ";<b> Education</b> : " + response.result[i].education; } userInfo += "</ol>"; $('#info').html("User has been added to the list successfully. " + userInfo); $('#name').val(''); $('#education').val(''); $('#error').hide('slow'); $('#info').show('slow'); }else{ errorInfo = ""; for(i =0 ; i < response.result.length ; i++){ errorInfo += "<br>" + (i + 1) +". " + response.result[i].code; } $('#error').html("Please correct following errors: " + errorInfo); $('#info').hide('slow'); $('#error').show('slow'); } }, error: function(e){ alert('Error: ' + e); } }); }$.ajax() method of JQuery has been used for making an Ajax call here which sends the form data name and education field values to Spring Controller. On success of the Ajax call, it first checks the status field of the response. Note that, the response object here is the JSON representation of the JsonResponse java object. If the status field of the response is “SUCCESS” then it iterates through the user list using the notation response.result[i] , note that the list object of java is converted to json array by Jackson library. If the status is “FAIL” the the result object will contain the validation errors which we can access using the notation response.result[i].code , here the code will return error message added in Spring controller. While running the example in tomcat 6 server, it will open following form :Ajax Validation FormJust click on the “Add Users” button without entering any value, it will show errors for the field as shown in the bellow image:Ajax Validation Show Error in PageNow enter any name and education and click on the “Add Users” button. It will add the user detail to list and also show the info of the whole user list on the page :Ajax Validation with Spring MVC and JQuery Success PageYou can also try the example by downloading the example from bellow links: Source: Download Source + Lib :Download Reference: Ajax Form Validation using Spring MVC and JQuery from our JCG partner Rahul Mondal at the Rai Studies blog....

Spring and Quartz: Multi-Job Scheduling Service

Job Scheduling is so important requirement for the applications. Especially in large-scale projects, working with a lot of jobs can be a problem. Spring and Quartz have brought significant benefits for the solution of this problem. This article shows how to schedule multi jobs easily by using Spring and Quartz. Used Technologies : JDK 1.6.0_21 Spring 3.1.1 Quartz 1.8.5 Maven 3.0.2 STEP 1 : CREATE MAVEN PROJECT A maven project is created as below. (It can be created by using Maven or IDE Plug-in)STEP 2 : LIBRARIES Spring dependencies are added to Maven’ s pom.xml. <!-- Spring 3 dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency>STEP 3 : CREATE TASK CLASSES A FirstTask Class is created. package com.otv.task; import org.apache.log4j.Logger; /** * First Task * * @author onlinetechvision.com * @since 24 Feb 2012 * @version 1.0.0 * */ public class FirstTask { private static Logger log = Logger.getLogger(FirstTask.class); /** * Execute this task * */ public void execute() { log.debug("FirstTask runs successfully..."); } }A SecondTask Class is created. package com.otv.task; import org.apache.log4j.Logger; /** * Second Task * * @author onlinetechvision.com * @since 24 Feb 2012 * @version 1.0.0 * */ public class SecondTask { private static Logger log = Logger.getLogger(SecondTask.class); /** * Execute this task * */ public void execute() { log.debug("SecondTask runs successfully..."); } }STEP 4 : CREATE ISchedulerService INTERFACE ISchedulerService Interface is created. package com.otv.service; /** * Scheduler Service Interface * * @author onlinetechvision.com * @since 24 Feb 2012 * @version 1.0.0 * */ public interface ISchedulerService { /** * Execute First Task * * @param * @throws * @return */ public void executeFirstTask(); /** * Execute Second Task * * @param * @throws * @return */ public void executeSecondTask(); }STEP 5 : CREATE SchedulerService CLASS SchedulerService Class is created by implementing ISchedulerService Interface. This service schedules tasks. package com.otv.service; import com.otv.task.FirstTask; import com.otv.task.SecondTask; /** * Scheduler Service Implementation * * @author onlinetechvision.com * @since 24 Feb 2012 * @version 1.0.0 * */ public class SchedulerService implements ISchedulerService { private FirstTask firstTask; private SecondTask secondTask; /** * Execute First Task * */ public void executeFirstTask() { getFirstTask().execute(); } /** * Execute Second Task * */ public void executeSecondTask() { getSecondTask().execute(); } /** * Get First Task * * @return FirstTask */ public FirstTask getFirstTask() { return firstTask; } /** * Set First Task * * @param firstTask First Task */ public void setFirstTask(FirstTask firstTask) { this.firstTask = firstTask; } /** * Get Second Task * * @return SecondTask */ public SecondTask getSecondTask() { return secondTask; } /** * Set Second Task * * @param secondTask Second Task */ public void setSecondTask(SecondTask secondTask) { this.secondTask = secondTask; } }STEP 6 : CREATE Application CLASS Application Class is created. This class runs the application. package com.otv.starter; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Application Starter Class * * @author onlinetechvision.com * @since 24 Feb 2012 * @version 1.0.0 * */ public class Application { /** * Main method of the Application * */ public static void main(String[] args) { new ClassPathXmlApplicationContext("applicationContext.xml"); } }STEP 7 : DEFINE Job Detail CONFIGURATIONS Job Details can be defined via two ways in Spring. By using MethodInvokingJobDetailFactoryBean or by extending QuartzJobBean. In this example, MethodInvokingJobDetailFactoryBean method has been used. targetObject and targetMethod properties are given to MethodInvokingJobDetailFactoryBean. <!-- Job Details--> <bean id="FirstTaskJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="SchedulerService" /> <property name="targetMethod" value="executeFirstTask" /> </bean> <bean id="SecondTaskJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="SchedulerService" /> <property name="targetMethod" value="executeSecondTask" /> </bean>STEP 8 : DEFINE Trigger CONFIGURATIONS Triggers can also be defined via two ways in Spring. By defining SimpleTriggerBean or CronTriggerBean . When SimpleTriggerBean is used, jobDetail, repeatInterval and startDelay properties are defined. When CronTriggerBean is used, jobDetail and cronExpression properties are defined. In this example, repeat interval of first task has been set 5 secs and repeat interval of second task has been set 12 secs . <!-- Simple Trigger --> <bean id="FirstSimpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">     <property name="jobDetail" ref="FirstTaskJobDetail" />     <property name="repeatInterval" value="5000" />     <property name="startDelay" value="1000" /> </bean>   <!-- <bean id="SecondSimpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">         <property name="jobDetail" ref="SecondTaskJobDetail" />         <property name="repeatInterval" value="12000" />         <property name="startDelay" value="1000" />     </bean> -->      <!-- Cron Trigger --> <bean id="SecondSimpleTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">     <property name="jobDetail" ref="SecondTaskJobDetail" />     <property name="cronExpression" value="0/12 * * * * ?" /> </bean>STEP 9 : DEFINE SchedulerFactoryBean CONFIGURATION Finally, Job Details and Triggers are configured by creating SchedulerFactoryBean. <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="jobDetails"> <list> <ref bean="FirstTaskJobDetail" /> <ref bean="SecondTaskJobDetail" /> </list> </property> <property name="triggers"> <list> <ref bean="FirstSimpleTrigger" /> <ref bean="SecondSimpleTrigger" /> </list> </property> </bean>STEP 10 : CREATE applicationContext.xml All applicationContext.xml content is shown as below. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Beans Declaration --> <bean id="FirstTask" class="com.otv.task.FirstTask"></bean> <bean id="SecondTask" class="com.otv.task.SecondTask"></bean> <bean id="SchedulerService" class="com.otv.service.SchedulerService"> <property name="firstTask" ref="FirstTask" /> <property name="secondTask" ref="SecondTask" /> </bean> <!-- Job Details--> <bean id="FirstTaskJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="SchedulerService" /> <property name="targetMethod" value="executeFirstTask" /> </bean> <bean id="SecondTaskJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="SchedulerService" /> <property name="targetMethod" value="executeSecondTask" /> </bean> <!-- Simple Trigger --> <bean id="FirstSimpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="FirstTaskJobDetail" /> <property name="repeatInterval" value="5000" /> <property name="startDelay" value="1000" /> </bean> <!-- <bean id="SecondSimpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="SecondTaskJobDetail" /> <property name="repeatInterval" value="12000" /> <property name="startDelay" value="1000" /> </bean> --> <!-- Cron Trigger --> <bean id="SecondSimpleTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="SecondTaskJobDetail" /> <property name="cronExpression" value="0/12 * * * * ?" /> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="jobDetails"> <list> <ref bean="FirstTaskJobDetail" /> <ref bean="SecondTaskJobDetail" /> </list> </property> <property name="triggers"> <list> <ref bean="FirstSimpleTrigger" /> <ref bean="SecondSimpleTrigger" /> </list> </property> </bean> </beans>STEP 11 : RUN PROJECT After Application Class is started, below output logs will be shown : 25.02.2012 00:17:18 DEBUG (FirstTask.java:23) - FirstTask runs successfully... 25.02.2012 00:17:23 DEBUG (FirstTask.java:23) - FirstTask runs successfully... 25.02.2012 00:17:24 DEBUG (SecondTask.java:22) - SecondTask runs successfully... 25.02.2012 00:17:28 DEBUG (FirstTask.java:23) - FirstTask runs successfully... 25.02.2012 00:17:33 DEBUG (FirstTask.java:23) - FirstTask runs successfully... 25.02.2012 00:17:36 DEBUG (SecondTask.java:22) - SecondTask runs successfully... 25.02.2012 00:17:38 DEBUG (FirstTask.java:23) - FirstTask runs successfully... 25.02.2012 00:17:43 DEBUG (FirstTask.java:23) - FirstTask runs successfully... 25.02.2012 00:17:48 DEBUG (SecondTask.java:22) - SecondTask runs successfully... 25.02.2012 00:17:48 DEBUG (FirstTask.java:23) - FirstTask runs successfully... 25.02.2012 00:17:53 DEBUG (FirstTask.java:23) - FirstTask runs successfully... 25.02.2012 00:17:58 DEBUG (FirstTask.java:23) - FirstTask runs successfully... 25.02.2012 00:18:00 DEBUG (SecondTask.java:22) - SecondTask runs successfully...STEP 12 : DOWNLOAD OTV_SpringQuartz_MultiJobScheduling Reference: Multi-Job Scheduling Service by using Spring and Quartz from our JCG partner Eren Avsarogullari at the Online Technology Vision blog....

Customized Internationalization (i18n) in Java

Internationalization (i18n) is very important in our software projects. It brings mainly these benefits:Externalizing UI strings into external files other than code files and so easy-to-manage UI content. Supporting multiple languages.In this post, a brief practical example of i18n will be given for Eclipse and Java projects, including customizing i18n mechanism to have more maintainable and encapsulated approach.First, we must have some classes which includes string values shown on user interface:An example UI classThen we must have an instance of an i18n utility class. This is generally one of the two in Java:java.util.ResourceBundle (doesn’t need spring dependency)ResourceBundle initializationorg.springframework.context.support.ResourceBundleMessageSource (has multiple word externalization capability (which will be told later)).ResourceBundleMessageSource initializationWe’ll use ResourceBundleMessageSource instance in this tutorial because of its extended capabilities.Then right click on the class and choose Source –> Externalize Strings. A window as below will be shown. Enter keys for strings into the right column. Keys will be started with class name as default. Keys must be unique on the system, so a predefined pattern should be applied (e.g. <class_name>.<type_id>.<description>)Eclipse string externalization windowClick Next–> Finish and your strings will be changed as follows. And also Messages class and externalizer properties file will be created automatically (auto-comments on the right are markers for eclipse which means “externalized”):Class with externalized stringsAuto-created i18n utility and property classesNow externalization is complete. But we want i18n, and we must support multiple languages. For this, define another properties file with location post-tag (e.g. “EN”, “FR”, “TR”, …), copy keys and fill values with new language and set locale of resource bundle in a proper place/action of your application (e.g. on settings window or login page):Multiple property files for each languageMessages_tr_TR.properties file contentSetting new locale to the resource bundleAs the last step, we want to encapsulate i18n utility class and also want to use a more  capable i18n utility (e.g. ResourceBundleMessageSource). For this, define a class as below:Customized and encapsulated message source (i18n utility) classFinally, change “Messages.getString” statements into your new instance:Class with externalized strings (with customized i18n utility class)You can also externalize parameterized strings using your class. Its usage will be as follows:Getting a parameterized string from i18n utilityDefining a parameterized string in property fileReference: Customized Internationalization (i18n) in Java – Step by Step from our JCG partner Cagdas Basaraner at the CodeBuild 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