What's New Here?


SpringMVC4 + Spring Data JPA + SpringSecurity configuration using JavaConfig

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));In this article we will see how to configure and integrate SpringMVC4, Spring Data JPA with Hibernate and SpringSecurity using JavaConfig. 1. First let’s configure all the necessary dependencies in pom.xml                 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sivalabs</groupId> <artifactId>spring-javaconfig</artifactId> <version>1.0</version> <packaging>war</packaging> <name>SpringApp JavaConfig Demo</name> <properties> <java.version>1.7</java.version> <junit.version>4.11</junit.version> <slf4j.version>1.7.5</slf4j.version> <logback.version>1.0.13</logback.version> <spring.version>4.0.0.RELEASE</spring.version> <spring-data-jpa.version>1.4.1.RELEASE</spring-data-jpa.version> <spring-security.version>3.2.0.RELEASE</spring-security.version> <hibernate.version>4.2.6.Final</hibernate.version> <aspectj.version>1.7.2</aspectj.version> <mysql.version>5.1.26</mysql.version> <jackson-json.version>2.3.1</jackson-json.version> <commons-dbcp.version>1.2.2</commons-dbcp.version> <commons-lang3.version>3.1</commons-lang3.version> </properties> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build><dependencies> <!-- Logging dependencies --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency><dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency><dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency><!-- Spring dependencies --><dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <!-- Spring Data JPA dependencies --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>${spring-data-jpa.version}</version> </dependency><dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <!-- SpringSecurity dependencies --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version> </dependency><!-- Testing dependencies --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency><!-- DB dependencies --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>${commons-dbcp.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson-json.version}</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.3</version> </dependency> <!-- Web dependencies --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency><dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <scope>compile</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>compile</scope> </dependency> </dependencies><dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-framework-bom</artifactId> <version>${spring.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> </project> 2. Configure database connection properties and email settings in application.properties################### DataSource Configuration ##########################jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=admininit-db=false################### Hibernate Configuration ##########################hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update################### JavaMail Configuration ########################## smtp.host=smtp.gmail.com smtp.port=465 smtp.protocol=smtps smtp.username=sivaprasadreddy.k@gmail.com smtp.password= support.email=sivaprasadreddy.k@gmail.com3. Configure common Service Layer beans such as PropertySourcesPlaceholderConfigurer and JavaMailSender etc in com.sivalabs.springapp.config.AppConfig.javapackage com.sivalabs.springapp.config;import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.env.Environment; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.scheduling.annotation.EnableScheduling;@Configuration @ComponentScan(basePackages={"com.sivalabs.springapp"}, excludeFilters=@ComponentScan.Filter(type=FilterType.REGEX, pattern={"com.sivalabs.springapp.web.*"})) @PropertySource(value = { "classpath:application.properties" }) @EnableScheduling @EnableAspectJAutoProxy @EnableCaching public class AppConfig { @Autowired private Environment env;@Bean public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Bean public JavaMailSenderImpl javaMailSenderImpl() { JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl(); mailSenderImpl.setHost(env.getProperty("smtp.host")); mailSenderImpl.setPort(env.getProperty("smtp.port", Integer.class)); mailSenderImpl.setProtocol(env.getProperty("smtp.protocol")); mailSenderImpl.setUsername(env.getProperty("smtp.username")); mailSenderImpl.setPassword(env.getProperty("smtp.password"));Properties javaMailProps = new Properties(); javaMailProps.put("mail.smtp.auth", true); javaMailProps.put("mail.smtp.starttls.enable", true);mailSenderImpl.setJavaMailProperties(javaMailProps);return mailSenderImpl; } @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager(); } } Observe that we have excluded the package “com.sivalabs.springapp.web.*” from component scanning using new REGEX excludeFilter type. If we don’t exclude web related packages and tries to run JUnit test for service layer beans we will encounter the following Exception: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling Also note that we have enabled Caching using @EnableCaching, so we should declare CacheManager bean. 4. Configure Persistence Layer beans in com.sivalabs.springapp.config.PersistenceConfig.java as follows:package com.sivalabs.springapp.config;import java.util.Properties; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.orm.hibernate4.HibernateExceptionTranslator; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement;@Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages="com.sivalabs.springapp.repositories") public class PersistenceConfig { @Autowired private Environment env;@Value("${init-db:false}") private String initDatabase; @Bean public PlatformTransactionManager transactionManager() { EntityManagerFactory factory = entityManagerFactory().getObject(); return new JpaTransactionManager(factory); }@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(Boolean.TRUE); vendorAdapter.setShowSql(Boolean.TRUE);factory.setDataSource(dataSource()); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("com.sivalabs.springapp.entities");Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); factory.setJpaProperties(jpaProperties);factory.afterPropertiesSet(); factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver()); return factory; }@Bean public HibernateExceptionTranslator hibernateExceptionTranslator() { return new HibernateExceptionTranslator(); } @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.username")); dataSource.setPassword(env.getProperty("jdbc.password")); return dataSource; } @Bean public DataSourceInitializer dataSourceInitializer(DataSource dataSource) { DataSourceInitializer dataSourceInitializer = new DataSourceInitializer(); dataSourceInitializer.setDataSource(dataSource); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("db.sql")); dataSourceInitializer.setDatabasePopulator(databasePopulator); dataSourceInitializer.setEnabled(Boolean.parseBoolean(initDatabase)); return dataSourceInitializer; } } Here we have configured DataSource and JPA EntityManagerFactory bean using Hibernate implementation. Also we have configured DataSourceInitializer bean to initialize and populate our tables with seed data. We can enable/disable executing this db.sql script by changing init-db property value in application.properties. And finally we have enabled Spring Data JPA repositories scanning using @EnableJpaRepositories to scan “com.sivalabs.springapp.repositories” package for JPA repository interfaces. 5. Now let us configure Web related beans in com.sivalabs.springapp.web.config.WebMvcConfig.javapackage com.sivalabs.springapp.web.config;import java.util.Properties; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver;@Configuration @ComponentScan(basePackages = { "com.sivalabs.springapp.web"}) @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { super.addViewControllers(registry); registry.addViewController("login/form").setViewName("login"); registry.addViewController("welcome").setViewName("welcome"); registry.addViewController("admin").setViewName("admin"); }@Bean public ViewResolver resolver() { InternalResourceViewResolver url = new InternalResourceViewResolver(); url.setPrefix("/WEB-INF/jsp/"); url.setSuffix(".jsp"); return url; }@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); }@Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); }@Bean(name = "messageSource") public MessageSource configureMessageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setCacheSeconds(5); messageSource.setDefaultEncoding("UTF-8"); return messageSource; }@Bean public SimpleMappingExceptionResolver simpleMappingExceptionResolver() { SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver(); Properties mappings = new Properties(); mappings.put("org.springframework.dao.DataAccessException", "error"); b.setExceptionMappings(mappings); return b; } } 6. Configure DispatcherService using AbstractAnnotationConfigDispatcherServletInitializer convinient class.package com.sivalabs.springapp.web.config;import javax.servlet.Filter; import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import com.sivalabs.springapp.config.AppConfig;public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {@Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { AppConfig.class}; }@Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebMvcConfig.class }; }@Override protected String[] getServletMappings() { return new String[] { "/" }; }@Override protected Filter[] getServletFilters() { return new Filter[]{ new OpenEntityManagerInViewFilter() }; }} Here few things to note are we configured AppConfig.class as RootConfig classes and WebMvcConfig.class as ServletConfigClasses which is similar to how we configure in web.xml using ContextLoaderListener and DispatcherServlet’s contextConfigLocation. Also we have registered OpenEntityManagerInViewFilter to enable lazy loading of JPA entity graphs in view rendering phase. 7. Let us configure SpringSecurity. First let us create a SecurityUser class which extends our application specific User class and implements org.springframework.security.core.userdetails.UserDetails.package com.sivalabs.springapp.web.config;import java.util.ArrayList; import java.util.Collection; import java.util.Set; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.sivalabs.springapp.entities.Role; import com.sivalabs.springapp.entities.User;public class SecurityUser extends User implements UserDetails {private static final long serialVersionUID = 1L; public SecurityUser(User user) { if(user != null) { this.setId(user.getId()); this.setName(user.getName()); this.setEmail(user.getEmail()); this.setPassword(user.getPassword()); this.setDob(user.getDob()); this.setRoles(user.getRoles()); } } @Override public Collection<? extends GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> authorities = new ArrayList<>(); Set<Role> userRoles = this.getRoles(); if(userRoles != null) { for (Role role : userRoles) { SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName()); authorities.add(authority); } } return authorities; }@Override public String getPassword() { return super.getPassword(); }@Override public String getUsername() { return super.getEmail(); }@Override public boolean isAccountNonExpired() { return true; }@Override public boolean isAccountNonLocked() { return true; }@Override public boolean isCredentialsNonExpired() { return true; }@Override public boolean isEnabled() { return true; } } We will implement a custom UserDetailsService and use Spring Data JPA repositories to load User details.package com.sivalabs.springapp.config;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import com.sivalabs.springapp.entities.User; import com.sivalabs.springapp.services.UserService; import com.sivalabs.springapp.web.config.SecurityUser;@Component public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserService userService; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { User user = userService.findUserByEmail(userName); if(user == null){ throw new UsernameNotFoundException("UserName "+userName+" not found"); } return new SecurityUser(user); } } Now create com.sivalabs.springapp.config.SecurityConfig.java which contains SpeingSecurity related bean definitions.package com.sivalabs.springapp.config;import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; //import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService;@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource;@Autowired private CustomUserDetailsService customUserDetailsService;@Override protected void configure(AuthenticationManagerBuilder registry) throws Exception { /* registry .inMemoryAuthentication() .withUser("siva") .password("siva") .roles("USER") .and() .withUser("admin") .password("admin") .roles("ADMIN","USER"); */ //registry.jdbcAuthentication().dataSource(dataSource); registry.userDetailsService(customUserDetailsService); }@Override public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers("/resources/**"); }@Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/login","/login/form**","/register","/logout").permitAll() .antMatchers("/admin","/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login/form") .loginProcessingUrl("/login") .failureUrl("/login/form?error") .permitAll(); } }As per our SpringSecurity custom Form Login configuration, we will use the following login form in login.jsp. <!DOCTYPE html> <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> <c:url var="rootURL" value="/"/> <html> <head> <title>Login</title> <link href="${rootURL}resources/bootstrap/css/bootstrap.css" media="screen" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="${rootURL}resources/jquery/jquery-1.10.2.js"></script> <script type="text/javascript" src="${rootURL}resources/bootstrap/js/bootstrap.js"></script> <script type="text/javascript" src="${rootURL}resources/js/app.js"></script> </head> <body> <div class="col-md-6 col-md-offset-2"> <c:if test="${param.error != null}"> <div class="alert alert-danger"> Invalid UserName and Password. </div> </c:if> <c:if test="${param.logout != null}"> <div class="alert alert-success"> You have been logged out. </div> </c:if> </div> <div class="row"> <div class="col-md-6 col-md-offset-2"> <h2>User Login Form</h2> <form:form id="loginForm" method="post" action="${rootURL}login" modelAttribute="user" class="form-horizontal" role="form" cssStyle="width: 800px; margin: 0 auto;"> <div class="form-group"> <label for="username" class="col-sm-2 control-label">UserName*</label> <div class="col-sm-4"> <input type="text" id="username" name="username" class="form-control" placeholder="UserName" /> </div> </div> <div class="form-group"> <label for="password" class="col-sm-2 control-label">Password*</label> <div class="col-sm-4"> <input type="password" id="password" name="password" class="form-control" placeholder="Password" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-4"> <input type="submit" class="btn btn-primary" value="Login"> </div> </div> </form:form> </div> </div> </body> </html> Once we successfully login we can obtain the authenticated use details using and secure parts of the view using as folloows:<h3>Email: <sec:authentication property="name"/></h3> <h3> <sec:authorize access="hasRole('ROLE_ADMIN')"> <a href="admin">Administration</a> </sec:authorize> </h3> <p> <a href="logout">Logout</a></p> </body>You can find the source code at github https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/springmvc-datajpa-security-demo  Reference: SpringMVC4 + Spring Data JPA + SpringSecurity configuration using JavaConfig from our JCG partner Siva Reddy at the My Experiments on Technology blog. ...

8 new features for Java 8

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));Jdk 1.8 aka, Java 8 is launched today meaning that the General Availability release of it is out in the open and developers can switch from Early Release releases to a tested release for production use. But what does it means for you, the busy Java developer? Well, here are some points that I condensed to mark this release: 1.Lamda Expressions I started with lambda expressions as this is probably the most sought after feature in the language after probably Generics/Annotations in Java 5. Here’s the syntax: (argtype arg...) -> { return some expression.. probably using these arguments } What it does is that it reduces the code where it is obvious, such as in an anonymous innerclass. (Swing action handlers just got sexy, yay!) So, a thread can be changed as:Runnable oldRunner = new Runnable(){ public void run(){ System.out.println("I am running"); } }; Runnable java8Runner = () ->{ System.out.println("I am running"); }; Similar to Scala, type inference is also possible in Lambdas. Consider the following available example: Comparator c = (a, b) -> Integer.compare(a.length(), b.length()); Here, the types of a,b (In this case String, from the Comparator interface) are inferred as the compare method is implemented. The symbol used to separate the block from arguments, -> is quite similar to => already used in Scala and if you are good at it, there is not much reason to switch as you will feel the way lambdas are implemented in java is inadequate(and verbose), but for a good ‘ol java programmer, this is the way to go. 2.Generic Type changes and improvements Taking clues from Lambdas, generic collections can also infer the data types to be used to an extent. The methods for instance using a generic collection need not specify genric types. Hence, the following method SomeClass.method(); Can be called simply ignoring the type information: SomeClass.method();The type can be inferred by the method signature, which is helpful in nested calls like myCollection.sort().removeUseless().beautify(); 3. Stream Collection Types (java.util.stream) A stream is a iterator that allows a single run over the collection it is called on. Along with Lambdas, this is another noteworthy feature to watch out for. You can use streams to perform functional operations like filer or map/reduce over collections which can be streamed as individual elements using Stream objects. Streams can run sequentially or parallely as desired. The parallel mode makes use of fork/join framework and can leverage power of multiple cores. Example: List guys = list.getStream.collect(Collectors.toList()) can also be implemented parallely as List guys = list.getStream.parallel().collect(Collectors.toList() Another nice example that reduces the collection to a single item is by calling reduce algorithem. int sum = numberList.stream().reduce(0, (x, y) -> x+y);or, int sum = numberList.stream().reduce(0, Integer::sum);4. Functional Interfaces (java.util.function) These interfaces contain some default methods which need not be implemented and can run directly from the interface. This helps with existing code – changing interfaces need not make all the classes implementing it implement new methods. This is similar to Traits in Scala and functional interfaces will be compatible with lambdas. 5. Nashorn – The Node.js on JVM This is the javascript engine that enables us to run javascript to run on a  jvm. It is similar to the V8 engine provided by chrome over which Node.js runs. It is compatible with Node.js applications while also allowing actual Java libraries to be called by the javascript code running on server. This is exciting to say at the least as it marries scalability and asynchronous nature of Node.js with safe and widespread server side Java middleware directly. 6. Date/Time changes (java.time) http://download.java.net/jdk8/docs/api/java/time/package-summary.html The Date/Time API is moved to java.time package and Joda time format is followed. Another goodie is that most classes are Threadsafe and immutable. 7. Type Annotations Now annotations can be used to decorate generic types itself. Eg: List<@Nullable String> which is not desired always, but can prove to be useful in certain circumstances. Apart from decorating Generic types, it can also be used in constructors and casting. new @NonEmpty @Readonly List(myNonEmptyStringSet) new @Interned MyObject()myString = (@NonNull String) myObject; Even the array objects can be annoted: @NotNull String[] arr; The inclusion of RuntimeVisibleTypeAnnotations and RuntimeInvisibleTypeAnnotations attributes which cause the .class file to save the annotation information. 8.Other – (nice to have) Changes Reflection api is slightly increased with the support of TypeName, GenericString, etc. String.join() method is a welcome addition as a lot of self created utility classes are created instead. So, the following example String abc= String.join(" ", "Java", "8"); Will get evaluated as “Java 8″. In the Collections package, the Comparator interface is revamped and methods like reversed, comparing and thenCOmparing have been added which allow easy customization of comparison over multiple fields. Other libraries like the Concurrency and NIO have also been updated but is nothing noteworthy for following up and is keeping with the changes in the api. Overall, Java8 is well thought of and is making mainstream java concise and picking some good parts of Scala/Clojure for the improving its syntax and addressing much sought features.Reference: 8 new features for Java 8 from our JCG partner Sumit Bisht at the Sumit Bisht blog blog....

The Optional Type API

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));Java 8 introduces the Optional class. In a nutshell, instead of returning null, and then checking for null, you return an Optional instance, which can either have or not have a value set. That way you don’t fail with NullPointerException. I won’t discuss whether the Optional type will eliminate NPEs completely (it won’t). Instead I’ll discuss things from a different perspective – API design. In addition to Java’s Optional, I’ll show guava’s Optional and scala’s Option, and compare them. An API, as Joshua Bloch suggests, should be as small as possible, but no smaller. The conceptual weight of an API should be minimized, and if you wonder whether to include something in your API or not, then you should leave it out. An API should be easy to use, and hard to misuse, and ideally should have one (or two) main usage patterns. The Optional type is a good example of having to make all these choices. What is the default usage of this? You get an optional type, and you want to execute some piece of code only if there is a value set. You could obviously do that by comparing to null, but you often tend to forget that and the optional types force you to realize that this value can actually be unset. The second important use-case is to be able to easily provide a default value, if none is set. Let’s first start with the worst of the three (in my opinion) – scala’s Option. At first it seems that this class offers you a lot of functionality. But, as it is normal for scala, there are a lot of different ways to use a class and none of them is better than the rest. For me, the particularly bad decision in this case is making Option (implicitly) convertible to Iterable. For the non-scala developers, let’s assume it is an Iterable. But it can have only one or zero elements. So, in order to implement our default and most common use-case we have the following options:Use imperative style if (option.nonEmpty) {option.get.doSomething()} Use .foreach – option.foreach(v => v.doSomething) Use a foreach loop (different from above): for (value <- option) {value.doSomething()} Use a for comprehension (for…yield) (different from the two above) Use pattern-matching – case Some and case None Use map, fold, collect, etc – this takes the process one step further – not only you get the value, but apply some function to itSo, from the basic notion of an optional type, we have a class with dozens of methods. The conceptual weight of this API is huge. There is no obviously preferred way to handle the most common case, and in fact method preferred by many scala developers uses some form of foreach, which sounds a bit weird, when you know there is at most one value. Now let’s proceed with my 2nd place candidate – Java 8 Optional. You have only two ways to use it – the imperative check with an if-clause, and the ifPresent(function) method, where you supply a function that handles the code when there is a value. You also have a couple of overloaded methods to provide a default value (the 2nd use-case). What I don’t like is the map, flatMap and filter methods there. They are useful, as the scala ones above, but they could be left out (and their usage handled separately, with almost no added verbosity), or they could be reduced to simply one function – map. It has a subtle difference with flatMap, and filtering a single element isn’t the most useful thing out there, besides, you could do that with a map function. I know that by now you are probably ready to ask (angrily) how you are going to write very concise code without the ability to fold, collect, flatMap, filter. Returning another optional type after performing an operation with the given optional type is a 3rd use-case, which is important for long methods. It is less common than the other two, so less attention should be paid to it. Ideally, one method is enough – all other sub-usacases can be handled in the map function itself. So we get to the winner – guava Optional. It has only the imperative way of handling the first use-case (as it is developed for versions of Java that lack first-class functions). The 2nd and 3rd use-cases above have as few methods as possible (or and transform(..)). Leightweight API that can achieve pretty much the same things, in the same amount of code. In fact, having a functional approach for the main use-case is not necessarily good – the point of having an Optional type is not to be able to work functionally with it – the point is to be made aware that the value might not be there. I’m not saying to get rid of it in scala and Java8, but then maybe .isPresent() and .get() could be reconsidered. Bottom-line is – it is hard to design APIs. Even a simple thing as an optional type has a lot of aspects to consider in terms of primary and secondary usa-cases, and whether convenience methods are needed, or they add unnecessary complexity to the API and can instead be handled in a different (not necessarily more verbose) way. And finally – use optional types when you can possibly return null – NPEs are easy to debug and fix, but are easy to miss and may happen at the wrong moment.Reference: The Optional Type API from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog....

