What's New Here?

software-development-2-logo

5 Best Email Clients for Open Source Environment

An email client, also known as Mail User Agent (MUA) is an application used to manage the emails. Linux has a lot of email clients, terminal and GUI based. I have collected the top 5 GUI based email clients and compared them in various aspects.  Standard formats normally used by most of the mailboxes are maildir and mbox. Outlook and Windows Live Mail are 2 of the most awesome mail clients for windows platform. However, newly evolved open source mail clients like thunderbird are found to work quite well with these mail clients across the platform. Following are the top email clients that work perfectly across the platform and support numerous plugins/addons. 1. Mozilla Thunderbird Thunderbird is a free application that is easy to setup and customize. It is loaded with tons of features, some features that even the top mail clients like outlook don’t provide. We have been using thunderbird for a user base of over 10k here in Ericsson on the Linux platform, Ubuntu. It gets better with each update and believe me, it works well in sync with the windows platform outlook email client. Being an open source application, it is customizable and there are tons of addons/plugins available which make it even more awesome.There are lots of forums where you can get support related to this open source application. Download latest stable version of Mozilla Thunderbird 2. Claws Mail Claws Mail is an email client (and news reader), based on GTK+, featuringQuick response Graceful, and sophisticated interface Easy configuration, intuitive operation Abundant features Extensibility Robustness and stabilityThe appearance and interface are designed to be familiar to new users coming from other popular email clients, as well as experienced users. Almost all commands are accessible with the keyboard. The messages are managed in the standard MH format, which features fast access and data security. You’ll be able to import your emails from almost any other email client, and export them just as easily. Lots of extra functionality, like an RSS aggregator, calendar, or laptop LED handling, are provided by extra plugins. Claws Mail is distributed under the GPL.Download the latest version of Claws mail 3. Zimbra Collaboration Suite Zimbra Collaboration Suite is a groupware email server and web client, currently owned and developed by Zimbra, Inc. Zimbra was initially developed by Zimbra, Inc., and first released in 2005. Zimbra powers collaboration for the way you work. Zimbra connects people and information with unified collaboration software that includes email, calendaring, file sharing, activity streams, social communities and more. With technology designed for social, mobile and the cloud, Zimbra gives individuals the flexibility to work from virtually anywhere, through nearly every computer, tablet and mobile device.Download the latest Open Source version of Zimbra  4. Sylpheed Sylpheed is a simple, lightweight but featureful, and easy-to-use e-mail client. Sylpheed provides intuitive user-interface. Sylpheed is also designed for keyboard-oriented operation, so Sylpheed can be widely used from beginners to power users. Sylpheed runs on many systems such as Windows, Linux, BSD, Mac OS X and other Unix-like systems. Sylpheed uses GTK+ GUI toolkit. The newest version of Sylpheed works with GTK+ 2.4 or later (2.6 or later is recommended). Sylpheed is a free software distributed under the GNU GPL (the library part is GNU LGPL). You can freely use, modify and redistribute it under the license. 5. Evolution Evolution (formerly Novell Evolution and Ximian Evolution, prior to Novell’s 2003 acquisition of Ximian) is a personal information management application that provides integrated mail, calendaring and address book functionality. It has been an official part of GNOME since Evolution 2.0 was included with the GNOME 2.8 release in September 2004. It combines e-mail, address book, calendar, task list and note-taking features. Its user interface and functionality is similar to Microsoft Outlook. Evolution is free software licensed under the terms of the GNU General Public License.Download the latest version of Evolution Comparison of Email Clients: Here is the technical and general comparison between the email clients i have discussed:Recommended email clients:Claws Mail – Highly recommended for individual users due to lightweight usage and interface is designed to be familiar to new users coming from other popular email clients. Mozilla Thunderbird – Good for the corporate environment with large user base, highly compatible with cross platform email clients Zimbra Collaboration Suite- Open Source Edition or Businesses Editon – One of the best for business and corporate users due to its support for a broad range of email clientsThese are the email clients i have used at some point or the other and have rated them accordingly. If you think, there are email clients that work better and should be in the list above, feel free to leave us a comment.   Reference: 5 Best Email Clients for Open Source Environment from our JCG partner Saurab Parakh at the Coding is Cool blog. ...
spring-logo

Spring for Apache Hadoop 2.0 M5

Spring has happily announced the Spring for Apache Hadoop 2.0 M5 milestone releases, while they are also getting much closer to a release candidate. In the Spring blog there is a good comparison between the new version 2.0 and the 1.0 version. According to it: 1.0 version of Spring for Apache Hadoop uses HDFS and MapReduce with either MapReduce v1 or MapReduce v2 (YARN). The default distribution is Apache Hadoop 1.2.1 with additional features, like Hadoop 2.2.0, Pivotal HD 1.1, Cloudera CDH4 MR1 or MR2 YARN and Hortonworks HDP 1.3. On the other hand, Spring for Apache Hadoop 2.0 focuses in adding YARN application development support in addition to continue to provide improvements in the HDFS and MapReduce support. The default distribution for the 2.0 releases is Apache Hadoop 2.2.0. Below you can see the specific artifacts with their respective transitive dependencies in the Spring IO milestone repository:2.0.0.M5 (default – Apache Hadoop stable 2.2.0) 2.0.0.M5-hadoop12 (Apache Hadoop stable 1.2.1) 2.0.0.M5-phd1 (Pivotal HD 1.1) 2.0.0.M5-cdh4 (Cloudera CDH4 MR1) 2.0.0.M5-cdh5 (Cloudera CDH5 YARN beta) 2.0.0.M5-hdp20 (Hortonworks HDP 2.0)Spring for Apache Hadoop 2.0 version also offers:The support for YARN features in the new spring-yarn sub-project. With the spring-yarn framework Spring based applications can be developed and they can be deployed to run on Hadoop v2 using YARN. YARN support with Spring Boot. Now Spring Boot applications can be deployed on YARN. Annotation based programming model and annotation based configuration for Hadoop YARN features.All new YARN features are in the YARN samples, so you can check them out there. A spring-data-hadoop-store sub-project is also here to provide better support for writing data to HDFS using DataWriter and DataReader implementation supporting formats like text files and SequenceFiles with or without compression. The new sub-project also integrates with the Dataset support from Kite SDK. For more project specific information please see the project page. ...
java-logo

Java: Handling a RuntimeException in a Runnable

