Featured FREE Whitepapers

What's New Here?

google-app-engine-logo

Vaadin App on Google App Engine in 5 Minutes

In this tutorial you’ll learn how to create your very first Vaadin web application, how to run it on a local AppEngine development server and how to deploy it to the Google App Engine infrastructure. And all of that in about 5 to 10 minutes. Yes, if you have the necessary prerequisites installed, you’ll be up and running straight away. Thanks to the power of Maven.This tutorial is in the form of a nicely formatted, 4-page, quick reference card. You can download it straight away, no sign-ups required.The card will guide you through the process of:Setting up your environment. How to run a Vaadin application on the Google App Engine development server. How to deploy that application. How to start customizing the Powered by Reindeer templates.Get started with Vaadin and Google AppEngine right now.Be Sociable, Share!Reference: Tutorial: a Vaadin Application on Google App Engine in 5 Minutes from our JCG partner Peter Backx at the Streamhead blog....
software-development-2-logo

Modelling Is Everything

I’m often asked, “What is the best way to learn about building high-performance systems”? There are many perfectly valid answers to this question but there is one thing that stands out for me above everything else, and that is modelling. Modelling what you need to implement is the most important and effective step in the process. I’d go further and say this principle applies to any development and the rest is just typing Domain Driven Design (DDD) advocates modelling the domain and expressing this model in code as fundamental to the successful delivery and ongoing maintenance of software. I wholeheartedly agree with this. How often do we see code that is an approximation of the problem domain? Code that exhibits behaviour which approximates to what is required via inappropriate abstractions and mappings which just about cope. Those mappings between what is in the code and the real domain are only contained in the developers’ heads and this is just not good enough. When requiring high-performance, code for parts of the system often have to model what is happening with the CPU, memory, storage sub-systems, or network sub-systems. When we have imperfect abstractions on top of these domains, performance can be very adversely affected. The goal of my “ Mechanical Sympathy” blog is to peek at what is under the hood so we can improve our abstractions. What is a Model? A model does not need to be the result of a 3-year exercise producing UML. It can be, and often is best as, people communicating via various means including speech, drawings, illustrations, metaphors, analogies, etc, to build a mental model for shared understanding. If an accurate and distilled understanding can be reached then this model can be turned into code with great results. Infrastructure Domain Models If developers writing a concurrent framework do not have a good model of how a typical cache sub-system works, i.e. it uses message passing to exchange cache lines, then the framework is unlikely to perform well or be correct. If their code drives the cache sub-system with mechanical sympathy and understanding, it is less likely to have bugs and more likely to perform well. It is much easier to predict performance from a sound model when coming from an understanding of the infrastructure for the underlying platform and its published abilities. For example, if you know how many packets per second a network sub-system can handle, and the size of its transfer unit, then it is easy to extrapolate expected bandwidth. With this model based understanding we can test our code for expectations with confidence. I’ve fixed many performance issues whereby a framework treated a storage sub-system as stream-based when it is really a block-based model. If you update part of a file on disk, the block to be updated must be read, the changes applied, and the results written back. Now if you know the system is block based and the boundaries of the blocks, you can write whole blocks back without incurring the read, modify, write back cycle replacing these actions with a single write. This applies even when appending to a file as the last block is likely to have been partially written previously. Business Domain Models The same thinking should be applied to the models we construct for the business domain. If a business process is modelled accurately, then the software will not surprise its end users. When we draw up a model it is important to describe the relationships for cardinality and the characteristics by which they will be traversed. This understanding will guide the selection of data structures to those best suited for implementing the relationships. I often see people use a list for a relationship which is mostly searched by key, for this case a map could be more appropriate. Are the entities at the other end of a relationship ordered? A tree or skiplist implementation may then be a better option. Identity Identity of entities in a model is so important. All models have to be entered in some way, and this normally starts with an entity from which to walk. That entity could be “Customer” by customer ID but could equally be “DiskBlock” by filename and offset in an infrastructure domain. The identity of each entity in the system needs to be clear so the model can be accessed efficiently. If for each interaction with a model we waste precious cycles trying to find our entity as a starting point, then other optimisations can become almost irrelevant. Make identity explicit in your model and, if necessary, index entities by their identity so you can efficiently enter the model for each interaction. Refine as we learn It is also important to keep refining a model as we learn. If the model grows as a series of extensions without refining and distilling, then we end up with a spaghetti mess that is very difficult to manage when trying to achieve predictable performance. Never mind how difficult it is to maintain and support. Everyday we learn new things. Reflect this in the model and keep it up to date. Implement no more, but also no less, than what is needed! The fastest code is code that just does what is needed and no more. Perform the instructions to complete the task and no more. Really fast code is normally not a weird mess of bit-shifting and compiler tricks. It is best to start with something clean and elegant. Then measure to see if you are within performance targets. So often this will be sufficient. Sometimes performance will be a surprise. You then need to apply science to test and measure before jumping to conclusions. A profiler will often tell you where the time is being taken. Once the basic modelling mistakes and assumptions have been corrected, it usually takes just a little mechanical sympathy to reach the performance goal. Unused code is waste. Try not to create it. If you happen to create some, then remove it from your codebase as soon as you notice it. Conclusion When non-functional requirements, such as performance and availability, are critical to success, I’ve found the most important thing is to get the model correct for the domain at all levels. That is, take the principles of DDD and make sure your code is an appropriate reflection of each domain. Be that the domain of business applications, or the domain of interactions with infrastructure, I’ve found modelling is everything. Reference: Modelling Is Everything from our JCG partner Martin Thompson at the Mechanical Sympathy blog....
spring-interview-questions-answers

Introducing Spring Integration