5 Features In Java 8 That WILL Change How You Code

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));Java 8 is packed full of some really exciting features at both the JVM and language level. While some of the features initially envisioned for this release got scoped out or pushed out to release 9, there are literally dozens of new features. Many of the new additions are under-the-hood improvements either at the compiler, JVM or help-system level. As such, while we may benefit from them, there’s nothing we need to actively do (other than install Java 8 of course) to enjoy them. Having said that, let’s look at 5 features that we feel are an absolute must for you to know about: 1. Lambda expressions Even if we really didn’t want to go mainstream here, there’s little doubt that from a developer’s perspective, the most dominant feature of Java 8 is the new support for Lambda expressions. This addition to the language brings Java to the forefront of functional programming, right there with other functional JVM-based languages such as Scala and Clojure. We’ve previously looked into how Java implemented Lambda expressions, and how it compared to the approach taken by Scala. From Java’s perspective this is by far one of the biggest additions to the language in the past decade. At minimum, it’s recommended you become familiar with the Lambda syntax, especially as it relates to array and collection operations, where Lambdas have been tightly integrated into the core language libraries. It is highly likely that you’ll start seeing more and more code like the snippet below in both 3rd party and within your organization’s code. Map<Person.Sex, List<Person>> byGender = roster.stream().collect(Collectors.groupingBy(Person::getGender)); * A pretty efficient way of grouping a collection by the value of a specific class field. 2. Parallel operations With the addition of Lambda expressions to arrays operations, Java introduced a key concept into the language of internal iteration. Essentially as developers we’re used to use loop operations as one of the most basic programming idioms, right up there with if and else. The introduction of Lambda expressions turned that paradigm around, with the actual iteration over a collection on which a Lambda function is applied now carried out by the core library itself (i.e. internal iteration). You can think of this as an extension of iterators where the actual operation of extracting the next item from a collection on which to operate is carried out by an iterator. An exciting possibility opened by this design pattern is to enable operations carried out on long arrays such as sorting, filtering and mapping to be carried out in parallel by the framework. When dealing with server code that’s processing lengthy collections on a continuous basis, this can lead to major throughput improvements with relatively little work from your end. Here’s the same snippet as above, but using the framework’s new parallel processing capabilities - ConcurrentMap<Person.Sex, List<Person>> byGender = roster.parallelStream().collect( Collectors.groupingByConcurrent(Person::getGender)); * It’s a fairly small change that’s required to make this algorithm run on multiple threads. 3. Java + JavaScript = ❤ Java 8 is looking to right one of its biggest historical wrongs – the ever growing distance between Java and JavaScript, one that has only increased in the past few years. With this new release, Java 8 is introducing a completely new JVM JavaScript engine – Nashorn. This engine makes unique use of some of the new features introduced in Java 7 such as invokeDynamic to provide JVM-level speed to JavaScript execution right there with the likes of V8 and SpiderMonkey. This means that the next time you’re looking to integrate JS into your backend, instead of setting up a node.js instance, you can simply use the JVM to execute the code. The added bonus here is the ability to have seamless interoperability between your Java and JavaScript code in-process, without having to use various IPC/RPC methods to bridge the gap. 4. New date / time APIs The complexity of the current native Java library API has been a cause of pain for Java developers for many years. Joda time has been filling this vacuum for years now, and with Java 8. An immediate question that arose early on was why didn’t Java 8 adopt Joda as its native time framework. Due to what was perceived as a design flaw in Joda, Java 8 implemented its own new date / time API from scratch. The good news is that unlike Calendar.getInstance(), the new APIs were designed with simplicity in mind, and clear operations to operate on manipulated values in both human readable and machine time formats. 5. Concurrent accumulators One of the most common scenarios in concurrent programming is updating of numeric counters accessed by multiple threads. There have been many idioms to do this over the years, starting from synchronized blocks (which introduce a high level of contention), to read/write locks to AtomicInteger(s). While the last ones are more efficient, as they rely directly on processor CAS instructions, they require a higher degree of familiarity to implement the required semantics correctly. With Java 8 this problem is solved at the framework level with new concurrent accumulator classes that enable you to very efficiently increase / decrease the value of a counter in a thread safe manner. This is really a case where it’s not a question of taste, or preference – using these new classes in your code is really a no-brainer. Are there any other language features you think every developers should know about? Add them in the comments section.Reference: 5 Features In Java 8 That WILL Change How You Code from our JCG partner Tal Weiss at the Takipi blog....