At the end of last year I was playing around with running scheduled tasks to monitor a Neo4j cluster and one of the problems I ran into was that the monitoring would sometimes exit. I eventually realised that this was because a RuntimeException was being thrown inside the Runnable method and I wasn’t handling it. The following code demonstrates the problem:         import java.util.ArrayList; import java.util.List; import java.util.concurrent.*;public class RunnableBlog { public static void main(String[] args) throws ExecutionException, InterruptedException { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " -> " + System.currentTimeMillis()); throw new RuntimeException("game over"); } }, 0, 1000, TimeUnit.MILLISECONDS).get();System.out.println("exit"); executor.shutdown(); } } If we run that code we’ll see the RuntimeException but the executor won’t exit because the thread died without informing it: Exception in thread "main" pool-1-thread-1 -> 1391212558074 java.util.concurrent.ExecutionException: java.lang.RuntimeException: game over at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252) at java.util.concurrent.FutureTask.get(FutureTask.java:111) at RunnableBlog.main(RunnableBlog.java:11) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) Caused by: java.lang.RuntimeException: game over at RunnableBlog$1.run(RunnableBlog.java:16) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) At the time I ended up adding a try catch block and printing the exception like so: public class RunnableBlog { public static void main(String[] args) throws ExecutionException, InterruptedException { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName() + " -> " + System.currentTimeMillis()); throw new RuntimeException("game over"); } catch (RuntimeException e) { e.printStackTrace(); } } }, 0, 1000, TimeUnit.MILLISECONDS).get();System.out.println("exit"); executor.shutdown(); } } This allows the exception to be recognised and as far as I can tell means that the thread executing the Runnable doesn’t die. java.lang.RuntimeException: game over pool-1-thread-1 -> 1391212651955 at RunnableBlog$1.run(RunnableBlog.java:16) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) pool-1-thread-1 -> 1391212652956 java.lang.RuntimeException: game over at RunnableBlog$1.run(RunnableBlog.java:16) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) pool-1-thread-1 -> 1391212653955 java.lang.RuntimeException: game over at RunnableBlog$1.run(RunnableBlog.java:16) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) This worked well and allowed me to keep monitoring the cluster. However, I recently started reading ‘Java Concurrency in Practice‘ (only 6 years after I bought it!) and realised that this might not be the proper way of handling the RuntimeException. public class RunnableBlog { public static void main(String[] args) throws ExecutionException, InterruptedException { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName() + " -> " + System.currentTimeMillis()); throw new RuntimeException("game over"); } catch (RuntimeException e) { Thread t = Thread.currentThread(); t.getUncaughtExceptionHandler().uncaughtException(t, e); } } }, 0, 1000, TimeUnit.MILLISECONDS).get();System.out.println("exit"); executor.shutdown(); } } I don’t see much difference between the two approaches so it’d be great if someone could explain to me why this approach is better than my previous one of catching the exception and printing the stack trace.   Reference: Java: Handling a RuntimeException in a Runnable from our JCG partner Mark Needham at the Mark Needham Blog blog. ...
spring-logo

Retry web service operations with RequestHandlerRetryAdvice