In this article we introduce Spring Integration. If you have not worked with Spring Integration before, it might help to brush up on Enterprise Integration Patterns by Gregor Hohpe. Also I will recommend this excellent introductory article by Josh Long. Context setting In a nutshell, Enterprise Integration Patterns is all about how to get two application (possibly on different technology stacks, different machines, different networks) talk to each other, in order to provide a single business functionality. The challenge is how to ensure that this communication remains transparent to business user, yet reliable and easy for applications. Messaging is one of the patterns. Using this pattern applications can talk to each other frequently, immediately, reliably, and asynchronously, using customizable formats. Applications talk to each other by sending data (called Messages) over virtual pipes (called Channels). This is overly simplistic introduction to the concept, but hopefully enough to make sense of the rest of the article. Spring Integration is not an implementation of any of the patterns, but it supports these patterns, primarily Messaging. The rest of this article is pretty hands on and is an extension of the series on Spring 3. The earlier articles of this series were:Hello World with Spring 3 MVC Handling Forms with Spring 3 MVC Unit testing and Logging with Spring 3 Handling Form Validation with Spring 3 MVCWithout further ado, let’s get started. Bare bones Spring Integration exampleAt the time of writing this article the latest version of Spring is 3.1.2.RELEASE. However, the latest version of Spring Integration is 2.1.3.RELEASE, as found in Maven Central. I was slightly – and in retrospect, illogically – taken aback that the Spring and Spring Integration should have different latest versions, but, hey that’s how it is. This means our pom.xml should have an addition now (if you are wondering where did that come from you need to follow through, at least on a very high level, the Spring 3 series that I have mentioned earlier in the article). File: /pom.xml <!-- Spring integration --> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-core</artifactId> <version>2.1.3.RELEASE</version> </dependency> This one dependency in the pom, now allows my application to send message over channels. Notice that now we are referring to message and channels in the realm of Spring Integration, which is not necessarily exactly same as the same concepts referred earlier in this article in the realm of Enterprise Integration Patterns. It is probably worth having a quick look at the Spring Integration Reference Manual at this point. However, if you are just getting started with Spring Integration, you are perhaps better off following this article for the moment. I would recommend you get your hands dirty before returning to reference manual, which is very good but also very exhaustive and hence could be overwhelming for a beginner. To keep things simple, and since I generally try to do test first approach (wherever possible), let us try and write some unit tests to create message, send it over a channel and then receive it. I have blogged here about how to use JUnit and Logback in Spring 3 applications. Continuing with the same principle, assuming that we are going to write a HelloWorldTest.java, let’s set up the Spring configuration for the test. File: \src\test\resources\org\academy\integration\HelloWorldTest-context.xml <?xml version='1.0' encoding='UTF-8'?> <beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:p='http://www.springframework.org/schema/p' xmlns:int='http://www.springframework.org/schema/integration' xsi:schemaLocation='http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/integrationhttp://www.springframework.org/schema/integration/spring-integration-2.1.xsd'><int:channel id='inputChannel'></int:channel><int:channel id='outputChannel'> <int:queue capacity='10' /> </int:channel><int:service-activator input-channel='inputChannel' output-channel='outputChannel' ref='helloService' method='greet' /><bean id='helloService' class='org.academy.integration.HelloWorld' /></beans> So, what did we just do? We have asked Spring Integration to create a ‘inputChannel’ to send messages to. A ‘outputChannel’ to read messages from. We have also configured for all messages on ‘inputChannel’ to be handed over to a ‘helloService’. This ‘helloService’ is an instance of org.academy.integration.HelloWorld class, which should be equipped to do something to the message. After that we have also configured that the output of the ‘helloService’ i.e. the modified message in this case to be handed over to the ‘outputChannel’. Simple, isn’t it? Frankly, when I had a worked with Spring Integration a few years ago for the first time, I found this all a bit confusing. It does not make much sense to me till I see this working. So, let’s keep going. Let’s add our business critical HelloWorld class. File: /src/main/java/org/academy/integration/HelloWorld.java package org.academy.integration;import org.slf4j.Logger; import org.slf4j.LoggerFactory;public class HelloWorld { private final static Logger logger = LoggerFactory .getLogger(HelloWorld.class); public String greet(String name){ logger.debug('Greeting {}', name); return 'Hello ' + name; } }As, you can see, given a ‘name’ it return ‘Hello {name}’. Now, let’s add the unit test to actually put this in action. File: /src/test/java/org/academy/integration/HelloWorldTest.java package org.academy.integration;import static org.junit.Assert.*;import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.MessageChannel; import org.springframework.integration.core.PollableChannel; import org.springframework.integration.message.GenericMessage; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class HelloWorldTest { private final static Logger logger = LoggerFactory .getLogger(HelloWorldTest.class);@Autowired @Qualifier('inputChannel') MessageChannel inputChannel;@Autowired @Qualifier('outputChannel') PollableChannel outputChannel;@Test public void test() { inputChannel.send(new GenericMessage<String>('World')); assertEquals(outputChannel.receive().getPayload(), 'Hello World'); logger.debug('Checked basic Hello World with Spring Integration'); }}Although not mandatory, I find it easier to use the following logback setting. Feel free to use it, if you fancy. File: /src/main/resources/logback.xml <?xml version='1.0' encoding='UTF-8'?> <configuration> <appender name='CONSOLE' class='ch.qos.logback.core.ConsoleAppender'> <encoder> <pattern>%d %5p | %t | %-55logger{55} | %m %n</pattern> </encoder> </appender><logger name='org.springframework'> <level value='ERROR' /> <!-- level value='INFO' /> --> <!-- level value='DEBUG' /> --> </logger><root> <level value='DEBUG' /> <appender-ref ref='CONSOLE' /> </root> </configuration> Now, simply type ‘mvn -e clean install’ (or use m2e plugin) and you should be able to run the unit test and confirm that given string ‘World’ the HelloWorld service indeed returns ‘Hello World’ over the entire arrangement of channels and messages. Again, something optional but I highly recommend, is to run ‘mvn -e clean install site’. This – assuming you have correctly configured some code coverage tool (cobertura in my case) will give you a nice HTML report showing the code coverage. In this case it would be 100%. I have blogged a series on code quality which deals this subject in more detail, but to cut long story short, it is very important for me to ensure that whatever coding practice / framework I use and recommend use, complies to some basic code quality standards. Being able to unit test and measure that is one such fundamental check that I do. Needless to say, Spring in general (including Spring integration) passes that check with flying colours. ConclusionThat’s it for this article. In the next article, we will see how to insulate the application code from the Spring Integration specific code that we have in our current JUnit test i.e. inputChannel.send(…) etc. Till then, happy coding. Suggested further reading … Here are the links to earlier articles in this series:Hello World with Spring 3 MVC Handling Forms with Spring 3 MVC Unit testing and Logging with Spring 3 Handling Form Validation with Spring 3 MVCThese are excellent material that I can recommend:Getting started with Spring Integration Sample codes with Spring Integration Spring Integration – Session 1 – Hello World Spring Integration – Session 2 – More Hello WorldsContinue to Spring Integration with Gateways Reference: Introducing Spring Integration from our JCG partner Partho at the Tech for Enterprise blog....
spring-interview-questions-answers

Spring Integration with Gateways