Happy 8th Birthday Java!

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));It’s been another longer journey but yesterday, exactly two years, seven months, and eighteen days after the release of Java 7 we now have production-ready builds of Java 8 available for download! This new major release contains several new features and enhancements that increase the performance of existing applications, make it easier to develop applications for modern platforms, and increase maintainability of code. Here is a brief overview about my personal highlights.           What’s new overall?Several areas of the language itself, profiles, security, JavaFX, tooling, scripting, Date and Time, concurrency and a more or less lengthy list of things changed or got added. More than 8.000 bugs and features have been addressed and be incorporated into this release. The complete list can be found in the official release-notes. Java Mission Control 5.3 One of the highlights is the new Java Mission Control release. It is bundled with the JDK and comes with a separate list of enhancements in it’s own release-notes. Find the complete documentation as part of the official Java SE 8 documentation. Compact Profiles The newly introduced profiles enable reduced memory footprint for applications that do not require the entire Java platform. The javac compiler has a -profile option, which allows the application to be compiled using one of the supported profiles. The three are additive layers, so that each Profile contains all of the APIs in profiles smaller than itself. The compact profiles feature is useful in small devices with less hardware power. And yes, I am personally still totally frustrated that Jigsaw will probably never see the light. But I am happy to be proven wrong on that. Java Date-Time Packages Thank you Stephen! Thank you for this great piece of work. TimesTen is the new Date and Time API in Java 8. Clear, Fluent, Immutable, Extensible. There are two basic ways to represent time. One way represents time in human terms, referred to as human time, such as year, month, day, hour, minute and second. The other way, machine time, measures time continuously along a timeline from an origin, called the epoch, in nanosecond resolution. See the official tutorial for more examples and usages. Good Bye PermGen! Removal of PermGen. Full stop. It’s gone! YES! Security Enhancements More and stronger Algorithms, TLS 1.2 default and further enhancements. Nashorn Java 8 is co-bundled with the Nashorn, which is an implementation of the ECMAScript Edition 5.1 Language Specification. See the user-guide for all the details. Happy 8th Birthday Java!Congratulations to everybody involved. Especially the Adopt-OpenJDK community which was driven by the London-Java-Community and supported the Date-Time efforts by providing tests.Reference: Happy 8th Birthday Java! from our JCG partner Markus Eisele at the Enterprise Software Development with Java blog....

