jueves, noviembre 10, 2011
Fear of the dark, fear of the dark I have a phobia that someone's always there (Fear of the Dark - Iron Maiden)
Etiquetas: GAE, Google App Engine, json, maven, maven gae, maven-datanucleus-plugin, maven-gae-plugin, spring mvc, spring MVC rest
lunes, noviembre 07, 2011
I en una paret al fons imprès en blanc i negre hi havia un pòster d'en Godard. Potser ell em podria dir-me perquè em ballava el cap. (Jean Luc - Els Amics de les Arts)
So final class will look like:
And previous factory can be instantiated with Spring and injecting delimiter, using Spring Expression module.
See that thanks of Spring Expression delimiter is injected directly into class.
I think it is not difficult to implement an application that can read Localized Comma-Separated Values files, and can avoid having problems when application is distributed around the world.
Full Code: https://github.com/downloads/maggandalf/Blog-Examples/csv.zip
Music: http://www.youtube.com/watch?v=A3Yl3Fsj7tw&feature=related
Etiquetas: comma-separated values, csv, DecimalFormatSymbols, i18n, internationalization, JavaCSV, l10n, localization
miércoles, noviembre 02, 2011
En ti puedo ver la libertad, Tu me haces sentir que puedo volar, Y se que aquí es mi lugar, Y se que a ti yo quiero amar (Cuando Me Miras Asi - Cristian Castro)
From ServiceLoader javadoc: A service is a well-known set of interfaces and classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself.
Since JDK 6, a simple service-provider loading facility is implemented. As is suggested it is simple, you cannot understand that implementation as a complex system for implementing plugins for your application, but can help you in many situations where you want implementations of a service could be discovered by other module automatically.
What I really like about using JDK Services is that your services do not have any dependency to any class. Moreover for registering a new implementation of a service, you just have to put jar file into classpath and nothing more.
Now I will explain the service we are going to implement, and then I will show you how to code it.
We want to implement a system that depending on kind of structured input (comma-separated value, tab-separated value, ...) returns a String[] of each value; so for example you can receive input a,b,c,d or 1<tab>2<tab>3<tab>4 and the system should return an array with [a, b, c, d] or [1, 2, 3, 4].
So our system will have three Java projects.
One defining service contract (an interface) and, because of teaching purpose, a main class where internet media type, for example text/csv, is received with input data. Then using a factory class that I have created, it will ask which registered service can transform input to String[].
And two projects each one implementing a service following defined contract, one for comma-separated values and another one for tab-separated values.
Let's see the code:
Main project (reader) is composed by an interface, a main class and a factory class.
The most important part is Decode interface which defines service contract.
Two operations are defined, one that returns if service supports given input, and another that transforms data to String[].
DecodeFactory class is responsible for finding an implementation service that supports required encoding. In fact, this class encapsulates java.util.ServiceLoader calls. ServiceLoader class is in charge of load registered services.
At line 3 we are loading all services that are registered in classpath. At line 7 we only iterate through all services asking if given encoding name is supported.
And finally main class.
And now if you run this class with java -jar reader.jar "text/cvs" "a, b, c, d", an UnsupportedEncodingException will be thrown. Now we are going to implement our first service. Note that reader project will not be modified nor recompiled.
First service we are going to implement is one that can support comma-separated values encoding. Only one class and one file are important.
CSV class is an implementation of Decode interface and transforms comma-separated values.
As you can see a simple StringTokenizer class. Only take care that this class is Locale sensitive, countries where comma (,) is used as decimal delimiter, separation character is semicolon (;).
And next important file is a file that is placed into META-INF. This file contains a pointer to service implementation class.
This file should be in META-INF/services and should be called as interface full qualified name. In this case org.alexsotob.reader.Decode. And its content should be service implementation full qualified name.
And now you can package this project, and you can reexecute reader project but with generated jar (csv.jar) into classpath. And now output will be an array with a, b, c and d characters instead of unsupported exception.
See that reader project has not been modified and its behaviour has been changed. Now you can develop new implementations for decoding new inputs, and you should only take care of copying them into classpath.
Only take care that all services should have a default constructor with no arguments.
And for those who use Spring Framework, Services are also supported through three different FactoryBeans, ServiceFactoryBean, ServiceListFactoryBean, ServiceLoaderFactoryBean.
Download Comma-Separated Values Service Project: https://github.com/downloads/maggandalf/Blog-Examples/csvDec.zip
Download Tab-Separated Values Service Project: https://github.com/downloads/maggandalf/Blog-Examples/tsvDec.zip
martes, octubre 25, 2011
Soy el rey de la mar tiburón Que te come a besos Pero yo soy el rey del mar tiburón El que te come mi amor (El Rey Tiburón - Maná))
"Injecting mock beans into spring context for testing. What I want to be able to do is via the HotswappableTargetSource override the bean definitions of select beans in my application context with my test versions and then run the test.
Then for each test case I'd like to specify which beans I want to be hot swappable and then each test must be able to create its own mock versions and swap those in, and be able to swap back again."
The most important line is number 12 where we are injecting UserDao mock into Spring context. See that at line 11 we are also registering autowired annotation post processor. If it was not registered, classes annotated with @Autowired would not work.
In current post I have explained how to inject mock beans into Spring Context for testing. Personally I don't like mixing mock beans with real beans in integration tests, I prefer only real beans in this kind of tests; but I can understand that in big modules where a system has multiple subsystems can be useful to isolate some modules from test.
This this would look:
Thank you very much for reading my blog.
Download Code.
Music: http://www.youtube.com/watch?v=Njbm_MABQJE&ob=av2n
Etiquetas: injecting mocks, integration tests, mock, mockito, Spring, StaticApplicationContext, test
lunes, octubre 17, 2011
Una terra promessa Un mondo diverso Dove crescere i nostri pensieri Noi non ci fermeremo Non ci stancheremo di cercare Il nostro camino (Terra Promessa - Eros Ramazzotti)
The essence of the Observer Pattern is to "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." GoF. Observer pattern is a subset of publish/subscribe pattern which allows a number of observer objects to see an event.
martes, octubre 11, 2011
You're so sexy sex sex sexy. Feel me now and stop the conversation. No, no, no don't stop the desire no, No, no, no, no! (Sexy - French Affair)
INTRODUCTION
SnakeYAML is a YAML parser and emitter for the Java programming language, and will be used to implement our message converter.
DESIGN
CODE
RUNNING
martes, octubre 04, 2011
Can't you see, It all makes perfect sense, Express in dollars and cents, Pounds shillings and pents, Can't you see, It all makes perfect sense (Perfect Sense Part II - Roger Waters)
REST INTRODUCTION
From Wikipedia: REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. A resource can be essentially any coherent and meaningful concept that may be addressed.
For those who have never read about Rest this description of Rest architecture could seem something strange and bit complicated.
CONCLUSIONS
Of course this is a very simple application with only one operation, but it gives you an idea of how to develop Restful web services using Spring MVC. It is a matter of time of writing all your required operations using same approach that I have used with GET.
Etiquetas: annotations, jackson, jaxb, json, rest, restclient, restful web services, spring mvc, spring MVC rest, xml, yaml
miércoles, septiembre 28, 2011
Ratti Ratti Sachi Maine Jaan Gavayi Hai, Nach Nach Koylo Pe Raat Bitayi Hai, Akhiyon Ki Neend Maine Phoonko Se Uda Di (Jai Ho - A.R. Rahman)
As an example I have used a simplified version of Cafe Sample Application that are shipped with Spring Integration bundle, but adding MongoDB MessageStore.
Next important piece of code is Cafe interface. This class acts as a facade for placing orders and not explained yet, for retrieving orders. Let's see this class:
And now you are ready to send orders using Cafe interface and receiving at console output not the order but an UUID.
And our "test" now looks like:
Download code.
Music: http://www.youtube.com/watch?v=NtDzUwVWQL0
jueves, septiembre 22, 2011
Luna quieres ser madre Y no encuentras querer Que te haga mujer Dime luna de plata (Hijo de la Luna - Mecano)
You can think I am joking, but not, JPA API is required. Here you can read why: https://jira.springsource.org/browse/SPR-6819. AnnotationDrivenStaticEntityMockingControl class requires javax.persistence.Entity to be in classpath. Hopefully nowadays most projects use JPA, so this dependency may already be required by your code, if not, then you should append it as dependency.
And finally aspectj-maven-plugin is registered:
This plugin requires that you define which dependencies will be used using <dependencies> tag. In order to apply already compiled aspects to your own sources you need to setup all JAR files you would like to weave in the plugin configuration using <aspectLibraries> section; in this case spring-aspects artifact is required so application can use capabilities that offer @Configurable annotation. Finally execution section should contain compile and test-compile goals so main and test classes can be woven.
Hope you find this post useful.
Alex.
Etiquetas: ajdt, aspectj, aspectj-maven-plugin, eclispe, maven, maven aspectj, pom, spring-aspects
lunes, septiembre 19, 2011
The Bell That Rings Inside Your Mind, Is Challenging The Doors Of Time, It’s A Kind Of Magic (A Kind Of Magic - Queen)
Almost all of our projects have a persistence layer, either relational database, document stores, or simply XML files. And typically you will use DAO pattern to implement abstract interface between your business objects and your data store.
In this post but I am going to explain another pattern that can be used instead of DAO pattern. Active record pattern is an architectural pattern that force you to implement CRUD operations on your model class, hence model class itself is responsible for saving, deleting, loading from database.
There are many strategies to follow to implement this pattern, but for me, the best one is using Aspect Oriented Programming, because we are still maintaining separation of concerns favoring isolated unit testing, and not breaking encapsulation.
Aspect-oriented programming entails breaking down program logic into distinct parts. These parts are known as crosscutting concerns because they "cut across" multiple abstractions in a program. Example of crosscutting concerns can be logging, transaction manager, error manager or splitting large datasets. For people that have worked with aspects not much secret here, to use them you simply create an aspect defining the advice and the pointcut, and your aspect is ready to be executed.
I am sure that first idea that comes to your brain is annotating Car class with @XmlRootElement (annotation to map root element in JAXB). Don’t do that, use aspects. Your first mission is trying to maintain Car file as simple as possible. To add an annotation using ITD, is as simple as:
With @type you are exposing which member is annotated. In this case only class. Other possibilities are @method, @constructor and @field. Then elements pattern that should be annotated, in this case Car class, but you could use any regular expressions like org.alexsotob..*. Finally the annotation.
Next step is using JAXB classes to marshalling/unmarshalling objects. In this example I am using spring-oxm package and briefly you will understand why. Spring-oxm is a part of spring-core that contains classes for dealing with O/X Mapping.
This spring module contains one class for each Xml binding supported. In our case Jaxb2Marshaller is used as marshaller and unmarshaller.
It is possible that you are thinking of creating a service class where you inject Jaxb2Marshaller instance. This service would include two methods (save and load) with Car class as argument or return value. Sorry but, doing this, you are implementing DAO pattern. Let's implement Active Record pattern approach. And as you may suppose, aspectj comes to rescue you to avoid mixing concepts in same source file.
Let's update previous aspect file so all required logic by JAXB will be in same file.
Last step is configuring marshaller in spring context file.
First of all is creating a new aspectj file to annotate Car class as Configurable.
Now run unit test again and green will invade your computer :D.
ITD is a really nice solution to design classes with its own responsibilities. It gives you the oportunity of writing maintainable and understandable code, without loosing encapsulation. Of course you should take care of not to have high coupling in aspected classes, and convert them in "God Classes".
Note that implementing same approach but using relational database, it is as simple as changing Jaxb2Marshaller to EntityManager.
I wish you have found this post useful.
Download Full code
Music: http://www.youtube.com/watch?v=KLFZzInXAWI
Etiquetas: active record pattern, ajdt, AOP, aspectj, class responsibilities, dao pattern, hamcrest xml, inter-type declarations, itd, java, jaxb, junit, spring-aspects, spring-oxm, xml
lunes, septiembre 12, 2011
Questa di Marinella è la storia vera Che scivolò nel fiume a Primavera Ma il vento che la vide così bella Dal fiume la portò sopra una stella (Canzone Di Marinella - Mina)
- Create a GitHub repository.
- Initialize local directory as Git repo.
- Modify project pom so distribution management tag points to local repository.
- Perform deploy goal so artifact is deployed to local repository.
- Push changes to GitHub.
- Nothing more. Now other project poms can use your repository.
Fourth Step is running mvn -DperformRelease=true clean deploy. Project is compiled, tested, and packaged. Now go to local repository and see what has appeared.
When bar project is being compiled, github-test artifact is downloaded.
I think it is a good approach when you need to upload a Maven artifact temporally, or simply because your project requires a milestone version of artifact that is not uploaded into any repository.
I hope you like this post, and ... MOVE TO GIT.
Music: http://www.youtube.com/watch?v=TL69oTe6HHY
Etiquetas: github, java, maven, maven deploy, maven repository
martes, septiembre 06, 2011
Soy El Capitán De La Nave Tengo El Control, Llamando A La Tierra Esperando Contestación, Soy Un Cowboy Del Espacio Azul Eléctrico (Llamando A La Tierra - M.Clan)
Our emulator has an XML file where all required resources for running tests are configured. In summary each file contains a list of blood barcodes, and reagent barcodes. In our case barcodes have a meaning (kind of resource, expiry date, checksum, ...).
So one can think about creating a standard configuration file that is used in integration tests. It is a good idea if you don't know that expiry date is expressed in months. So one day without knowing exactly why your tests begin to fail. The answer is obvious, resources have become expired. We need a (script ?) that updates this XML file so when a resource is becoming expired, its month field is changed.
Moreover not all resources should be updated. Some tests imply working with expired resources. For this reason some barcodes have special format that suggests that update should not be applied.
Because project is developed in Java, one can think about creating a small Java class that do all these work. But wait and think if this class would be small or not, we need a parser (DocumentBuilder), a method that walks all nodes and see if resource is expired or not (NodeList, Element.getAttribute(), ...), and finally writing modifications to file. Furthermore, some barcodes contains special charachtrs that should be detected using a regular expression (Pattern, Matcher) for avoiding its update. Although this class is not difficult, it is far away from a small class with few lines.
But how about polyglot programming? Groovy can be a choice. Let's see how Groovy deals with XML and Regular Expressions.
Imagine next XML file:
Groovy and XML
Meanwhile in Java you create a DocumentBuilderFactory that returns a DocumentBuilder, and then call parse method, in Groovy is as simple as:
and root variable points to root element of XML file.
And now imagine that you want to update all blood barcodes of given holder. With Java you will use an iterator over NodeList or using an XPath expression. See the simplicity with Groovy.
See that with Groovy, nodes are explored as object attributes, and finally we call findAll() method that returns a list of sample nodes belonging to SampleHolder11 tag. For returning an attribute value is as easy as adding @ character before attribute name, in our case barcode.
And for writing an XML is as easy as:
In previous example, output is written to console.
Remember that some barcodes have special format. In our case if any barcode starts with A, B, C or D, should not be modified. A clean, reusable and maintainable solution is using regular expressions to check if one barcode matches or not special format. In Java the process is not banal, you have to create a Pattern object with a regular expression, a Matcher and use find() method to see if pattern is found on entry or not.
But how we can determine if one string matches a regular expression in Groovy ? ==~ operator does the work for us. Tell me what you think about this expression:
Elementary. You will agree with me that Groovy approach is simpler than Java one. For specifying a pattern you only have to use ~ character plus a slash (/) then a regular expression and finally a slash to delimit. But Groovy also supports =~ (create a Matcher) and ==~ (return boolean, whether String matches the pattern).
I think that creating a script that reads/parses/writes XML file is so fast and easy, not much classes are involved compared to Java. And not worth making the comparison with regular expression approach, in Groovy is the simplest way one may think.
After the success of previous Groovy script, we decided to create another tool (Groovy script) for manipulating database.
System registers into database every incidence that has occurred to an execution. Some incidences are easy to reproduce with emulator, but others not. In integration tests there is no problem, because a defined-filled database is used, but acceptance tests contains no data and is generated with the execution of tests. But because there are some incidences that are hard to reproduce in emulator, a Groovy script to insert incidences are created.
Groovy and SQL
As Java, Groovy can also access to databases and as you can suppose in a simple way. No Connection object, no PreparedStatement, no ResultSet, ....
Let's see an example of searching data and using them for creating a new registry. Imagine that we have a table called Execution and another one called Incidence, and one-to-many relationship.
Simple, yes? With one line a connection to database is established.
Executing SELECT query and iterate over results are also easy. Using eachRow method, all results are iterated. No ResultSet object is required anymore. Parameters values are passed between brackets ([]), and as XML each row is accessed using Closure. In previous example each row is mapped to execution variable. Moreover see how easy is read a value of each tuple. As in XML you access the value as a class attribute, no more getters of ResultSet methods, in example execution.dboid is used to refer to dboid field.
Finally execute method is used to update database.
Now that I have shown you some of nice features that Groovy offers us, I will explain you how we execute these tools.
GMaven
We use Jenkins with Maven as Continuos Integration System. Before Jenkins starts to execute Integration Tests, Groovy scripts are executed so emulator is configured propertly. The iteresting part of this step is how pom is configured for executing Groovy scripts.
Exists a plugin called gmaven-plugin. This plugin runs Groovy scripts depending on phase and goal.
No problem configuring gmaven plugin, the most important part is where you specify which script should be executed.
As final notes I want to say that I am a huge fan of Java and my intention is not criticize it, but I think that there are some problems that are best suited using other languages rather than Java. My advice is learning as many kind of languages as you can (Scala, Groovy, ...) so as programmer you can choose the best solution to a given problem.
I wish you find this post useful.
Music: http://www.youtube.com/watch?v=9u54Xs22_SI