Featured FREE Whitepapers

What's New Here?

groovy-logo

Simple but powerful DSL using Groovy

In one of my projects we had very complicated domain model, which included more than hundred of different domain object types. It was a pure Java project and, honestly, Java is very verbose with respect to object instantiation, initialization and setting properties. Suddenly, the new requirement to allow users define and use own object models came up. So … the journey begun. We ended up with the idea that some kind of domain language for describing all those object types and relations is required. Here Groovy came on rescue. In this post I would like to demonstrate how powerful and expressive could be simple DSL written using Groovy builders. As always, let’s start with POM file for our sample project:4.0.0com.example dsl 0.0.1-SNAPSHOT jar UTF-8 junit junit 4.10 org.codehaus.groovy groovy-all 1.8.4 org.codehaus.gmaven gmaven-plugin 1.4 1.8 compile testCompile org.apache.maven.plugins maven-compiler-plugin 2.3.1 1.6 1.6I will use the latest Groovy version, 1.8.4. Our domain model will include three classes: Organization, User and Group. Each Organization has a mandatory name, some users and some groups. Each group can have some users as members. Pretty simple, so here are our Java classes. Organization.java package com.example;import java.util.Collection;public class Organization { private String name; private Collection< User > users = new ArrayList< User >(); private Collection< Group > groups = new ArrayList< Group >(); public String getName() { return name; }public void setName( final String name ) { this.name = name; }public Collection< Group > getGroups() { return groups; }public void setGroups( final Collection< Group > groups ) { this.groups = groups; }public Collection< User > getUsers() { return users; }public void setUsers( final Collection< User > users ) { this.users = users; } }User.java package com.example;public class User { private String name;public String getName() { return name; }public void setName( final String name ) { this.name = name; } }Group .java package com.example;import java.util.Collection;public class Group { private String name; private Collection< User > users = new ArrayList< User >();public void setName( final String name ) { this.name = name; }public String getName() { return name; }public Collection< User > getUsers() { return users; }public void setUsers( final Collection< User > users ) { this.users = users; } }Now, we have our domain model. Let think about the way regular user can describe own organization with users, groups and relations between all these objects. Primarily, we taking about some kind of human readable language simple enough for regular user to understand. Meet Groovy builders. package com.example.dsl.samplesclass SampleOrganization { def build() { def builder = new ObjectGraphBuilder( classLoader: SampleOrganization.class.classLoader, classNameResolver: "com.example" )return builder.organization( name: "Sample Organization" ) { users = [ user( id: "john", name: "John" ),user( id: "samanta", name: "Samanta" ),user( id: "tom", name: "Tom" ) ]groups = [ group( id: "administrators", name: "administrators", users: [ john, tom ] ), group( id: "managers", name: "managers", users: [ samanta ] ) ] } } }And here is small test case which verifies that our domain model is as expected: package com.example.dslimport static org.junit.Assert.assertEquals import static org.junit.Assert.assertNotNullimport org.junit.Testimport com.example.dsl.samples.SampleOrganizationclass BuilderTestCase { @Test void 'build organization and verify users, groups' () { def organization = new SampleOrganization().build()assertEquals 3, organization.users.size() assertEquals 2, organization.groups.size() assertEquals "Sample Organization", organization.name } }I am using this simple DSL again and again across many projects. It’s really simplifies a lot complex object models creation. Reference: Simple but powerful DSL using Groovy from our JCG partner Andrey Redko at the Andriy Redko {devmind} blog...
apache-hadoop-logo

The problems in Hadoop – When does it fail to deliver?