Frustration-Driven Development – Towards DevOps, Lean, Clojure

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));My wife has mentioned that she likes my passion for doing things right in software development. That made me thinking, why do I actually care so much and do not just enjoy the coding itself? It boils down to that I am not happy until my code is in production. Seeking the satisfaction of having my code used by and helping people while trying to eliminate all unnecessary mental drain is behind all the practices that I embrace and evangelize. It’s a drug I like to take often, in small doses.           practices = f(max(delivered value), min(mental energy)) So how does this relate to DevOps, Continuous Delivery, testing, single-piece-flow, Lean Startup, Clojure? It is simple. Build It Fast I care about DevOps and Continuous Delivery because they are about getting my stuff out as soon as possible. I love to build & ship, get it used right after finishing. Having my work sitting in a queue – for a code review, testing, deployment – is frustrating. I want to finish it, see it running, being used, and working well and put it off my brain so that i can focus on the next thing with a clear mind. That is why also single-piece-flow sounds so attractive to me. If my work is not deployed, used, and thus confirmed to be OK and useful, it is not finished. It may come back due to defects and I have no proof that it actually was worthwhile. The lack of the it’s-working-and-valuable gratification and the mental drain of having multiple unfinished things (see Zeigarnik effect) is frustrating. Build The Right Thing For the same reason I care about users and building the right thing, i.e. something that they actually will use and benefit from, while also making it as user-friendly as possible. A tight contact with users/business, A/B testing and other Lean Startup techniques, user monitoring are some of great tools and practices that help us ensure that we indeed build the right thing. I am a very skeptical person. History has shown many times that we are terrible at predicting what users need / want so I don’t believe in the value of a product until I see data that prove it. As Marry Poppendieck famously put it, “Show me the money!” I’m convinced that development is primarily about discovery – both of value (for users) and of the technical (challenges and solutions). The degree of uncertainty may vary but it is always there. It is frustrating to see projects following blindly the course set by an “omniscient” stakeholder / PM / architect. Build It Right I also care a lot about testing, TDD, and the “build quality in” of lean. I want to get the fruit of my work to users to improve their lives ASAP and then delete it from my brain. But defects make it come back. So without good quality, I may never know whether I am actually finished or not. Context switching and re-loading the previous work into my mind is mentally tiring. Also, I dislike testing phases and code freeze, they are obstacles – not just rocks, but mountains – on the path from code to value. Therefore good quality built in, automated tests, and all the Continuous Delivery practices are crucial. I crave for improving people’s (users’) lives. I want to have the satisfaction of this drug of mine often and quickly. Struggling with spaghetti legacy code is slowing me down. Therefore I care about good and simple architecture and design (DRY, SRP and all the stuff). I care a lot for refactoring; a true professional aims for long-term sustainable high development speed over quick fixes. I have been too often on the bad end of “let’s hack this quickly now and pay the price later.” Use The Best Tools My love for producing value for users also explains why I have grown to dislike Java and like Clojure (though it can be generalized to other languages, f.ex. C# vs. F#). In Java, it feels very wasteful to keep repeating myself due to weak abstractions and to write heaps of boilerplate code (all those getters, Comparators etc.) Clojure is much more powerful, with abstractions that make it easy to “say things once” such as higher-order functions and multimethods, and is malleable to fit the problem at hand like a glove (thanks to macros etc.). Java, on the other hand, forces me to fit the problem to the language and to write loads of boilerplate code. Also, in Clojure, REPL enables truly interactive and exploratory development, with an extremely short feedback loop and thus helps me go fast. My favorite example of the Clojure-Java dichotomy is a map-reduce job written using the Clojure library Cascalog vs. what it would look like in plain Hadoop Java. (It is a little pears-and-apples comparison but demonstrates the point of 90% business code vs. 90% boilerplate code). For similar reasons, when I have to use a framework or a library, I prefer one that actually makes my life simpler and does not make me fight it all the time. (So no to JSF.) People Matter Too Organizations based on trust, with good inter-personal relationships, are the most conductive for creativity and productivity. I therefore prefer synergistic/chaordic organizations (over analytic or, Cthulhu save us, toxic ones) and good teams. Few Historical Examples Project Gnomes: This was a technically great project, with DevOps, full control over everything, frequent releases. Yet it frustrated me because I did not believe in the value of the product being built. Project Blackjack: On the positive side, this was a very business/users-oriented project driven by actual needs of real users. But it was in the stone age of development, with outdated technologies, hosting and thus all environment changes outsourced to a less-than-flexible international company with changes taking from days to months, and the development was little too much focused on risk. Why Should The Business Care? The business does care about making money, not about making me happy. So why should they care about my frustration? Why should they care about starting to get value from IT ASAP? About verifying that an investment of IT resources is really worth it? About avoiding defects and downtimes (and lost customers and sales)? Ehm, do I need to answer? (Also, happy developers = productive developers so yes, they should care about our satisfaction and frustrations.) Summary For me, development is essentially about maximizing value <=> minimizing the idea-to-”cash” time. This naturally leads to DevOps, Continuous Delivery, lean startup practices and thinking, “build the quality in,” single piece flow, and it drives my choice of tools and languages. Psychologically, it is about maximizing gratification while minimizing mental drain, i.e. the expenditure of mental energy.Reference: Frustration-Driven Development – Towards DevOps, Lean, Clojure from our JCG partner Jakub Holy at the The Holy Java blog....

Akka Toolkit 2.3 released

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));The release of 2.3.0 version of Akka toolkit was recently announced. Akka is a very useful toolkit and runtime for building highly concurrent, distributed, and fault tolerant event-driven applications on the JVM. It is distributed and provides high-level abstractions like Actors, Futures and STM. Its new release comes eight months after the 2.2.0 release and brings along new features. One of the most important ones is that now Actor and FSM support Java 8 lamda expressions (still in experimental mode). The syntax used is very close to Scala’s pattern matching.   Other important features are :Cluster nodes can now come back after being in an unreachable state. So cluster becomes more resilient transient network failures. Stateful actors can be distributed to the cluster when not fitting in one machine, without knowing their actual location, which may change over time. This feature is the sharding of actors. The experimental label is removed from Akka IO package, but with the Pipeline infrastructure is discontinued. The OSGi support has been reworked to make akka-actor an OSGi bundle.The most exciting new feature is Akka Persistence. In Akka Persistence the actors persist their internal state, so when restarted after a crash or after migration they can recover it. The actors actually persist their changes to a journal, so stateful actors can be recovered by replaying stored changes, rebuilding the actors’ internal state. Akka Persistence provides point-to-point communication channels with at-least-once message delivery semantics. There have been changes to the documentations so as to get started with the new release of the framework. ...