This is the second article of the series on Spring Integration. This article builds on top of the first article where we introduced Spring Integration. Context setting In the first article, we created a simple java application whereA message was sent over a channel, It was intercepted by a service i.e. POJO and modified. It was then sent over a different channel The modified message was read from the channel and displayed.However, in doing this – keeping in mind that we were merely introducing the concepts there – we wrote some Spring specific code in our application i.e. the test classes. In this article we will take care of that and make our application code as insulated from Spring Integration api as possible. This is done by, what Spring Integration calls gateways. Gateways exist for the sole purpose of abstracting messaging related ‘plumbing’ code away from ‘business’ code. The business logic might really not care whether a functionality is being achieved be sending a message over a channel or by making a SOAP call. This abstraction – though logical and desirable – have not been very practical, till now. It is probably worth having a quick look at the Spring Integration Reference Manual at this point. However, if you are just getting started with Spring Integration, you are perhaps better off following this article for the moment. I would recommend you get your hands dirty before returning to reference manual, which is very good but also very exhaustive and hence could be overwhelming for a beginner. The gateway could be a POJO with annotations (which is convenient but in my mind beats the whole purpose) or with XML configurations (can very quickly turn into a nightmare in any decent sized application if unchecked). At the end of the day it is really your choice but I like to go the XML route. The configuration options for both styles are detailed out in this section of the reference implementation. Spring Integration with Gateways So, let’s create another test with gateway throw in for our HelloWorld service (refer to the first article of this series for more context). Let’s start with the Spring configuration for the test. File: src/test/resources/org/academy/integration/HelloWorld1Test-context.xml <?xml version='1.0' encoding='UTF-8'?> <beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:p='http://www.springframework.org/schema/p' xmlns:int='http://www.springframework.org/schema/integration' xsi:schemaLocation='http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/integrationhttp://www.springframework.org/schema/integration/spring-integration-2.1.xsd'><int:channel id='inputChannel'></int:channel><int:channel id='outputChannel'> <int:queue capacity='10' /> </int:channel><int:service-activator input-channel='inputChannel' output-channel='outputChannel' ref='helloService' method='greet' /><bean id='helloService' class='org.academy.integration.HelloWorld' /><int:gateway service-interface='org.academy.integration.Greetings' default-request-channel='inputChannel' default-reply-channel='outputChannel'></int:gateway></beans> In this case, all that is different is that we have added a gateway. This is an interface called org.academy.integration.Greetings. It interacts with both ‘inputChannel’ and ‘outputChannel’, to send and read messages respectively. Let’s write the interface. File: /src/main/java/org/academy/integration/Greetings.java package org.academy.integration;public interface Greetings { public void send(String message);public String receive();} And then we add the implementation of this interface. Wait. There is no implementation. And we do not need any implementation. Spring uses something called GatewayProxyFactoryBean to inject some basic code to this gateway which allows it to read the simple string based message, without us needing to do anything at all. That’s right. Nothing at all. Note – You will need to add more code for most of your production scenarios – assuming you are not using Spring Integration framework to just push around strings. So, don’t get used to free lunches. But, while it is here, let’s dig in. Now, lets write a new test class using the gateway (and not interact with the channels and messages at all). File: /src/test/java/org/academy/integration/HelloWorld1Test.java package org.academy.integration;import static org.junit.Assert.*;import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class HelloWorld1Test {private final static Logger logger = LoggerFactory .getLogger(HelloWorld1Test.class);@Autowired Greetings greetings;@Test public void test() { greetings.send('World'); assertEquals(greetings.receive(), 'Hello World'); logger.debug('Spring Integration with gateways.'); }}Our test class is much cleaner now. It does not know about channels, or messages or anything related to Spring Integration at all. It only knows about a greetings instance – to which it gave some data by .send() method – and got modified data back by .receive() method. Hence, the business logic is oblivious of the plumbing logic, making for a much cleaner code. Now, simply type ‘mvn -e clean install’ (or use m2e plugin) and you should be able to run the unit test and confirm that given string ‘World’ the HelloWorld service indeed returns ‘Hello World’ over the entire arrangement of channels and messages. Again, something optional but I highly recommend, is to run ‘mvn -e clean install site’. This – assuming you have correctly configured some code coverage tool (cobertura in my case) will give you a nice HTML report showing the code coverage. In this case it would be 100%. I have blogged a series on code quality which deals this subject in more detail, but to cut long story short, it is very important for me to ensure that whatever coding practice / framework I use and recommend use, complies to some basic code quality standards. Being able to unit test and measure that is one such fundamental check that I do. Needless to say, Spring in general (including Spring integration) passes that check with flying colours. ConclusionThat’s it for this article. Happy coding. Suggested further reading … Here are the links to earlier articles in this series:Hello World with Spring 3 MVC Handling Forms with Spring 3 MVC Unit testing and Logging with Spring 3 Handling Form Validation with Spring 3 MVC Introducing Spring IntegrationThese are excellent material that I can recommend:Getting started with Spring Integration Sample codes with Spring Integration Spring Integration – Session 1 – Hello World Spring Integration – Session 2 – More Hello WorldsReference: Spring Integration with Gatways from our JCG partner Partho at the Tech for Enterprise blog....
spring-interview-questions-answers

Spring security 3 Ajax login – accessing protected resources