Hadoop is a great piece of software. It is not original but that certainly does not take away its glory. It builds on parallel processing, a concept that’s been around for decades. Although conceptually unoriginal, Hadoop shows the power of being free and open (as in beer!) and most of all shows about what usability is all about. It succeeded where most other parallel processing frameworks failed. So, now you know that I’m not a hater. On the contrary, I think Hadoop is amazing. But, it does not justify some blatant failures on the part of Hadoop, may it be architectural, conceptual or even documentation wise. Hadoop’s popularity should not shield it from the need to re-enginer and re-work problems in the Hadoop implementation. The point below are based on months of exploring and hacking around Hadoop. Do dig in.Did I hear someone say “Data Locality”? Hadoop harps over and over again on data locality. In some workshops conducted by Hadoop milkers, they just went on and on about this. They say whenever possible, Hadoop will attempt to start a task on a block of data that is stored locally on that node via HDFS. This sounds like a super feature, doesn’t it? It saves so much of bandwidth without having to transfer TBs of data, right? Hellll, no. It does not. What this means is that first you have to figure out a way of getting data into HDFS, the Hadoop Distributed File System. This is non trivial, unless you live in the last decade and all your data exists as files. Assuming that you do, let’s transfer the TBs of data over to HDFS. Now, it will start doing it’s whole “data locality” thing. Ermm, OK. Am I hit by a wave of brilliance or isn’t it what’s is supposed to do anyway? Let’s get our facts straight. To use Hadoop, our problem should be able to execute in parallel. If the problem or a at least a sub-problem can’t be parallelized it won’t gain much out of Hadoop. This means the task algorithm is independent of any specific part of the data it processes. Further simplifying this would be saying, any task can process any section of the data. So, doesn’t that mean the “data locality” thing is the obvious thing to do? Why, would the Hadoop developers even write some code that would make a task process data in another node unless something goes horribly wrong. The feature would be if it was doing otherwise! If a task has finished operating on the node’s local data and then would transfer data from another node and process this data, that would be a worthy feature of the conundrum. At least that would be worthy of noise. Would you please put everything back into files Do you have nicely structured data in databases? Maybe, you became a bit fancy and used the latest and greatest NoSQL data store? Now let me write down what you are thinking. “OK, let’s get some Hadoop jobs to run on this, cause I want to find all this hidden gold mines in my data, that will get me a front page of Forbes.” I hear you. Let’s get some Hadoop jobs rolling. But wait! What the …..? Why are all the samples in text files. A plethora of examples using CSV files, tab delimited files, space delimited files, and all other kind of neat files. Why is everyone going back a few decades and using files again? Haven’t all these guys heard of DBs and all that fancy stuff. It seems that you were too early an adopter of Data Stores. Files are the heroes of the Hadoop world. If you want to use Hadoop quickly and easily, the best path for you right is to export your data neatly into files and run all those snazzy word count samples (Pun intended!). Because without files Hadoop can’t do all that cool “data locality” shit. Everything has to be in HDFS first. So, what would you do to analyze your data in the hypothetical FUHadoopDB? First of all, implement about 10+ classes necessary to split and transfer data into the Hadoop nodes and run your tasks. Hadoop needs to know how to get data from FUHadoopDB, so let’s assume this is acceptable. Now, if you don’t store it in HDFS, you won’t get the data locality shit. If this is the case, when the task runs, they themselves will have to pull data from the FUHadoopDB to process the data. But, if you want the snazzy data locality shit you need to pull data from FUHadoopDB and store it in HDFS. You will not incur the penalty of pulling data while the tasks are running, but you pay it at the preparation stage of the job, in the form of transferring the data into HDFS. Oh and did I mention the additional disk space you would need to store the same data in HDFS. I wanted to save that disk space, so I chose to make my tasks pull data while running the tasks. The choice is yours. Java is OS independent, isn’t it? Java has its flaws but for the most part it runs smoothly on most OSs. Even if there are some OS issues, it can be ironed out easily. The Hadoop folks have issued document mostly based on Linux environments. They say Windows is supported, but ignored those ignorant people by not providing adequate documentation. Windows didn’t even make it to the recommended production environments. It can be used as a development platform, but then you will have to deploy it on Linux. I’m certainly not a windows fan. But if I write a Java program, I’d bother to make it run on Windows. If not, why the hell are you using Java? Why the trouble of coming up with freaking bytecode? Oh, the sleepless nights of all those good people who came up with byte code and JVMs and what not have gone to waste. CS 201: Object Oriented Programming If you are trying to integrate Hadoop into your platform, think again. Let me take the liberty of typing your thoughts. “Let’s just extend a few interfaces and plugin my authentication mechanism. It should be easy enough. I mean these guys designed the world’s greatest software that will end world hunger.”. I hear you again. If you are planning to do this, don’t. It’s like OOP anti patterns 101 in there. So many places that would say “if (kerberos)” and execute some security specific function. One of my colleagues went through this pain, and finally decided to that it’s easier to write keberos based authentication for his software and then make it work with Hadoop. With great power comes great responsibility. Hadoop fails to fulfil this responsibility. Even with these issues, Hadoop’s popularity seems to be catching significant attention, and its rightfully deserved. Its ability to commodotize big data analytics should be exalted. But it’s my opinion that it got way too popular way too fast. The Hadoop community needs to have another go at revamping this great piece of software. Reference: The problems in Hadoop – When does it fail to deliver? from our JCG partner Mackie Mathew at the dev_religion blog...
software-development-2-logo

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...
software-development-2-logo

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....
software-development-2-logo

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-logo

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-logo

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-logo

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....
spring-logo

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-logo

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....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

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