Android App tutorial:Peg board game

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));I released in Github the source code of an app that can be used to play peg board. This app was published on the market some times ago and this is a new version. The app screenshots are shown below:                  There are some interesting aspects we can consider in this app and they are described below. It can be used as example how to integrate different elements like SlidingPaneLayoutfragments, event handling and so on.App structure The main android UI pattern used by the app is the Sliding Pane layout because we need to have the screen divided in two area: the main area is where we can play with our pegs and the other one that usually is closed is the menu. So the overall layout is: <android.support.v4.widget.SlidingPaneLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/sp" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/tilebkg" ><fragment android:id="@+id/pinMenu" android:name="com.survivingwithandroid.pegboard.fragment.MenuFragment" android:layout_width="200dp" android:layout_height="match_parent" android:layout_gravity="left" /><fragment android:id="@+id/pinTable" android:name="com.survivingwithandroid.pegboard.fragment.DreamPinTableFragment" android:layout_width="600dp" android:layout_height="match_parent" android:layout_gravity="right" android:layout_weight="1" /></android.support.v4.widget.SlidingPaneLayout> The result is shown below:As you can notice the SlidingPaneLayout handles two fragments DreamPinTableFragment and MenuFragment. DreamPinTableFragment takes care of creating the table and handling the user touch so that the user can place pins on it, while the MenuFragment handles the some options like choosing the pin colors, save the work and so on. Custom Layout with ViewGroup The peg board is implemented as custom layout. The class that implements it is called PinTableView that extends ViewGroup. This custom layout takes care of dividing the UI screen in small cells that corresponds to the holes where the pegs are placed. The app screen is treated as a table divided in rows and columns. The first method called by DreamPinTableFragment is disposePin. This method calculates the number or rows and columns and initializes the table: public int[] disposePins(int width, int height, int dotSize) {this.dotSize = dotSize;numRow = height / dotSize + 1; numCol = width / dotSize + 1;int[] dotColors = Pin.createDotArray(dotSize, true);for (int r=0; r < numRow ; r++) { for (int c=0; c < numCol; c++) { PinImageView pinImg = new PinImageView(getContext(), r, c); this.addView(pinImg); } }return new int[]{numRow, numCol}; } Notice that in this method we add PinImageView (another custom view) to the layout (line…) giving to them the right row and column number. Then in onLayout method we traverse the list of childs (we added previously) and start placing them in the right position. In this case we need to calculate the x and y coordinates in real pixel, this is simple once we know the row and column number and the cell pixel size: @Override protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) { int childCount = getChildCount();for (int i=0; i < childCount; i++) { PinImageView pinImg = (PinImageView) getChildAt(i);//int left = pinImg.getCol() * dotSize + dotSize * (pinImg.getType() == PinImageView.COLOR_COMMANDS || pinImg.getType() == PinImageView.DELETE ? 0 : 1); int left = pinImg.getCol() * dotSize; //int top = pinImg.getRow() * dotSize + dotSize * (pinImg.getType() == PinImageView.COLOR_COMMANDS || pinImg.getType() == PinImageView.DELETE ? 0 : 1); int top = pinImg.getRow() * dotSize; int right = left + dotSize ; int bottom = top + dotSize ;pinImg.layout(left, top, right, bottom); }} In this way, we created an empty board that looks like the picture shown below:Custom imageView: PinImageView As we saw before, we place in our layout a custom ImageView childs. PinImageView is a simple class that extends ImageView and represents a single Peg (or pin as we prefer to call it). This class has an internal state that holds the type of the peg it represents and implements some kind of animation to make the UI more attractive. public class PinImageView extends ImageView { private int row; private int col; private int xSize; private int ySize; private int stato = -1; private Context ctx; private int currentPinId;public PinImageView(Context context, int row, int col) { super(context); this.ctx = context; this.row = row; this.col = col; //this.parent = parent;// Load image Drawable d = getResources().getDrawable(TableConfig.pinBackground); setImageDrawable(d); xSize = this.getWidth(); ySize = this.getHeight(); this.currentPinId = TableConfig.pinBackground;} ... class AnimView implements Runnable {Animation anim; Drawable d;public AnimView(Animation anim, Drawable d) { this.anim = anim; this.d = d; } @Override public void run() { anim.setAnimationListener(new Animation.AnimationListener() {@Override public void onAnimationStart(Animation animation) { TableConfig.playSound(PinImageView.this.ctx); }@Override public void onAnimationRepeat(Animation animation) {}@Override public void onAnimationEnd(Animation animation) { setImageDrawable(d); PinImageView.this.setVisibility(View.VISIBLE); } });PinImageView.this.startAnimation(anim); }} } Handle user touch: OnTouchEvent and OnTouchListener The next step is handling the user touch. We define that DreamPinTableFragment listens to the events triggered when user touches the screen. We want to place a peg in the position where user touched the screen: @Override public boolean onTouch(View v, MotionEvent event) {int x = (int) event.getX() ; int y = (int) event.getY() ;if (event.getAction() == MotionEvent.ACTION_DOWN) { pinsTable.changePinColor(x, y); return true; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { pinsTable.changePinColor(x, y); return true; }return false;} and then we delegate to the PinTableView to handle the event passing the coordinates: public void changePinColor(int x, int y) { int row = getRow(y); int col = getColumn(x);PinImageView pinImg = (PinImageView) getChildAt(col + ( row * numCol )); if (pinImg != null) { pinImg.setPinColor(currentColor);} } Knowing the x and y coordinates we can calculate the corresponding row and column and set the peg with the right color. App Menu As we explained before the app has a menu where user can select the pincolor, save the work or change the table background. The class that handles the menu is called MenuFragment. This is very simple class, it just notifies to the main activity the events triggered when user selects a menu item. In turn, the main activity handle this event informing the other fragment when these event regards pegs or some actions that have to be taken on the table. The MenuFragment defines an interface (a listener) that we have to implement when we want to have information on the events occurred in the menu: public static interface MenuEventListener { public void onPinSelected(int pinId); public void onClearSelected(); public void onSaveSelected(); public void onBackgroundSelected(); } So the main activity: public class DreamPinsActivity extends Activity implements MenuFragment.MenuEventListener { .... @Override public void onPinSelected(int pinId) {pinTableFrag.setCurrentPin(pinId); closeMenu(); }@Override public void onClearSelected() { ... }@Override public void onSaveSelected() { closeMenu(); ... }public void onBackgroundSelected() { ... } } Save layout as image The last aspect we want to cover is saving the layout as image. We can implement it in this way: in the PinsTableView: public Bitmap createBitmap() { Bitmap b = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.RGB_565); Canvas c = new Canvas(b);this.draw(c);return b; } where we create an empty bitmap having the same size of the screen and then draw on the corresponding Canvas. Once we have our bitmap that contains the screenshot of the app screen we save it in a file: OutputStream outStream = context.getContentResolver() .openOutputStream(uri);b.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); outStream.close();Source code availabe @ github  Reference: Android App tutorial:Peg board game from our JCG partner Francesco Azzola at the Surviving w/ Android blog. ...

Joy of Coding… and mutation testing in Java

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));For many years now it has been good practice to write unit tests for your source-code. And also to use test coverage reporting to see how much of your code is covered by tests. Although line + branch coverage reporting is quite useful, it doesn’t tell you how good your unit tests actually are. Hence it’s even possibly to achieve 100% coverage without even a single assert in your tests. Being interested in better ways of testing I attended the “Mutation testing” workshop during this years Joy of Coding conference. Mutation testing is a radical different approach of executing and analyzing the result and coverage of your unit tests. Instead of measuring how much of your code is “accessed from” your unit tests it determines how much of your code is actually “tested by” your unit tests. So how does it actually work The basic idea behind mutation testing is to make a small change (a mutation) to the (byte) code and then execute your tests to see if it is detected by the unit tests. Possible mutations are altering a “>” into “>=“, replacing “++” with “--” and removing “void” method invocations. Each mutation therefor creates an altered version of your code called a “mutant”. Prior to the actual mutation testing our unit tests first need to be executed against the original code to see if no tests are failing. Then the unit tests will be run for each “mutant” (making it possibly very time consuming) the see if:the mutant is detected by our unit tests: the tests fails and therefore the “mutant” is considered “killed”. the mutant remains unnoticed by our unit tests: the tests did “not” fail (the “mutant” is considered “alive”) and didn’t notice the mutation; this means that the “mutant” is actually “not” tested (uncovered) by the unit tests.An example of mutation testing So how does this “mutation testing” actually work? Consider the following method: public String foo(int i) { if ( i >= 0 ) { return "foo"; } else { return "bar"; } } And the fact that the unit tests consist of only one test method:@Test public void testFoo() { testee.foo(0); } What if we would create a “mutant” of our code in which “>=” is altered into “>“? We would expect our unit test method to detect this, right? Well in this case it’s not since the test method doesn’t contain a single assertion. What is we would change a “testFoo” method to include an assertion: @Test public void testFoo() { String result = testee.foo(0); assertEquals("foo", result); } Now our unit test method will fail and detect (aka “killed) the “mutant” code. Besides altering “>=” into “>” additional “mutants” could be created:the first return method could be altered to return null (instead of "foo"); this “mutant” is “killed” by the “testFoo” method due to the “assertEquals” statement but remains unnoticed the original “testFoo” method (without any assertions). the second return method can be altered to return null (instead of "bar"); since no test method actually covers this execution path this “mutant” will remain unnoticed.NOTE: some mutation testing tooling (like PIT for Java) won’t even bother creating a “mutant” for the second return statement as it will never be covered by the unit tests (as detected by traditional line coverage). Equivalent mutations causing false-positives As apposed to traditional line + branch coverage, mutation coverage can possibly lead to false-positives. It could “incorrectly” report (a false-positive) that a “mutant” as “not” being detected by your unit tests. For instance consider the following Java code: public int someNonVoidMethod() { return 0; } public void foo() { int i = someNonVoidMethod(); // do more stuff with i } During mutation testing (using PIT Mutation testing with some “non”-default configuration) the following “mutant” could have been created: public int someNonVoidMethod() { return 0; } public void foo() { int i = 0; // do more stuff with i } The “int i = 0” statement in the “mutant” is functionally “equivalent” to the original code in which “someNonVoidMethod” returns 0. Such an “equivalent mutation” cannot be detected since the unit tests will (and should) not fail on it. And therefore it will be reported as being non-covered whereas it is actually a false-positive. When using PIT, a mutation testing framework for Java, “equivalent mutations” should, according to the documention, be minimal using the “default” set of mutators. For instance the “Non Void Method Call Mutator” of PIT causing the “int i = 0” equivalent mutation is disabled at default. Conclusion After participating in workshop, some additional investigation and playing around with PIT, I got really enthusiastic about using “mutation testing” in the near future (starting with new components) on my current project. As apposed to traditional coverage reporting the mutation test coverage actually measures the quality of your tests and cannot be fooled like traditional coverage reporting. In case you also got interested:check out this very funny presentation from Chris Rimmer about the basic concept of mutation testing. furthermore there’s an interesting article from a company called TheLadders using the PIT mutation testing tool. also theres an extensive article from Filip van Laenen about “mutation testing” in edition 108 of the overload magazine. last but not least there’s the documentation on the PIT mutation testing website.Reference: Joy of Coding… and mutation testing in Java from our JCG partner Emil Galen at the JDriven blog....

Estimation by stuffing things into boxes

(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=629802223740065"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));I’ve started using an approach for software project estimation that so far is proving to be fairly transparent, quick and reliable. I’ve observed that within a reasonable degree of variation, most teams seems to complete about one “user-relevant task” per developer per calendar week. There are so many theoretical holes in my argument that there’s no point trying to cover them all. The funny thing is that it seems to work fairly well in practice. And to the degree that it’s dirty, it’s at least quick and dirty. The only thing I will address is that one of these “user relevant tasks” is smaller than a typical application feature. Most importantly: Most teams never get it right on the first try. Or they spend too long gold-plating everything. Or both. This article shows an example of estimating a fictive project: The Temporary Staffing System. The high-level scope Let’s say that our organization has come up with the following vision: For a temporary employment agent who wants to match candidates to client needs, the Temporary Staffing System is an interactive web application, which lets them register and match candidates and positions. Unlike competing systems this lets us share selective information with our clients. We come up with the following flow through the application:A new company wants to hire a skilled worker for a temporary position Administrative user adds the client details to the system Administrative user adds client logins to the system (perhaps we also should let the clients log in with LinkedIn etc?) Client logs into the application and completes new position description, including skill requirements Temp agency adds a worker to the system Temp agency proposes the worker to a position registered by a client (in the future, the worker may register themselves!) Client gets notified of new proposals (via email) Client views status of all open positions in the system External to the system: Client interviews candidate, request further information and makes a decision whether to hire or not Client accepts or rejects the worker in the system As worker performs work, they register their time in the system At the end of a billing period, the system generates billing information to accounting system At the end of a salary period, the system generates salary information to the accounting systemSome of these steps may be one user story, some may be many. The top of the backlog We choose some of the most central parts of the scope to create the beginning of the backlog. In order to accommodate for the learning as we go along, the first draft of our backlog may look like this:Experimental create open position Experimental list positions Simplified create open position Simplified list positions Complete create open positions Complete list positionsAn “experimental” version of a story is a functionality trivial version that touches all parts of the technology. In the case of these two stories, perhaps we have the application leave the logged in client as a hard coded variable. The story may only include writing some of the fields of the positions, maybe only title and description. The Simplified version may add more complex properties, such as skills from a skill list or it may add filters to the list. The complete version should be something we’re prepared to put in front of real users. By revisiting a feature like this, we have the chance to get the feedback to create a good feature without gold-plating. Continuing the backlog We add enough of the other stories to the backlog to cover an interesting part of the scope:… Basic create client account Complete create client account Basic login admin user Basic login client user Complete login client user Basic add worker Complete add worker Basic propose worker for position Complete propose worker for position Complete confirm worker for position Basic enter timesheet (in this version temp agency enters on behalf of worker) Experimental billing report Basic billing report Basic salary reportThis functionality should be enough to have a pilot release where some clients and workers can be supported by the new system. Or we may complete the backlog with complete versions of all functionality, worker login and perhaps a polished version of a feature or two. Adding the non-functional tasks There are some tasks that we want to plan some extra time for. I generally find that many of these tasks are tasks that customers understand quite well:… Attend training on CSS (the team is rusty in design skills) Basic layout and styling of web pages Complete layout and styling of web pages Polished layout and styling of web pages (they want it really nice) Locate slowest pages and make some performance improvements Deploy solution to target platform Deploy demo version to wider set of stakeholders Deploy pilot version Exploratory test of complete flowPlanning the project In this example project, we have five team members plus a coach/project manager on half-time. Since our team will be working in pairs, we want to work on three functional areas per week. This way, we can avoid huge merge conflicts. The team agrees to plan for five stories per week, but only three the first week, because things generally go slower. Here is the top of the completed backlog:Week 1: Experimental create open position Week 1: Experimental list positions Week 1: Attend training on CSS Week 2: Simplified create open position Week 2: Simplified list positions Week 2: Basic create client account Week 2: Basic layout and styling of web pages Week 3: Basic login client user Week 3: Deploy solution to target platform Week 3: Basic add worker Week 3: Basic propose worker for position Week 3: Basic enter timesheet (temp agency enters on behalf of worker) Week 4: Experimental salary report Week 4: Complete layout and styling of web pages Week 4: Complete create open positions Week 4: Complete list positions Week 4: Deploy demo version to wider set of stakeholders … Week 6: Exploratory test of complete flow Week 7: Deploy pilot versionPresenting the plan Working through the list gives us a complete timeframe of just over 6 weeks for full feature set for the pilot release. To cover realities of life, we probably want to plan for at least one week of slack or even more, depending on the strength of our commitment and the consequences of being wrong. This gives a plan indicating 7 weeks times 5 people at 40 hours per week plus a 50% project manager at 20 hours per week or a total of 1540 hours. I generally find that after a pilot release (or even before it), things change a lot. So I don’t invest much time into planning this. Tracking the development The true strength of a plan like this appears when you start running the project. Each week, the team will report on which stories they completed. This allows us to adjust the plan to actual progress. On the flip side, the weekly planning comes down the team and the customers agreeing on the definition of a story. The vagueness of “basic add worker” is by design! But the team should agree on what they mean by “experimental”, “simplified”, “basic”, “complete” and “polished”. Conclusions In this article, I have showed a quick and accurate way of coming up with a project forecast, complete with time and cost estimates. It’s easy to see and react to deviations from the forecast. A few critical critical observations support this methodology:I never believe a developer estimate other than “by the end of the day” or “by the end of the week”. (Don’t talk to me about hours!) Estimating in hours is a silly way to get to project costs. Any hour-based estimate is always prodded and padded before magically turning into cost. Instead, estimate number of features, feature per week and cost by week. Visiting a feature multiple times lowers total cost due to less gold-plating and investment of in poorly understood areas. It also improves the success of the final feature The ambition of a feature (that is, how many times we will visit it) is a more reliable indication of cost than developer gut feelingI’ve left many questions on the table, for example: What about architecture? What is meant by a “simplified” user story? How to deal with deviations from the forecast? Feel free to grill me for details in the comments to the article. “So what will it cost?” Using this simple method to lay out your project forecast week by week, you can give a better answer next time someone asks.Reference: Estimation by stuffing things into boxes from our JCG partner Johannes Brodwall at the Thinking Inside a Bigger Box 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
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.