I have seen some blogs about Spring Security 3 Ajax login, however I could not find any that tackles how to invoke Ajax based login, where a protected resource is being accessed in Ajax by an anonymous user. The problem – The web application enables anonymous access to certain parts and certain parts are protected resources which require the user to login. When an anonymous user accesses protected resources (via Http Get / Post), Spring Security automatically invokes the login page and after a successful authentication, redirects to the required resource/page. However, if the protected resource is being accessed in Ajax, the login page will not appear correctly (will be set on part of the page). The 302 code (redirect to login page) will not function as expected in Ajax. Please note that this is NOT the same as initiating an Ajax login screen (e.g. when user press on the login button and a popup with user/password fields is being invoked). So – how can we have Spring Security 3 handle access to protected resources both with “regular” HTTP Post(FORM based authentication) AND Ajax calls, including a redirect to the required resource after successful authentication? So, this blog post has two protection layers/parts: 1. Spring Security 3 standard FORM based authentication 2. Configure/extends Spring Security 3. and the app to support also Ajax access to protected resources. Regarding part 1 – there are many references about the issue. No need to elaborate. Regarding part 2 – Requires the following: 1. Configure Spring Security 3 to enable Ajax based login. 2. Configure client Ajax calls to protected resources to handle request for authentication. 3. Re-execution of functions to simulate the automatic user original method invocation after successful login (as it happens in the FORM based login) The below diagram describes a detailed flow and should help follow the client/sever communication.Handling protected resource access via AjaxLets discuss the diagram: The flow starts with an anonymous user Ajax request to a protected resource (1). In this case the user wants to add an item to the shopping cart. The addItem method is a protected resource, which is protected via Spring Security (@pre_authorize(“SOME_ROLE”)) (2). This causes the Spring Secutiry filter (3) to send the login FORM with HTTP code 302 (i.e. redirect to that page). Now, since this is an Ajax call, it will not handle the request well, so here comes the part that takes the login FORM, put it aside, and invoke Ajax based login instead (4): The client Ajax method (which invoked the Ajax addItem method) checks whether it is a form based login or any other reply. If it is a FORM based login, it will call a dialog modal (5) that will try to login in Ajax. Spring will handle the Ajax login authentication (6) and return an appropriate message to the client. The client, if the message was successful, will re-execute the original function, which tried to access the protected resource (e.g. addItem in our example). Let us see how it all fits in our code: Steps #1, #4 – Client side which accesses protected resources and checks if a login is required //JavaScript method - Ajax call to protected resource (#1 in flow diagram) function addItem(itemId) { $.ajax({ url: '/my_url/order/addItem', type: 'POST', data: ({orderItemId : itemId,...}), success: function(data) {//construct a callback string if user is not logged in. var cllbck = 'addItem('+itemId +')';//Client check if login required //(#4 in flow diagram) if (verifyAuthentication(data,cllbck)){ // in here => access to protected resource was ok // show message to user, "item has been added..." } }); }Steps #2, #3 – is a regular Spring Security configuration. Plenty of resources out there. Step #4 – Client checks if login is required: function verifyAuthentication(data, cllBackString){ //naive check - I put a string in the login form, so I check for existance if (isNaN(data) && (data.indexOf("login_hidden_for_ajax")!= -1)){ //if got here then data is a loginform => login required //set callback in ajax login form hidden input $("#my_callback").val(cllBackString); //show ajax login //Get the window height and width var winH = $(window).height(); var winW = $(window).width(); //Set the popup window to center $("#ajaxLogin").css('top', winH/2-$("#ajaxLogin").height()/2); $("#ajaxLogin").css('left', winW/2-$("#ajaxLogin").width()/2); $("#ajaxLogin").fadeIn(2000); return false; } // data is not a login form => return true to continue with function processing return true; } Step #5, #7 – the Ajax login FORM utilizes the following Ajax login: function ajaxLogin(form, suffix){ var my_callback = form.my_callback.value; // The original function which accessed the protected resource var user_pass = form.j_ajax_password.value; var user_name = form.j_ajax_username.value;//Ajax login - we send credentials to j_spring_security_check (as in form based login $.ajax({ url: "/myContextURL/j_spring_security_check", data: { j_username: user_name , j_password: user_pass }, type: "POST", beforeSend: function (xhr) { xhr.setRequestHeader("X-Ajax-call", "true"); }, success: function(result) { //if login is success, hide the login modal and //re-execute the function which called the protected resource //(#7 in the diagram flow) if (result == "ok") { $("#ajax_login_error_"+ suffix).html(""); $('#ajaxLogin').hide(); if (my_callback!=null && my_callback!='undefined' && my_callback!=''){ eval(my_callback.replace(/_/g,'"')); } return true; }else { $("#ajax_login_error_"+ suffix).html('<span class="alert display_b clear_b centeralign">Bad user/password</span>') ; return false; } }, error: function(XMLHttpRequest, textStatus, errorThrown){ $("#ajax_login_error_"+ suffix).html("Bad user/password") ; return false; } }); } We need to set Spring to support Ajax login (#6): Set Spring Security xml configuration: <beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/security" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd"> <http auto-config="false" use-expressions="true"> <intercept-url access="hasRole('ROLE_ADMIN')" pattern="/admin**"> <intercept-url filters="none" pattern="/**"> <intercept-url access="permitAll" pattern="/signin/**"> <form-login authentication-failure-handler-ref="ajaxAuthenticationFailureHandler" authentication-success-handler-ref="ajaxAuthenticationSuccessHandler" login-page="/common/authentication/login"> <logout invalidate-session="true" logout-success-url="/common/authentication/logout"> <custom-filter before="LOGOUT_FILTER" ref="logoutFilter"> </custom-filter></logout></form-login></intercept-url></intercept-url></intercept-url></http> ... </beans:beans>Define a handler for login success: @Component("ajaxAuthenticationSuccessHandler") public class AjaxAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { public AjaxAuthenticationSuccessHandler() { }@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { HttpSession session = request.getSession(); DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) session.getAttribute(WebAttributes.SAVED_REQUEST); //check if login is originated from ajax call if ("true".equals(request.getHeader("X-Ajax-call"))) { try { response.getWriter().print("ok");//return "ok" string response.getWriter().flush(); } catch (IOException e) { //handle exception... } } else { setAlwaysUseDefaultTargetUrl(false); ... } } }Define a handler for login failure – the same as success, but the string is “not-ok”. I know some of the code here is not the best practice so I would like to hear what you think. Please post me if you can see a way to improve the process or make it more generic. Acknowledgment : Diagram was done via gliffy - online diagram tool Reference: Spring security 3 Ajax login – accessing protected resources from our JCG partner Gal Levinsky at the Gal Levinsky’s blog blog....
java-logo

Five useful ways to sorting in java