1.Introduction Sometimes when invoking a web service, we may be interested in retrying the operation in case an error occurs. When using Spring Integration, we can achieve this functionality with RequestHandlerRetryAdvice class. This class will allow us to retry the operation for a specified number of times before giving up and throwing an exception. This post will show you how to accomplish this. The test application will invoke a web service and if it fails to respond, it will wait for a specified time and try it again until it receives a response or it reaches a retry limit. If the limit is reached, the failed request will be stored into a database. Mainly, this post shows an example of the following:Using an outbound gateway to invoke a web service Configuring a retry advice to retry the operation if necessary MongoDB integration.The source code of the application can be found at github. You can also get the source code of the web service project that is called by the application at github. 2.Web service invocation Use case: The client invokes the web service and receives a response.The request enters the messaging system through the “system entry” gateway. It then reaches the outbound gateway, invokes the web service and waits for the response. Once received, the response is sent to the response channel. The above image is the result of this configuration: <context:component-scan base-package="xpadro.spring.integration" /><!-- Initial service request --> <int:gateway id="systemEntry" default-request-channel="requestChannel" service-interface="xpadro.spring.integration.gateway.ClientService" /> <int:channel id="requestChannel"> <int:queue /> </int:channel><int-ws:outbound-gateway id="marshallingGateway" request-channel="requestChannel" reply-channel="responseChannel" uri="http://localhost:8080/spring-ws/orders" marshaller="marshaller" unmarshaller="marshaller"> <int:poller fixed-rate="500" /> </int-ws:outbound-gateway><oxm:jaxb2-marshaller id="marshaller" contextPath="xpadro.spring.integration.types" /><!-- Service is running - Response received --> <int:channel id="responseChannel" /><int:service-activator ref="clientServiceActivator" method="handleServiceResult" input-channel="responseChannel" /> Mapped to the response channel there’s a service activator which just logs the result. TestInvocation.java: Sends the request to the entry gateway @ContextConfiguration({"classpath:xpadro/spring/integration/config/int-config.xml", "classpath:xpadro/spring/integration/config/mongodb-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class TestInvocation { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private ClientService service; @Test public void testInvocation() throws InterruptedException, ExecutionException { logger.info("Initiating service request..."); ClientDataRequest request = new ClientDataRequest(); request.setClientId("123"); request.setProductId("XA-55"); request.setQuantity(new BigInteger("5"));service.invoke(request); logger.info("Doing other stuff..."); Thread.sleep(60000); } } With this configuration, if the service invocation fails, a MessagingException will be raised and sent to the error channel. In the next section, we will add the retry configuration. 3.Adding the retry advice Use case: The initial request failed because the service is not active. We will retry the operation until a response is received from the service. In this case, we need to add the retry advice to the web service outbound gateway: <int-ws:outbound-gateway id="marshallingGateway" interceptor="clientInterceptor" request-channel="requestChannel" reply-channel="responseChannel" uri="http://localhost:8080/spring-ws/orders" marshaller="marshaller" unmarshaller="marshaller"> <int:poller fixed-rate="500" /> <int-ws:request-handler-advice-chain> <ref bean="retryAdvice" /> </int-ws:request-handler-advice-chain> </int-ws:outbound-gateway> Now the web service outbound gateway will delegate the invocation to the retry advice, which will try the operation as many times as specified until it gets a response from the service. Let’s define the retry advice: <bean id="retryAdvice" class="org.springframework.integration.handler.advice.RequestHandlerRetryAdvice" > <property name="retryTemplate"> <bean class="org.springframework.retry.support.RetryTemplate"> <property name="backOffPolicy"> <bean class="org.springframework.retry.backoff.FixedBackOffPolicy"> <property name="backOffPeriod" value="4000" /> </bean> </property> <property name="retryPolicy"> <bean class="org.springframework.retry.policy.SimpleRetryPolicy"> <property name="maxAttempts" value="4" /> </bean> </property> </bean> </property> </bean> To accomplish its objective, the advice uses a RetryTemplate, which is provided by the Spring Retry project. We can customize its behavior by defining backoff and retry policies. Backoff policy: Establishes a period of time between each retry. The more interesting types are:FixedBackOffPolicy: Used in our example. It will wait for the same specified amount of time between each retry. ExponentialBackOffPolicy: Starting with a determined amount of time, it will double the time on each retry. You can change the default behavior by establishing a multiplier.Retry policy: Establishes how many times will retry the failed operation. Some of the types:SimpleRetryPolicy: Used in our example. Specifies a retry attempts limit. ExceptionClassifierRetryPolicy: Allows us to establish a different maxAttempts depending on the exception raised. TimeoutRetryPolicy: Will keep retrying until a timeout is reached.4.No luck, logging the failed request Use case: The service won’t recover, storing the request to the database.The final part of the configuration is the following: <!-- Log failed invocation --> <int:service-activator ref="clientServiceActivator" method="handleFailedInvocation" input-channel="errorChannel" output-channel="logChannel" /><int:channel id="logChannel" /><bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory"> <constructor-arg> <bean class="com.mongodb.Mongo"/> </constructor-arg> <constructor-arg value="test"/> </bean><int-mongodb:outbound-channel-adapter id="mongodbAdapter" channel="logChannel" collection-name="failedRequests" mongodb-factory="mongoDbFactory" /> The service activator subscribed to the error channel will retrieve the failed message and send it to the outbound adapter, which will insert it to a mongoDB database. The service activator: public Message<?> handleFailedInvocation(MessagingException exception) { logger.info("Failed to succesfully invoke service. Logging to DB..."); return exception.getFailedMessage(); } If we not succeed in obtaining a response from the service, the request will be stored into the database:6.Conclusion We’ve learnt how Spring Integration gets support from the Spring Retry project in order to achieve retry of operations. We’ve used the int-ws:request-handler-advice-chain, but the ‘int’ namespace also supports this element to add this functionality to other types of endpoints.   Reference: Retry web service operations with RequestHandlerRetryAdvice from our JCG partner Xavier Padro at the Xavier Padró’s Blog blog. ...
software-development-2-logo

The Anatomy of a Great Stack Overflow Question (After Analyzing 10,000)

How to phrase a question in Stack Overflow in order to get better answers Stack Overflow offers a great interface for accessing all of its data and running any possible query in the questions/answers database. We started using this database to better understand the most common questions about debugging (what we’re trying to solve at Takipi). While learning about debugging through thousands of questions, we also noted an additional bonus: we started better understanding what drives the Stack Overflow community. This article is the result of researching over 10,000 Stack Overflow questions. It summarizes how you need to phrase and write your question in order to get better and faster answers. When we started running our scripts on the queries’ answers we weren’t sure we’d arrive at strong conclusions. After looking into a few hundred questions, though, we already started recognizing certain distinct patterns that we were seeing over and over again across different programming languages and topics. You can find a detailed explanation of how we performed the test at the end of the article, but let’s get to the best part first — the results. The main criteria we set for a ‘good’ question were getting high quality answers (from users with high reputation + votes), getting an answer relatively quickly and the number of votes and views. Keep it short Probably the strongest pattern we saw across all the different queries and scripts we ran was this: the shorter the question, the more likely you are to get a quick and useful answer. The average length of a ‘good’ question was around 1200 characters (~3-4 short paragraphs), while the average length of a standard question was 1800 characters. The strongest effect of the length was on the view count and votes, where the average length of the top questions was around 50% of that of standard questions. There’s no such thing as too short, either — really short questions (around 200-300 characters) received the best results. Title length matters less, we discovered. While we saw the effect of the question’s length across the board, it seems like the length of the title has a minor influence on the quality of the question. The average title length of the top questions was about 5% shorter than that of standard titles (47 characters vs. 50).#1 influencer – asker reputation The asker’s reputation has a huge effect on the number and quality of the answers and the speed of reply. It seems that users with high reputations tend to answer more frequently to users with high reputations as well. While we saw that short questions are 50-100% more likely to get better and faster answers, a question asked by a user with a very high reputation is three times more likely to get better answers than a question asked by a user with a low reputation. You might conclude, of course, that users with high reputations ask better questions. It’s definitely true, but we saw some very similar questions asked by users with low and high reputations, and the difference in the quality of the answer was clear. Some examples: the average asker reputation of the top 100 Java questions with the best answers (high reputation of the user who gave the answer + votes) was 4500 points. The average asker reputation of standard Java questions was 1500. The average asker reputation of Ruby questions that were answered within 15 minutes was 2400. The average asker reputation of Ruby questions that were answered after 24 hours was 1300. The average asker reputation of the 100 top viewed Java questions is 3150, compared to average standard question reputation of 1100.Should I use code snippets? Embedding code snippets in the question was one of the few parameters we tested that gave very clear results across different languages, but opposite results across different criteria. It seems like questions which include code snippets get better answers — answers with more votes and from users with higher reputation. For example, 87% of the Python related questions answered by users with a very high reputation included code snippets. 64% of the average Python questions include code snippets. Ruby-related questions showed similar results — 91% of the top questions included code snippets compared to an average of 79%. When it comes to votes, views and time until the first answer, the trend is opposite — for example, 58% of the most viewed Python questions included code snippets. 72% of the questions with an average number of views included code snippets. It seems like it’s related to the question’s length — code snippets lead to longer questions which get lower results. Use fewer tags Not a huge difference, but it seems that across the different criteria we tested, the top results have fewer tags than the average. Questions which got high quality answers, quicker response and more votes had an average of 3 tags (seems to be the same in different languages). Standard questions had around 3.5 – 3.7 tags. When is the best time to post a question? From our data it doesn’t seem that the time of day affects the results. Stack Overflow “rush hour” is usually between 11 am and 5 pm UTC. About 50% of the questions are asked in that time frame. Questions asked in these hours were a bit more likely to get an answer faster (by about 5-10%) but the answers weren’t higher in quality. The time the question was posted doesn’t affect other criteria like votes, views or number of answers. How to title your question - Getting into the art science of wording Use the name of the language/ topic in the title One of the main scripts we used was built in order to count and analyze the titles. We grouped words according to programming terms (like “string”, “array”, “function”), language/topic (like Ruby, MySQL, C#), negative/positive words (like “can’t”, “worst”, “best”, “fail”) and more. The most distinct conclusion — if you want to get faster and better answers, use the topic you’re asking about in the title. Have a question about something in Python? Just add Python to the title. Some examples: 36% of Ruby-related questions that were answered within 15 minutes included the word “Ruby” in the title. Only 15% of the questions that were answered after 24 hours had the word “Ruby” in the title. 58% of the Java questions with the highest view count include the word “Java.” 39% of standard Java questions included the word “Java.” And what about using two languages in the title? For example, “Why are String comparisons (CompareTo) faster in Java than in C#?”. It seems like using two different languages/ topics in the title might reduce the number and quality of the answers, as there are fewer users who are proficient in both. However, this kind of questions performed very well and were much more likely to get good results. It doesn’t matter if you phrase the title as a question or not Here’s one statistic that surprised me. Phrasing the title as a question doesn’t affect the speed or quality of the answers. For example – “Add the same method to multiple classes” vs. “How to add the same method to multiple classes?” will gain the same results. The only difference we noted in the research was that titles phrased as questions are a bit more likely to get a faster answer (by about 10%). Something doesn’t work for you? You can’t solve a problem? The community is here to help A title that indicates that something is not working, or asking about an error, will usually get a better and faster response. For example: Rspec stub doesn’t work Why is bundler unable to reach http://rubygems.org? Can’t import my own modules in Python It seems like using words that indicate failure (“cannot”, “unable”, “fails”, “error”, “not working”, etc.) lead to better answers. For example, 22% of the top Ruby questions included a negative phrase in the title, while the average for standard questions was 14%. However, it seems that indicating that something doesn’t work or asking about an error doesn’t attract users with high reputations. These questions got faster results, more answers, and higher view count, but were answered by users with a less than average reputation. Should I use X or Y? Comparing different technologies or methodologies is a good recipe for high quality answers. This type of questions had a significant part in every ‘top questions’ list we formed. Here are a few examples: Why shouldn’t I use PyPy over CPython if PyPy is 6.3 times faster? Why is char[] preferred over String for passwords? Why are String comparisons (CompareTo) faster in Java than in C#? Let’s make it interesting Pretty obvious, but many of the top ranked questions point to mysterious behavior or unexpected results. Here are some examples of top questions: Why is processing a sorted array faster than an unsorted array? (6960 votes) Why does changing 0.1f to 0 slow down performance by 10x? (774 votes) Why does parseInt(1/0, 19) return 18? (632 votes) How did we perform the test? We decided to focus on language-oriented questions in order to avoid general questions (like “how do I become a better programmer” or “which job interview question to use”) or humor-related questions that usually get a very high score but don’t represent typical problems developers face. We focused on 6 programming languages – Java, Ruby, Python, C++, Javascript and C#. The first three languages we analyzed were Java, Ruby and Python — the results were very similar across these three, so we decided not to analyze the other three for now. We decided to focus only on questions asked since 2011. We ran eight different queries and sorted the questions according to: votes, number of answers, favorites count, time until the first answer, time of day the question was posted, questions answered by users with a high reputation, questions asked by users with high reputation, view count. Then we compared the top 300 questions in each section to 300 questions that received an average score on the parameter we focused on. This is obviously not an exact science, and there’s not a “scientific recipe” for getting great answers. However, all the patterns mentioned above repeated themselves across the different parameters and different languages we questioned. Here are some of the queries we used: have fun with it and let us know if you find other interesting results. Thanks to Dror Cohen from CodersClan for helping out and to John Woo who justified his 120k+ SO reputation points and helped us write the queries.  Sample QueriesQuestions by users with high reputation and Python tag ;WITH recordsList AS ( SELECT 'http://stackoverflow.com/users/' + CAST(p.OwnerUserId AS VARCHAR(10)) AS OwnerLink, 'http://stackoverflow.com/questions/' + CAST(p.ID AS VARCHAR(10)) AS QuestionLink, p.Score, p.ViewCount, p.FavoriteCount, p.Title, LEN(p.Title) AS TitleLength, LEN(p.Body) AS BodyLength, p.Tags, p.CreationDate, u.Reputation, ROW_NUMBER() OVER (PARTITION BY p.OwnerUserId ORDER BY p.Score DESC) UserAnswerSequence, CASE WHEN CHARINDEX('<code>', p.Body) > 0 THEN 'True' ELSE 'False' END ContainsCodeBlock FROM Posts AS p INNER JOIN Users As u ON p.OwnerUserId = u.Id INNER JOIN PostTags AS pt ON pt.PostId = p.Id WHERE p.PostTypeId = 1 -- <<== Questions AND p.CommunityOwnedDate IS NULL -- <<== not WIKI AND pt.TagId = 16 -- <<== PYTHON ) SELECT TOP 5000 OwnerLink, QuestionLink, Score, ViewCount, FavoriteCount, Title, TitleLength, BodyLength, Tags, CreationDate, ContainsCodeBlock FROM recordsList WHERE UserAnswerSequence <= 50 ORDER BY Reputation DESC, Score DESCAnswers by users with high reputation and Java tag ;WITH recordsList AS ( SELECT 'http://stackoverflow.com/users/' + CAST(p.OwnerUserId AS VARCHAR(10)) AS OwnerLink, 'http://stackoverflow.com/questions/' + CAST(p.ID AS VARCHAR(10)) AS QuestionLink, p.Score, p.ViewCount, p.FavoriteCount, p.Title, LEN(p.Title) AS TitleLength, LEN(p.Body) AS BodyLength, p.Tags, p.CreationDate, u.Reputation, ROW_NUMBER() OVER (PARTITION BY pa.OwnerUserId ORDER BY pa.Score DESC, p.Score DESC) UserAnswerSequence, CASE WHEN pa.CommunityOwnedDate IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END IsAnswerWiki FROM Posts AS p INNER JOIN Posts As pa ON pa.PostTypeId = 2 -- <<== Answer AND p.Id = pa.ParentID AND p.OwnerUserId <> pa.OwnerUserId -- <<== not come on the same poster AND p.AcceptedAnswerId = pa.Id INNER JOIN Users As u ON pa.OwnerUserId = u.Id INNER JOIN PostTags AS pt ON pt.PostId = p.Id WHERE p.PostTypeId = 1 -- <<== Questions AND p.CommunityOwnedDate IS NULL -- <<== not WIKI AND pt.TagId = 17 -- <<== JAVA AND p.OwnerUserId IS NOT NULL -- <<== user is not deleted AND pa.OwnerUserId IS NOT NULL -- <<== user is not deleted ) SELECT TOP 5000 OwnerLink, QuestionLink, Score, ViewCount, FavoriteCount, Title, TitleLength, BodyLength, Tags, CreationDate, IsAnswerWiki FROM recordsList WHERE UserAnswerSequence <= 50 ORDER BY Reputation DESC, Score DESCGrouping questions by the hour they were published (0-23) and showing the time it took to answer them. ;WITH hourgenerator -- <<== generates 0-23 (24Hour) AS ( SELECT 0 AS hourPosted UNION ALL SELECT hourPosted + 1 FROM hourgenerator WHERE hourPosted < 23 ), questionsPerHour AS ( SELECT CAST(p.CreationDate as DATE) AS [Date], DATEPART(Hour, p.CreationDate) AS hourPosted, COUNT(*) NumberOfQuestions, AVG(DATEDIFF(second, p.CreationDate, pa.CreationDate)) AvgTimeAnswered FROM Posts AS p INNER JOIN Posts As pa ON pa.PostTypeId = 2 -- <<== Answer AND p.Id = pa.ParentID AND p.OwnerUserId <> pa.OwnerUserId -- <<== not come on the same poster AND p.AcceptedAnswerId = pa.Id WHERE p.PostTypeId = 1 -- <<== Questions AND p.CommunityOwnedDate IS NULL -- <<== not WIKI AND DATEDIFF(second, p.CreationDate, pa.CreationDate) >= 0 AND p.OwnerUserId IS NOT NULL -- <<== user is not deleted AND pa.OwnerUserId IS NOT NULL -- <<== user is not deleted AND p.CreationDate >= CAST('2013-11-14' AS DATE) AND p.CreationDate < DATEADD (dd, 1 ,CAST('2013-11-14' AS DATE)) GROUP By CAST(p.CreationDate as DATE), DATEPART(Hour, p.CreationDate) ) SELECT COALESCE(qph.[Date], CAST('2013-11-14' AS DATE)) AS [Date], hg.hourPosted, COALESCE(qph.NumberOfQuestions, 0) AS NumberOfQuestions, COALESCE(qph.AvgTimeAnswered, 0) AS AvgTimeAnswered FROM hourgenerator AS hg LEFT JOIN questionsPerHour AS qph ON hg.hourPosted = qph.hourPosted ORDER BY hg.hourPosted  Reference: The Anatomy of a Great Stack Overflow Question (After Analyzing 10,000) from our JCG partner Iris Shoor at the Takipi blog. ...
spring-logo

How error handling works in Spring Integration

1.Introduction The target of this post is to show you how errors are handled when using the messaging system with Spring Integration. You will see that error handling is different between synchronous and asynchronous messaging. As usual, I’ll skip the chat and proceed with some examples.You can get the source code at github.2.The sample application I will use a basic example, since I want to focus on exception handling. The application consists in an order service, which receives an order, processes it and returns a confirmation. Below we can see how the messaging system is configured: int-config.xml <context:component-scan base-package="xpadro.spring.integration"/><int:gateway default-request-channel="requestChannel" service-interface="xpadro.spring.integration.service.OrderService"/><int:channel id="requestChannel"/><int:router input-channel="requestChannel" ref="orderRouter" method="redirectOrder"/><int:channel id="syncChannel"/><int:channel id="asyncChannel"> <int:queue capacity="5"/> </int:channel><int:service-activator method="processOrder" input-channel="syncChannel" ref="orderProcessor"/><int:service-activator method="processOrder" input-channel="asyncChannel" ref="orderProcessor"> <int:poller fixed-delay="2000"/> </int:service-activator> The gateway is the entry point of the messaging system. It will receive the order and send it to the direct channel “requestChannel” where a router will redirect it to the appropriate channel based on the order id:syncChannel: A direct channel that will send the order to an order processor subscribed to this channel. asyncChannel: A queue channel from which the order processor will actively retrieve the order.Once the order is processed, an order confirmation will be sent back to the gateway. Here is a graphic representing this:Ok, let’s start with the simplest case, synchronous sending using a Direct Channel. 3.Synchronous sending with Direct channel The order processor is subscribed to the “syncChannel” Direct Channel. The “processOrder” method will be invoked in the sender’s thread. public OrderConfirmation processOrder(Order order) { logger.info("Processing order {}", order.getId()); if (isInvalidOrder(order)) { logger.info("Error while processing order [{}]", ERROR_INVALID_ID); throw new InvalidOrderException(ERROR_INVALID_ID); } return new OrderConfirmation("confirmed"); } Now, we will implement a test that will provoke an exception by sending an invalid order. This test will send an order to the gateway: public interface OrderService { @Gateway public OrderConfirmation sendOrder(Order order); } The test: TestSyncErrorHandling.java @ContextConfiguration(locations = {"/xpadro/spring/integration/config/int-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class TestSyncErrorHandling { @Autowired private OrderService service; @Test public void testCorrectOrder() { OrderConfirmation confirmation = service.sendOrder(new Order(3, "a correct order")); Assert.assertNotNull(confirmation); Assert.assertEquals("confirmed", confirmation.getId()); } @Test public void testSyncErrorHandling() { OrderConfirmation confirmation = null; try { confirmation = service.sendOrder(new Order(1, "an invalid order")); Assert.fail("Should throw a MessageHandlingException"); } catch (MessageHandlingException e) { Assert.assertEquals(InvalidOrderException.class, e.getCause().getClass()); Assert.assertNull(confirmation); } } } We run the test and see how an exception is raised in the order processor and reaches the test. That’s fine; we wanted to validate that sending an invalid order raised an exception. This happened because the test sent the order and blocked waiting for the order to be processed in the same thread. But, what happens when we use an asynchronous channel? Let’s continue to the next section. 4.Asynchronous sending with Queue Channel This section’s test sends an order that will be redirected by the router to the queue channel. The gateway is shown below: public interface OrderService { @Gateway public Future<OrderConfirmation> sendFutureOrder(Order order); } Notice that this time the gateway is returning a Future. If we didn’t return this, the gateway would block the test thread. By returning Future, the gateway becomes asynchronous and doesn’t block the sender’s thread. The test: TestKoAsyncErrorHandling.java @ContextConfiguration(locations = {"/xpadro/spring/integration/config/int-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class TestKoAsyncErrorHandling { @Autowired private OrderService service; @Test(expected=MessageHandlingException.class) public void testAsyncErrorHandling() throws InterruptedException, ExecutionException { Future<OrderConfirmation> confirmation = service.sendFutureOrder(new Order(6, "another order")); } } Ok, so now we are going to launch the test and see the exception raising… java.lang.AssertionError: Expected exception: org.springframework.integration.MessageHandlingException Oops the test failed because no exception reached the test! What happened? Well, the explanation is below: <int:channel id="asyncChannel"> <int:queue capacity="5"/> </int:channel><int:service-activator method="processOrder" input-channel="asyncChannel" ref="orderProcessor"> <int:poller fixed-delay="2000"/> </int:service-activator> Since we are using an asynchronous channel (a queue), the sender sends the order and moves on. Then, the receiver polls the order from a different thread. For this reason, it won’t be possible to throw the Exception back to the sender. Let’s act like nothing happened then? Well you better not, there are other options. 5.Asynchronous error handling When using asynchronous messaging, Spring Integration handles exceptions by publishing them to message channels. The exception thrown will be wrapped into a MessagingException and become the payload of the message. What channel is the error message sent to? First, it will check if the request message contains a header called “errorChannel”. If found, the error message will be sent there. Otherwise, the message will be sent to a so-called global error channel. 5.1 Global error channel By default, a global error channel called “errorChannel” is created by Spring Integration. This channel is a publish-subscribe channel. This means we can subscribe several endpoints to this channel. In fact, there’s already an endpoint subscribed to it: a logging handler.This handler will log the payload of messages arriving to the channel, though it can be configured to behave differently. We will now subscribe a new handler to this global channel and test that it receives the exception message by storing it into a database. First of all, we will need to change a few things in our configuration. I’ve created a new file so it doesn’t interfere with our previous tests: int-async-config.xml <context:component-scan base-package="xpadro.spring.integration"/><int:gateway default-request-channel="asyncChannel" service-interface="xpadro.spring.integration.service.OrderService" error-channel="errorChannel"/><int:channel id="asyncChannel"> <int:queue capacity="5"/> </int:channel><int:service-activator method="processOrder" input-channel="asyncChannel" ref="orderProcessor"> <int:poller fixed-delay="2000"/> </int:service-activator><int:service-activator input-channel="errorChannel" ref="orderErrorHandler" method="handleFailedOrder"/><bean id="orderErrorHandler" class="xpadro.spring.integration.activator.OrderErrorHandler"/> The gateway: I’ve added an error channel. If the invocation fails, the error message will be sent to this channel. If I hadn’t defined an error channel, the gateway would have propagated the exception to the caller, but in this case it wouldn’t have worked since this is an asynchronous gateway. The error handler: I’ve defined a new endpoint that is subscribed to the global error channel. Now, any error message sent to the global error channel will be delivered to our handler. I’ve also added a configuration file in order to configure the database. Our error handler will insert received errors to this database: db-config.xml <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg ref="dataSource"/> </bean><!-- in-memory database --> <jdbc:embedded-database id="dataSource"> <jdbc:script location="classpath:db/schemas/schema.sql" /> </jdbc:embedded-database> The error handler is pretty simple; it receives the error message and inserts its information to the database: public class OrderErrorHandler { @Autowired private JdbcTemplate jdbcTemplate; @ServiceActivator public void handleFailedOrder(Message<MessageHandlingException> message) { Order requestedOrder = (Order) message.getPayload().getFailedMessage().getPayload(); saveToBD(requestedOrder.getId(), message.getPayload().getMessage()); } private void saveToBD(int orderId, String errorMessage) { String query = "insert into errors(orderid, message) values (?,?)"; jdbcTemplate.update(query, orderId, errorMessage); } } Ok, now is all set. Let’s implement a new test: TestOkAsyncErrorHandlingTest.java @ContextConfiguration(locations = {"/xpadro/spring/integration/config/int-async-config.xml", "/xpadro/spring/integration/config/db-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class TestOkAsyncErrorHandling { @Autowired private JdbcTemplate jdbcTemplate; @Autowired private OrderService service; @Before public void prepareTest() { jdbcTemplate.update("delete from errors"); } @Test public void testCorrectOrder() throws InterruptedException, ExecutionException { Future<OrderConfirmation> confirmation = service.sendFutureOrder(new Order(7, "another correct order")); OrderConfirmation orderConfirmation = confirmation.get(); Assert.assertNotNull(orderConfirmation); Assert.assertEquals("confirmed", orderConfirmation.getId()); } @Test public void testAsyncErrorHandling() throws InterruptedException, ExecutionException { Future<OrderConfirmation> confirmation = service.sendFutureOrder(new Order(6, "another order")); Thread.sleep(2000); Assert.assertEquals(1, getSavedErrors()); validateSavedError(6); } private int getSavedErrors() { return jdbcTemplate.queryForObject("select count(*) from errors", Integer.class); } private void validateSavedError(int orderId) { String query = "select * from errors where orderid=?"; Map<String, Object> result = jdbcTemplate.queryForMap(query, orderId); Assert.assertEquals(6, result.get("orderid")); assertThat((String)result.get("message"), containsString("Order ID is invalid")); } } This time the test is successful, the error message has been stored to the database. 5.2 Other mechanisms Custom error channel: You can define your error channel and define it as a queue channel instead of the default publish-subscribe channel: <int:poller id="defaultPoller" default="true" fixed-delay="5000" /><int:channel id="errorChannel"> <int:queue capacity="10"/> </int:channel> ErrorMessageExceptionTypeRouter: This Spring Integration specialized router will resolve the channel where the error message will be sent. It bases its decision on the most specific cause of the error: <int:exception-type-router input-channel="errorChannel" default-output-channel="genericErrorChannel"> <int:mapping exception-type="xpadro.spring.integration.exception.InvalidOrderException" channel="invalidChannel" /> <int:mapping exception-type="xpadro.spring.integration.exception.FooException" channel="fooChannel" /> </int:exception-type-router> 6.Conclusion We have learnt what are the different mechanisms for error handling when using Spring Integration. With this base, you will be able to extend it and configure your error handling by implementing transformers to extract the information from the error message, using header enrichers for setting error channel or implementing your own router among other things.   Reference: How error handling works in Spring Integration from our JCG partner Xavier Padro at the Xavier Padró’s Blog blog. ...
mockito-logo

Use Mockito to mock autowired fields

Dependency injection is very powerful feature of Inversion of Control containers like Spring and EJB. It is always good idea to encapsulate injected values into private fields. But encapsulation of autowired fields decreases testability. I like the way how Mockito solved this problem  to mock autowired fields. Will explain it on example. (This blog post expects that you are little bit familiar with Mockito syntax, but it is self-descriptive enough though.) Here is first dependency of testing module. It is Spring singleton bean. This class will be mocked in the test.   @Repository public class OrderDao { public Order getOrder(int irderId){ throw new UnsupportedOperationException("Fail is not mocked!"); } } Here is second dependency of testing class. It is also Spring component. This class will be spied (partially mocked) in test. Its method calculatePriceForOrder will be invoked unchanged. Second method will be stubbed. @Service public class PriceService { public int getActualPrice(Item item){ throw new UnsupportedOperationException("Fail is not mocked!"); }public int calculatePriceForOrder(Order order){ int orderPrice = 0; for (Item item : order.getItems()){ orderPrice += getActualPrice(item); } return orderPrice; } } And here is class under test. It  autowires dependencies above. @Service public class OrderService {@Autowired private PriceService priceService;@Autowired private OrderDao orderDao;public int getOrderPrice(int orderId){ Order order = orderDao.getOrder(orderId); return priceService.calculatePriceForOrder(order); } } Finally here is test example. It uses field level annotations:@InjectMocks – Instantiates testing object instance and tries to inject fields annotated with @Mock or @Spy into private fields of testing object @Mock – Creates mock instance of the field it annotates @Spy – Creates spy for instance of annotated fieldpublic class OrderServiceTest { private static final int TEST_ORDER_ID = 15; private static final int TEST_SHOES_PRICE = 2; private static final int TEST_SHIRT_PRICE = 1;@InjectMocks private OrderService testingObject;@Spy private PriceService priceService;@Mock private OrderDao orderDao;@BeforeMethod public void initMocks(){ MockitoAnnotations.initMocks(this); }@Test public void testGetOrderService(){ Order order = new Order(Arrays.asList(Item.SHOES, Item.SHIRT)); Mockito.when(orderDao.getOrder(TEST_ORDER_ID)).thenReturn(order);//notice different Mockito syntax for spy Mockito.doReturn(TEST_SHIRT_PRICE).when(priceService).getActualPrice(Item.SHIRT); Mockito.doReturn(TEST_SHOES_PRICE).when(priceService).getActualPrice(Item.SHOES);//call testing method int actualOrderPrice = testingObject.getOrderPrice(TEST_ORDER_ID);Assert.assertEquals(TEST_SHIRT_PRICE + TEST_SHOES_PRICE, actualOrderPrice); } } So what happen when you run this test:First of all TestNG framework picks up @BeforeMethod annotation and invokes initMocks method This method invokes special Mockito call (MockitoAnnotations.initMocks(this)) to initialize annotated fields. Without this call, these objects would be null. Common mistake with this approach is to forget this invocation. When all the test fields are populated with desired values, test is called.This example doesn’t include Spring context creation and Spring’s annotations are here only as examples for usage against production code. Test itself doesn’t include  any dependency to Spring and ignores all its annotations. In fact there could be used EJB annotations instead or it can be running against plain (non IoC managed) private fields. Developers tend to think about MockitoAnnotations.initMocks(this) call as unnecessary overhead. But it is actually very handy, because it resets testing object and re-initializes mocks. You can use it for exampleWhen you have various test methods using same annotated instances to ensure that various test runs doesn’t use same recorded behavior When repetitive / parametrized tests are used. For example you can include this call into test  method itself and receive spy object as test parameter (as part of test case). This ability is very sexy in conjunction to TestNG @DataProvider feature (Will explain this in different blog post).@Spy annotated object can be created in two waysAutomatically by Mockito framework if there is default (non-parametrized) constructor Or explicitly initialized (e.g. when there is only non-default constructor)Testing object annotated by @InjectMocks can be also initialized explicitly.Example source code can be downloaded from GitHub.  Reference: Use Mockito to mock autowired fields from our JCG partner Lubos Krnac at the http://lkrnac.net/ blog. ...
spring-logo

Spring Integration – Using RMI Channel Adapters

1.Introduction This article explains how to send and receive messages over RMI using Spring Integration RMI channel adapters. It is composed of the following sections:Implementing the service: The first section focuses on creating and exposing a service. Implementing the client: Shows how to invoke the service using the MessagingTemplate class. Abstracting SI logic: Finally, I’ve added another section explaining how to implement the same client abstracting all Spring Integration code, leaving the client focused on its business logic.You can get the source code at github. 2.Implementing the service This first part is pretty simple. The service is defined through annotations, so it will be autodetected by component scanning. It has a repository injected, which gets the data from an embedded database, as it will be shown in this same section: @Service("defaultEmployeeService") public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeRepository employeeRepository;@Override public Employee retrieveEmployee(int id) { return employeeRepository.getEmployee(id); } } The repository is as follows: @Repository public class EmployeeRepositoryImpl implements EmployeeRepository { private JdbcTemplate template; private RowMapper<Employee> rowMapper = new EmployeeRowMapper(); private static final String SEARCH = "select * from employees where id = ?"; private static final String COLUMN_ID = "id"; private static final String COLUMN_NAME = "name";@Autowired public EmployeeRepositoryImpl(DataSource dataSource) { this.template = new JdbcTemplate(dataSource); }public Employee getEmployee(int id) { return template.queryForObject(SEARCH, rowMapper, id); }private class EmployeeRowMapper implements RowMapper<Employee> { public Employee mapRow(ResultSet rs, int i) throws SQLException { Employee employee = new Employee(); employee.setId(rs.getInt(COLUMN_ID)); employee.setName(rs.getString(COLUMN_NAME));return employee; } } } The following configuration exposes the service over RMI: server-config.xml <context:component-scan base-package="xpadro.spring.integration"/><int-rmi:inbound-gateway request-channel="requestEmployee"/><int:channel id="requestEmployee"/><int:service-activator method="retrieveEmployee" input-channel="requestEmployee" ref="defaultEmployeeService"/><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean><!-- in-memory database --> <jdbc:embedded-database id="dataSource"> <jdbc:script location="classpath:db/schemas/schema.sql" /> <jdbc:script location="classpath:db/schemas/data.sql" /> </jdbc:embedded-database> Let’s focus on the lines with the ‘int’ namespace: The gateway’s function is to separate the plumbing of the messaging system from the rest of the application. In this way, it gets hidden from the business logic. A gateway is bidirectional, so you have:Inbound gateway: Brings a message into the application and waits for a response. Outbound gateway: Invokes an external system and sends the response back to the application.In this example, we are using a RMI inbound gateway. It will receive a message over RMI and send it to the requestEmployee channel, which is also defined here. Finally, the service activator allows you to connect a spring bean to a message channel. Here, it is connected to the requestEmployee channel. The message will arrive to the channel and the service activator will invoke the retrieveEmployee method. Take into account that the ‘method’ attribute is not necessary if the bean has only one public method or has a method annotated with @ServiceActivator. The response will then be sent to the reply channel. Since we didn’t define this channel, it will create a temporary reply channel.3.Implementing the client The client we are going to implement will invoke the service in order to retrieve an employee. To do this, it will use the MessagingTemplate class: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:xpadro/spring/integration/test/config/client-config.xml"}) public class TestRmiClient { @Autowired MessageChannel localChannel;@Autowired MessagingTemplate template;@Test public void retrieveExistingEmployee() { Employee employee = (Employee) template.convertSendAndReceive(localChannel, 2);Assert.assertNotNull(employee); Assert.assertEquals(2, employee.getId()); Assert.assertEquals("Bruce Springsteen", employee.getName()); } } The client uses the messagingTemplate to convert the Integer object to a Message and send it to the local channel. As shown below, there’s an outbound gateway connected to the local channel. This outbound gateway will send the request message over RMI. <int-rmi:outbound-gateway request-channel="localChannel" remote-channel="requestEmployee" host="localhost"/><int:channel id="localChannel"/><bean class="org.springframework.integration.core.MessagingTemplate" /> 4.Abstracting SI logic In the previous section, you may have noticed that the client class which accesses the service has Spring Integration specific logic mixed with its business code:It uses the MessagingTemplate, which is a SI class. It knows about the local channel, which is specific to the messaging systemIn this section, I will implement this same example abstracting the messaging logic, so the client will only care about its business logic. First, let’s take a look at the new client: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:xpadro/spring/integration/test/config/client-gateway-config.xml"}) public class TestRmiGatewayClient { @Autowired private EmployeeService service;@Test public void retrieveExistingEmployee() { Employee employee = service.retrieveEmployee(2);Assert.assertNotNull(employee); Assert.assertEquals(2, employee.getId()); Assert.assertEquals("Bruce Springsteen", employee.getName()); } } We can see now that the client just implement its business logic, without using neither message channels nor messaging template. It will just call the service interface. All the messaging definitions are in the configuration file. <int-rmi:outbound-gateway request-channel="localChannel" remote-channel="requestEmployee" host="localhost"/><int:channel id="localChannel"/><int:gateway default-request-channel="localChannel" service-interface="xpadro.spring.integration.service.EmployeeService"/> client-gateway-config.xml What we did here is add a gateway that will intercept calls to the service interface EmployeeService. Spring Integration will use the GatewayProxyFactoryBean class to create a proxy around the service interface. This proxy will use a messaging template to send the invocation to the request channel and wait for the response.5.Conclusion We have seen how to use Spring Integration to access a service over RMI.  We have also seen that we can not only explicitly send messages using the MessagingTemplate but also do it transparently with GatewayProxyFactoryBean.   Reference: Spring Integration – Using RMI Channel Adapters from our JCG partner Xavier Padro at the Xavier Padró’s Blog blog. ...
software-development-2-logo

Version Numbering Scheme – Yet another approach

Version numbering schemes are probably one of the few things we software engineers have more than sort algorithms. However, there’s always room for one more. While the classic approach of MAJOR.MINOR.PATCH (e.g. 1.8.2) works quite well for libraries or products which are distributed in a broad manner, it is still not as easy as it seems.What is a major change? What a minor? What comes after 1.9? 2.0 or 1.10? There are tons of examples where this classic approach fails, Java being one of the most prominent examples. One the other hand, this approach is almost perfectly suited for libraries, as the rules are quite obvious here:increment minor version for every release (2.4 -> 2.5) increment major version when a backward incompatible change was made (2.4 -> 3.0) increment the patch level for each update, which only fixed bugs but didn’t add functionality (2.4 -> 2.4.1)However, for software which runs in the cloud or is only delivered to a number of customers, the distinction is not always this clear. As we do not distinguish between minor or major updates ( ask our sales guys, each release is a major step forward), we ended up using the build numbers of our Jenkins build server as version number. Although this approach works quite well, there are two problems with it:You need a build server which issues consecutive build numbers Without looking at the build server, you cannot tell the age of a release (How much older is BUILD-51 compared to BUILD-52?)Therefore we now started to switch to another approch for our SIRIUS based products: Inspired by date code placed on ICs, we started to use the same codes for our releases. A date code consists of four digits, the first two being the year and the second two being the week number. So this blog post would have 1406 as version. As we don’t perform more than one release per week, a version number is always unique. Furthermore these numbers are quite short and easy to remember (compared to full dates like foo-20130527). Still they provide a rough information concerning the release date. Now as I said, this scheme is not superior over others. It’s just a good solution for our problem. Use it if you like it, ignore it otherwise!   Reference: Version Numbering Scheme – Yet another approach from our JCG partner Andreas Haufler at the Andy’s Software Engineering Corner blog. ...
enterprise-java-logo

Partitioning SPA Resources and API Implementations in Separate WAR Components

Single Page Applications are quickly gaining traction as a way to implement rich, robust, and mobile friendly web-based applications. Essentially, this requires a shift in application architecture where the entire application user interface is implemented using JavaScript and the server side code supplies a RESTful, JSON-based API for  server side application logic and data access. This model is shown below:A case for separate client and server side deployment components This SPA shift provides user experience and performance benefits as well as an opportunity to completely decouple the user interface from server side logic. Decoupling the UI from application logic is something we do from a code partitioning standpoint by applying the Model View Controller (MVC) pattern. From a deployment application life cycle perspective, they are still coupled – that is, the application is packaged and deployed with static client side elements and server side elements in one component. It seems that the natural instinct is to package both client and server side elements into a single JEE WAR component. This can make the application lifecycle simpler, however, the construction of the application seems to naturally organize developers working on the UI and developers working on the server side API, and even more since two different development languages are used. So, instead of one WAR, separating applications into separate deployable WARs for UI and server side API elements can provide the following benefits:API remains stable for UI development (not a moving target) UI controls when server side API changes are introduced Supports concurrent developer paths of UI and API layers Changes to UI can be tested and moved into QA and production environments without having to retest the API layer Underlying API implementation/technology can be changed without impacting UI UI implementation/technology can change without impacting API Opportunity to introduce UI elements during runtime (exploits JavaScripts dynamic behavior)Here’s a picture of this topology:How? Since UI is implemented with dynamic JavaScript, a JEE WAR component does not have to be used to house UI resources. Any web server such as Apache or the very popular Node.js server can be used. However, enterprises that already have support for JEE will have lifecycle support for WARs in place, and it keeps the door open for using server side dynamic behavior for initial loading of resources, authentication, and integrating or mediating things in a dynamic manner. For example, instead of initial loading of the SPA with index.html, an index.jsp could be used to apply some user/client specific logic to the loading process. Servlet Solution One solution to supporting SPA API/endpoints is to implement a servlet in static content SPA WAR that will redirect API URL routes to a server where the endpoint resides. This is accomplished by defining a servlet in the web.xml with a mapping for API calls to the server. Here’s an example web.xml configuration that handles URIs starting with API: <servlet> <servlet-name>api</servlet-name> <display-name>api</display-name> <servlet-class>com.khs.spa.servlet.ApiServlet</servlet-class> <init-param> <param-name>redirect</param-name> <param-value>localhost:8080/khs-command-ref</param-value> </init-param></servlet><servlet-mapping> <servlet-name>api</servlet-name> <url-pattern>/api/*</url-pattern> </servlet-mapping> The servlet will redirect to the API WAR(s) based upon the URL defined in the redirect initialization parameter value shown above. The API servlet implementation that redirects API HTTP GET/POST/PUT/DELETE requests is shown below: package com.khs.spa.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ApiServlet extends HttpServlet { private static final long serialVersionUID = 4345668988238038540L; private String redirect = null; @Override public void init() throws ServletException { super.init(); // load redirect for servlet redirect = getServletConfig().getInitParameter("redirect"); if (redirect == null) { throw new RuntimeException("redirect value not set in servlet <init-param>"); } } private void doService(HttpServletRequest request, HttpServletResponse response) throws RuntimeException, IOException { // you could do extra stuff here, i.e. logging etc... String path = request.getRequestURI().split(request.getContextPath())[1]; String route = redirect + path; response.sendRedirect(route); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doService(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doService(request, response); } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doService(request, response); } @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doService(request, response); } @Override protected long getLastModified(HttpServletRequest req) { return super.getLastModified(req); } @Override protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doHead(req, resp); } @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doOptions(req, resp); } @Override protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doTrace(req, resp); } } Considerations This approach assumes a stateless API implementation. Since a redirect is involved, if the API WAR is session-based, it will not work unless some kind of federated session mechanism is in place. Authentication and authorization mechanisms can occur either at the client SPA UI-WAR and/or the API layer. Likewise, if multiple API services or enterprise systems need to be accessed for the SPA, they can still be applied in the SPA UI-WAR. Single Page Applications not only allow us to implement rich/responsive user interfaces, but promote the usage of lightweight, easy-to-use restful APIs for data and application logic. This physical runtime decoupling of the user interface makes the notion of a “throwaway” user interface more realistic, and the availability of reusable services via an API layer more achievable.CodeProject  Reference: Partitioning SPA Resources and API Implementations in Separate WAR Components from our JCG partner David Pitt at the Keyhole Software 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