A rapid overview of java sorting :                     normal sort of list : private static List VEGETABLES = Arrays.asList("apple", "cocumbers", "blackberry"); Collections.sort(VEGETABLES);output: apple, blackberry, cocumbers Reverse sorting: private static List VEGETABLES = Arrays.asList("apple", "cocumbers", "blackberry"); Collections.sort(VEGETABLES, Collections.reverseOrder()); output: cocumbers, blackberry, apple with custom comparator: private class StringComparator implements Comparator { public int compare(Object o1, Object o2) { String so1 = (String) o1; String so2 = (String) o2; return so1.compareTo(so2); } } private static List VEGETABLES = Arrays.asList("apple", "cocumbers", "blackberry"); Collections.sort(VEGETABLES, new StringComparator()); output: apple, blackberry, cocumbers Elements sorting: private class Element implements Comparable { private String name; private Double atomicMass; @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Element"); sb.append("{name='").append(name).append('\''); sb.append(", atomicMass=").append(atomicMass); sb.append('}'); return sb.toString(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getAtomicMass() { return atomicMass; } public void setAtomicMass(Double atomicMass) { this.atomicMass = atomicMass; } public Element(String name, String mass, double atomicMass) { this.name = name; this.atomicMass = atomicMass; } public int compareTo(Element o) { return this.getAtomicMass().compareTo(o.getAtomicMass()); } } ArrayList<Element> elements = new ArrayList<Element>(); elements.add(new Element("Hydrogen", "H", 1.00794)); // Hydrogen 1.00794 amu Atomic Mass elements.add(new Element("Iron", "Fe", 55.845)); elements.add(new Element("Lithium", "Li", 6.941)); elements.add(new Element("Lead", "Pb", 207.2)); elements.add(new Element("Magnesium", "Mg", 24.305)); Collections.sort(elements); // Sort by Element output: Element{name='Hydrogen', atomicMass=1.00794} Element{name='Lithium', atomicMass=6.941} Element{name='Magnesium', atomicMass=24.305} Element{name='Iron', atomicMass=55.845} Element{name='Lead', atomicMass=207.2} Chronological sorting: SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy", Locale.US); try { ArrayList<Date> holidays = new ArrayList<Date>(); holidays.add(formatter.parse("May 31, 2010")); // Memorial Day holidays.add(formatter.parse("July 4, 2010")); // Independence Day holidays.add(formatter.parse("February 15, 2010")); // Presidents Day holidays.add(formatter.parse("September 6, 2010")); // Labor Day holidays.add(formatter.parse("December 24, 2010")); // Thanksgiving Day holidays.add(formatter.parse("July 5, 2010")); // federal employees extra day off for July 4th holidays.add(formatter.parse("January 18, 2010")); // Martin Luther King Day holidays.add(formatter.parse("November 25, 2010")); // federal employees extra day off for Christmas holidays.add(formatter.parse("October 11, 2010")); // Columbus Day holidays.add(formatter.parse("December 25, 2010")); // Christmas Day holidays.add(formatter.parse("January 1, 2010")); // New Year's Day Collections.sort(holidays); // Native sort for Date is chronological } catch (ParseException e) { e.printStackTrace(); } output: sorted:[Fri Jan 01 00:00:00 CET 2010, Mon Jan 18 00:00:00 CET 2010, Mon Feb 15 00:00:00 CET 2010, Mon May 31 00:00:00 CEST 2010, Sun Jul 04 00:00:00 CEST 2010, Mon Jul 05 00:00:00 CEST 2010, Mon Sep 06 00:00:00 CEST 2010, Mon Oct 11 00:00:00 CEST 2010, Thu Nov 25 00:00:00 CET 2010, Fri Dec 24 00:00:00 CET 2010, Sat Dec 25 00:00:00 CET 2010] You can view the complete simple class below: package com.tommyalf.personal.sorting;import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;/** * Created by IntelliJ IDEA. * User: tommyalf * Date: 1-dic-2010 * Time: 22.40.49 */ public class SortDemo { private static List VEGETABLES = Arrays.asList("apple", "cocumbers", "blackberry");;public static void main(String args[]) { SortDemo sd = new SortDemo(); sd.normalSort(); sd.reverseSort(); sd.stringComparator(); sd.elementsSort(); sd.chronologicalSort(); }private void chronologicalSort() { SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy", Locale.US); try { ArrayList<Date> holidays = new ArrayList<Date>(); holidays.add(formatter.parse("May 31, 2010")); // Memorial Day holidays.add(formatter.parse("July 4, 2010")); // Independence Day holidays.add(formatter.parse("February 15, 2010")); // Presidents Day holidays.add(formatter.parse("September 6, 2010")); // Labor Day holidays.add(formatter.parse("December 24, 2010")); // Thanksgiving Day holidays.add(formatter.parse("July 5, 2010")); // federal employees extra day off for July 4th holidays.add(formatter.parse("January 18, 2010")); // Martin Luther King Day holidays.add(formatter.parse("November 25, 2010")); // federal employees extra day off for Christmas holidays.add(formatter.parse("October 11, 2010")); // Columbus Day holidays.add(formatter.parse("December 25, 2010")); // Christmas Day holidays.add(formatter.parse("January 1, 2010")); // New Year's Day System.out.println("before sort:" + holidays); Collections.sort(holidays); // Native sort for Date is chronological System.out.println("sorted:" + holidays); } catch (ParseException e) { e.printStackTrace(); } }private void elementsSort() { ArrayList<Element> elements = new ArrayList<Element>(); elements.add(new Element("Hydrogen", "H", 1.00794)); // Hydrogen 1.00794 amu Atomic Mass elements.add(new Element("Iron", "Fe", 55.845)); elements.add(new Element("Lithium", "Li", 6.941)); elements.add(new Element("Lead", "Pb", 207.2)); elements.add(new Element("Magnesium", "Mg", 24.305)); Collections.sort(elements); // Sort by Element System.out.print("Elements sort by atomicMass value:"); for ( Element e : elements ) { System.out.println(e); } }private void stringComparator() { Collections.sort(VEGETABLES, new StringComparator()); System.out.print("StringComparator:"); printList(VEGETABLES); }private void reverseSort() { Collections.sort(VEGETABLES, Collections.reverseOrder()); System.out.print("ReverseSort:"); printList(VEGETABLES); }private void normalSort() { Collections.sort(VEGETABLES); System.out.print("NormalSort:"); printList(VEGETABLES); }private void printList(List vegetables) { for (int i = 0, n = vegetables.size(); i < n; i++) { if (i != 0) { System.out.print(", "); } System.out.print(VEGETABLES.get(i)); } System.out.println(); }private class StringComparator implements Comparator { public int compare(Object o1, Object o2) { String so1 = (String) o1; String so2 = (String) o2; return so1.compareTo(so2); } }private class Element implements Comparable<Element> { private String name; private Double atomicMass;@Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Element"); sb.append("{name='").append(name).append('\''); sb.append(", atomicMass=").append(atomicMass); sb.append('}'); return sb.toString(); }public String getName() { return name; }public void setName(String name) { this.name = name; }public Double getAtomicMass() { return atomicMass; }public void setAtomicMass(Double atomicMass) { this.atomicMass = atomicMass; }public Element(String name, String mass, double atomicMass) { this.name = name; this.atomicMass = atomicMass; }public int compareTo(Element o) { return this.getAtomicMass().compareTo(o.getAtomicMass()); } } } Reference: Five useful ways to sorting in java from our JCG partner Tommy Alf at the Tommy Alf – blog blog. ...
jannocessor-logo

Java code generation with JAnnocessor

In this article I will show you how to generate code with JAnnocessor framework created by Nikolche Mihajlovski. First time I met JAnnocessor on GeeCON 2012 conference during Nikolche’s speech: “Innovative and Pragmatic Java Source Code Generation” (slides). Afterwards I used it successfully in one of my projects. There are almost no resources about this framework so I hope my article will be useful for those who are interested in using it or just are looking for brand new toy for their project. Background Every Java developer uses some sort of code generation tool on a daily basis. Setters, getters, trivial constructors, toString – all of these is just a boilerplate code. Usually we generate it with our favorite IDE’s help. I can’t really imagine coding it manually and because Java is a static language we will never be able to skip this process. Those trivial examples of code generation provided by all modern IDEs are not the only situations when code generation is useful. There are many modern frameworks generate some code to help us to write more reliable code and do it faster. I think the most well known examples are QueryDSL and JPA2 Metamodel Generator that creates objects used to perform type-safe database queries. There are also other situations – not so well supported by IDE – where we could use code generation. Usually it might be helpful in generating:builder facade DTOs and mappers from domain objects to DTOsThese are only examples. For some projects there might be something project specific where we can’t use any existing code generation tool and we have to write our own. How to do that? With Java APT – Annotation Processing Tool. Few words about Java APT Annotation Processing Tool was introduced in Java 1.5 and provides low level API for processing annotated classes. It is a base for most (maybe all?) existing code generation frameworks and because of really low level API I don’t recommend using plain Java APT if you just want to generate some classes. How creepy is code generation with APT look at example on apt-jelly (another code generation tool) page. Instead of using plain Java APT – you can use one of existing frameworks. Recently I’ve attended to conference talk about interesting JAnnocessor that seems to do its job pretty well. Hello JAnnocessor JAnnocessor is a quite new framework made by Nikolche Mihajlovski. How is it different from APT? Here is how author what author says: JAnnocessor is built on top of Java APT, encapsulating the Java source code model in a rich and convenient high-level domain model that serves as a good target for expressive matching and transformation. JAnnocessor comes with couple of built in processors: builder, dto, facade and mapper. If you need custom functionality you can easily write it by your own. There is one big drawback – very very poor documentation. Actually there is almost no documentation at all. In wiki you won’t find too much and what is even worse – you won’t find Javadocs in framework classes neither. Although there is Getting Started Guide written by author I miss there some points so I will guide you through basics step by step.   Maven setup We will use JAnnocessor only during compile phase so there is no need to add it into our application package – we set scope to provided <dependency> <groupId>com.googlecode.jannocessor</groupId> <artifactId>jannocessor</artifactId> <version>0.7.2</version> <scope>provided</scope> </dependency>Next part is annotation processing plugin. Although Getting Started Guide recommends to use jannocessor-maven-plugin I was forced to do it “old fashioned way” with maven-processor-plugin because I missed some configuration options. Into build/plugins section we add: <plugin> <groupId>org.bsc.maven</groupId> <artifactId>maven-processor-plugin</artifactId> <version>2.0.4</version> <executions> <execution> <id>generate-code</id> <goals> <goal>process</goal> </goals> <phase>compile</phase><configuration> <processors> <processor>org.jannocessor.processor.JannocessorProcessor</processor> </processors><systemProperties> <logback.configurationFile>${project.basedir}/etc/jannocessor-logback.xml</logback.configurationFile> </systemProperties> <options> <templates.path>${project.basedir}/src/main/resources</templates.path> </options> <defaultOutputDirectory>${project.basedir}/target/generated-sources/</defaultOutputDirectory> </configuration> </execution> </executions> </plugin>processors – tells maven-processor-plugin which class performs annotation processing – don’t change it configuration/logback.configurationFile – that’s optional. JAnnocessor uses inside logback for logging and if you do so as well in your project and you have logback.xml in classpath it is going to be used by JAnnocessor. I recommend to write separate logging configuration for JAnnocessor to avoid possible problems (for example if you use janino conditionals). jannocessor-logback.xml can be as simple as: <?xml version="1.0" encoding="UTF-8"?> <configuration><appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%-30(%date) %-5level %logger{0} %msg%n</pattern> </encoder> </appender><root level="error"> <appender-ref ref="console"/> </root></configuration>options/templates.path – probably you will use custom JAnnocessor templates. That line can be removed if you won’t defaultOutputDirectory – that’s important – by default generated classes are added to src/main/java – which is in my opinon very bad idea. Remember that all generated classes are recreated every Maven build and all modifications made by hand are lost. That’s why generated classes should be places in /target/generated-sources/ or /target/generated-test-sources/Builder generation In this example I will use built-in generator to generate builder class for my simple POJO. First of all we need new annotation to mark classes for whom we want to generate builder. It can be as simple as: package pl.maciejwalkowiak.jannocessor.domain;public @interface GenerateBuilder { }Our sample POJO: package pl.maciejwalkowiak.jannocessor.domain;@GenerateBuilder public class Person { private String firstName; private String lastName; private Integer age;public String getFirstName() { return firstName; }public void setFirstName(String firstName) { this.firstName = firstName; }public String getLastName() { return lastName; }public void setLastName(String lastName) { this.lastName = lastName; }public Integer getAge() { return age; }public void setAge(Integer age) { this.age = age; } }Next important part is to tell JAnnocessor what has to be generated. In order to do that we need to create specific class in specific package: org.jannocessor.config.Processors. I couldn’t find a way to make it configurable so that configuration could be in our project’s package. In configuration we specify where created classes should be placed: pl.maciejwalkowiak.jannocessor.domain.builder and where are base bean classes: pl.maciejwalkowiak.jannocessor.domain. Last parameter means if we want to use debug mode – for now it isn’t important. package org.jannocessor.config;import pl.maciejwalkowiak.jannocessor.domain.GenerateBuilder;import org.jannocessor.extra.processor.BuilderGenerator; import org.jannocessor.model.structure.JavaClass; import org.jannocessor.processor.annotation.Annotated; import org.jannocessor.processor.annotation.Types;public class Processors {@Annotated(GenerateBuilder.class) @Types(JavaClass.class) public BuilderGenerator generateBuilder() { return new BuilderGenerator("pl.maciejwalkowiak.jannocessor.domain.builder", "pl.maciejwalkowiak.jannocessor.domain", false); } }Let’s run it In order to run it we just need to execute mvn compile. In target/generated-sources/pl/maciejwalkowiak/jannocessor/domain/builder/ we will find class PersonBuilder: package pl.maciejwalkowiak.jannocessor.domain.builder;import pl.maciejwalkowiak.jannocessor.domain.Person; import javax.annotation.Generated;/** * Generated by JAnnocessor */ @Generated("Easily with JAnnocessor") public class PersonBuilder {private String firstName;private String lastName;private Integer age;public PersonBuilder firstName(String firstName) { this.firstName = firstName; return this; }public PersonBuilder lastName(String lastName) { this.lastName = lastName; return this; }public PersonBuilder age(Integer age) { this.age = age; return this; }public Person build() { Person instance = new Person();instance.setFirstName(firstName); instance.setLastName(lastName); instance.setAge(age);return instance; }}Thanks to builder class we have fluent interface for creating Person objects: Person person = new PersonBuilder().firstName("John").lastName("Doe").age(25).build();Creating our own generator For creating custom generators JAnnocessor provides rich API and couple of examples. Unfortunately there is no guide or tutorial available. For this article I wanted to write quickly generator for FEST Assert 2.x but after some time digging in JAnnocessor source code I gave up. Instead I will just show concept. In order to code custom generator you just need to create class that inherits from org.jannocessor.extra.processor.AbstractGenerator. public class MyCustomGenerator extends AbstractGenerator<AbstractJavaClass> {public MyCustomGenerator(String destPackage, boolean inDebugMode) { super(destPackage, inDebugMode); }@Override protected void generateCodeFrom(PowerList<AbstractJavaClass> models, ProcessingContext context) { // .... } }PowerList<AbstractJavaClass> models represents collection of all classes annotated with custom annotation. Then you have access to all class fields, methods, implemented interfaces etc. The only thing that I missed is rich access to classes superclass. In order to get superclass’ fields I had to use Java Reflection API. If you want to write custom generator I encourage you to look into examples like BuilderGenerator. It’s not much but it will be definitely helpful.   Summary In this post I’ve shown how to setup and use JAnnocessor. Although I think its good and possibly very useful library, lack of documentation makes it impossible to use it in real serious project. I hope Nikolche will write good docs or build community around project that will do it. I also hope that project will move to github. It somehow become a standard so if author want’s to build community around it – I think it is the only right move. Nevertheless I asked him about that and at least for now he doesn’t have any plans to do so. Reference: Java code generation with JAnnocessor from our JCG partner Maciej Walkowiak at the Software Development Journey blog....
software-development-2-logo

Fixing Bugs – if you can’t reproduce them, you can’t fix them

‘Generally, if you can’t reproduce it, it’s almost impossible to fix’. Anonymous programmer, Practices of Software Maintenance, Janice Singer Fixing a problem usually starts with reproducing it – what Steve McConnell calls “ stabilizing the error”. Technically speaking, you can’t be sure you are fixing the problem unless you can run through the same steps, see the problem happen yourself, fix it, and then run through the same steps and make sure that the problem went away. If you can’t reproduce it, then you are only guessing at what’s wrong, and that means you are only guessing that your fix is going to work. But let’s face it – it’s not always practical or even possible to reproduce a problem. Lots of bug reports don’t include enough information for you to understand what the hell the problem actually was, never mind what was going on when the problem occurred – especially bug reports from the field. Rahul Premraj and Thomas Zimmermann found in The Art of Collecting Bug Reports (from the book Making Software), that the two most important factors in determining whether a bug report will get fixed or not are:Is the description well-written, can the programmer understand what was wrong or why the customer thought something was wrong? Does it include steps to reproduce the problem, even basic information about what they were doing when the problem happened?It’s not a lot to ask – from a good tester at least. But you can’t reasonably expect this from customers. There are other cases where you have enough information, but don’t have the tools or expertise to reproduce a problem – for example, when a pen tester has found a security bug using specialist tools that you don’t have or don’t understand how to use. Sometimes you can fix a problem without being able to see it happen in front of you, come up with a theory on your own, trusting your gut – especially if this is code that you recently worked on. But reproducing the problem first gives you the confidence that you aren’t wasting your time and that you actually fixed the right thing. Trying to reproduce the problem should almost always be your first step.What’s involved in reproducing a bug? What you want to do is to find, as quickly as possible, a simple test that consistently shows the problem, so that you can then run a set of experiments, trace through the code, isolate what’s wrong, and prove that it went away after you fixed the code. The best explanation that I’ve found of how to reproduce a bug is in Debug It! where Paul Butcher patiently explains the pre-conditions (identifying the differences between your test environment and the customer’s environment, and trying to control as many of them as possible), and then how to walk backwards from the error to recreate the conditions required to make the problem happen again. Butcher is confident that if you take a methodical approach, you will (almost) always be able to reproduce the problem successfully. In Why Programs Fail: A guide to Systematic Debugging, Andreas Zeller, a German Comp Sci professor, explains that it’s not enough just to make the problem happen again. Your goal is to come up with the simplest set of circumstances that will trigger the problem – the smallest set of data and dependencies, the simplest and most efficient test(s) with the fewest variables, the shortest path to making the problem happen. You need to understand what is not relevant to the problem, what’s just noise that adds to the cost and time of debugging and testing – and get rid of it. You do this using binary techniques to slice up the input data set, narrowing in on the data and other variables that you actually need, repeating this until the problem starts to become clear. Code Complete’s chapter on Debugging is another good guide on how to reproduce a problem following a set of iterative steps, and how to narrow in on the simplest and most useful set of test conditions required to make the problem happen; as well as common places to look for bugs: checking for code that has been changed recently, code that has a history of other bugs, code that is difficult to understand (if you find it hard to understand, there’s a good chance that the programmers who worked on it before you did too).Replay Tools One of the most efficient ways to reproduce a problem, especially in server code, is by automatically replaying the events that led up to the problem. To do this you’ll need to capture a time-sequenced record of what happened, usually from an audit log, and a driver to read and play the events against the system. And for this to work properly, the behavior of the system needs to be deterministic – given the same set of inputs in the same sequence, the same results will occur each time. Otherwise you’ll have to replay the logs over and over and hope for the right set of circumstances to occur again. On one system that I worked on, the back-end engine was a deterministic state machine designed specifically to support replay. All of the data and events, including configuration and control data and timer events, were recorded in an inbound event log that we could replay. There were no random factors or unpredictable external events – the behavior of the system could always be recreated exactly by replaying the log, making it easy to reproduce bugs from the field. It was a beautiful thing, but most code isn’t designed to support replay in this way. Recent research in virtual machine technology has led to the development of replay tools to snapshot and replay events in a virtual machine. VMWare Workstation, for example, included a cool replay debugging facility for C/C++ programmers which was “guaranteed to have instruction-by-instruction identical behavior each time.” Unfortunately, this was an expensive thing to make work, and it was dropped in version 8, at the end of last year. Replay Solutions provides replay for Java programs, creating a virtual machine to record the complete stream of events (including database I/O, network I/O, system calls, interrupts) as the application is running, and then later letting you simulate and replay the same events against a copy of the running system, so that you can debug the application and observe its behavior. They also offer similar application record and replay technology for mobile HTML5 and JavaScript applications. This is exciting stuff, especially for complex systems where it is difficult to setup and reproduce problems in different environments. Fuzzing and Randomness If the problem is non-deterministic, or you can’t come up with the right set of inputs, one approach to try is to simulate random data inputs and watch to see what happens – hoping to happen on a set of input variables that will trigger the problem. This is called fuzzing. Fuzzing is a brute force testing technique that is used to uncover data validation weaknesses that can cause reliability and security problems. It’s effective at finding bugs, but it’s a terribly inefficient way to reproduce a specific problem. First you need to setup something to fuzz the inputs (this is easy if a program is reading from a file, or a web form – there are fuzzing tools to help with this – but a hassle if you need to write your own smart protocol fuzzer to test against internal APIs). Then you need time to run through all of the tests (with mutation fuzzing, you may need to run tens of thousands or hundreds of thousands of tests to get enough interesting combinations) and more time to sift through and review all of the test results and understand any problems that are found. Through fuzzing you will get new information about the system to help you identity problem areas in the code, and maybe find new bugs, but you may not end up any closer to fixing the problem that you started on. Reproducing problems, especially when you are working from a bad bug report (“the system was running fine all day, then it crashed… the error said something about a null pointer I think?”) can be a serious time sink. But what if you can’t reproduce the problem at all? Let’s look at that next… Reference: Fixing Bugs – if you can’t reproduce them, you can’t fix them from our JCG partner Jim Bird at the Building Real Software blog....
android-logo

Android WebView CSS Support

Creating HTML applications can be a great way to cut down development time between two platforms. The trend today is to develop a web app for iOS (with varing amount of native code) and simply use the HTML, CSS, and Javascript on other platforms like Android. The process can work well, and it can save you considerable time while still having a nice, polished app on multiple platforms. There are a few pitfalls with the approach, though. One of the main troubles is developing for iOS first. You see, iOS has a great in-app brower. It has support for all of the latest HTML5 components, it fully supports CSS3, and it has great Javascript performance. The problem is, no other platform is near that level yet. This can create some issues when you are porting your HTML,CSS, and Javascript to other platforms, like Android. When following the pattern above, you should really develop for the lower platform first and then port to iOS. This way, you will have less development time lost to solving compabability issues. Some of these issues could be: Javascript DOM differences, CSS3 syntactical differences, and Javascript performance differences. Also, keep in mind that the usage of third party libraries, that may work great on iOS, may not work on other platforms. It may not even have an equivalent verison available. One thing to watch out for would be: -webkit-linear-gradient… versus -webkit-gradient… I’m sure that there are several other major differences between what is supported between Android and iOS. Once I find more, I’ll let you know. Reference: Android WebView CSS Support from our JCG partner Isaac Taylor at the Programming Mobile blog....
java-logo

Java: Mergesort using Fork/Join Framework

The objective of this entry is to show a simple example of a Fork/Join RecursiveAction, not to delve too much into the possible optimizations to merge sort or the relative advantages of using Fork/Join Pool over the existing Java 6 based implementations like ExecutorService. The following is a typical implementation of a Top Down Merge sort algorithm using Java: import java.lang.reflect.Array;public class MergeSort { public static <T extends Comparable<? super T>> void sort(T[] a) { @SuppressWarnings('unchecked') T[] helper = (T[])Array.newInstance(a[0].getClass() , a.length); mergesort(a, helper, 0, a.length-1); } private static <T extends Comparable<? super T>> void mergesort(T[] a, T[] helper, int lo, int hi){ if (lo>=hi) return; int mid = lo + (hi-lo)/2; mergesort(a, helper, lo, mid); mergesort(a, helper, mid+1, hi); merge(a, helper, lo, mid, hi); }private static <T extends Comparable<? super T>> void merge(T[] a, T[] helper, int lo, int mid, int hi){ for (int i=lo;i<=hi;i++){ helper[i]=a[i]; } int i=lo,j=mid+1; for(int k=lo;k<=hi;k++){ if (i>mid){ a[k]=helper[j++]; }else if (j>hi){ a[k]=helper[i++]; }else if(isLess(helper[i], helper[j])){ a[k]=helper[i++]; }else{ a[k]=helper[j++]; } } }private static <T extends Comparable<? super T>> boolean isLess(T a, T b) { return a.compareTo(b) < 0; } } To quickly describe the algorithm – The following steps are performed recursively:The input data is divided into 2 halves Each half is sorted The sorted data is then mergedMerge sort is a canonical example for an implementation using Java Fork/Join pool, and the following is a blind implementation of Merge sort using the Fork/Join framework: The recursive task in Merge sort can be succinctly expressed as an implementation of RecursiveAction – private static class MergeSortTask<T extends Comparable<? super T>> extends RecursiveAction{ private static final long serialVersionUID = -749935388568367268L; private final T[] a; private final T[] helper; private final int lo; private final int hi; public MergeSortTask(T[] a, T[] helper, int lo, int hi){ this.a = a; this.helper = helper; this.lo = lo; this.hi = hi; } @Override protected void compute() { if (lo>=hi) return; int mid = lo + (hi-lo)/2; MergeSortTask<T> left = new MergeSortTask<>(a, helper, lo, mid); MergeSortTask<T> right = new MergeSortTask<>(a, helper, mid+1, hi); invokeAll(left, right); merge(this.a, this.helper, this.lo, mid, this.hi); } private void merge(T[] a, T[] helper, int lo, int mid, int hi){ for (int i=lo;i<=hi;i++){ helper[i]=a[i]; } int i=lo,j=mid+1; for(int k=lo;k<=hi;k++){ if (i>mid){ a[k]=helper[j++]; }else if (j>hi){ a[k]=helper[i++]; }else if(isLess(helper[i], helper[j])){ a[k]=helper[i++]; }else{ a[k]=helper[j++]; } } } private boolean isLess(T a, T b) { return a.compareTo(b) < 0; } } MergeSortTask above implements a compute method, which takes in a array of values, split it up into two parts, creates a MergeSortTask out of each of the parts and forks off two more tasks(hence it is called RecursiveAction!). The specific API used here to spawn of the task is invokeAll which returns only when the submitted subtasks are marked as completed. So once the left and right subtasks return the result is merged in a merge routine. Given this the only work left is to use a ForkJoinPool to submit this task. ForkJoinPool is analogous to the ExecutorService used for distributing tasks in a threadpool, the difference to quote the ForkJoinPool’s API docs: A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute subtasks created by other active tasks (eventually blocking waiting for work if none exist) This is how the task of submitting the task to the Fork/Join Pool looks like: public static <T extends Comparable<? super T>> void sort(T[] a) { @SuppressWarnings('unchecked') T[] helper = (T[])Array.newInstance(a[0].getClass() , a.length); ForkJoinPool forkJoinPool = new ForkJoinPool(10); forkJoinPool.invoke(new MergeSortTask<T>(a, helper, 0, a.length-1)); } A complete sample is also available here: https://github.com/bijukunjummen/algos/blob/master/src/main/java/org/bk/algo/sort/algo04/merge/MergeSortForkJoin.java Reference: Mergesort using Fork/Join Framework from our JCG partner Biju Kunjummen at the all and sundry blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

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