What's New Here?


Official Eclipse Support for Java(TM) 8

Dani Megert, the project lead for the Java development tools (JDT) project made this announcement earlier today: The Eclipse top-level project is very proud to announce official support for Java™ 8. Starting with I20140318-0830 all Luna (4.4) builds contain the Eclipse support for Java™ 8. For Kepler SR2 (4.3.2) a feature patch is available. For future builds visit our downloads page. The Java™ 8 support contains the following:  Eclipse compiler implements all the new Java™ 8 language enhancements. Significant features, like Search and Refactoring, have been updated – to support Java™ 8. Quick Assist and Clean Up to migrate anonymous class creations to lambda expressions and back. New formatter options for lambdas.Note that PDE API Tools has not yet adopted the new language constructs. This will be completed in the final Luna release. Big thanks to everyone who worked on this effort!Congratulations to the team!Reference: Official Eclipse Support for Java(TM) 8 from our JCG partner Wayne Beaton at the Eclipse Hints, Tips, and Random Musings blog....

Go for Java Programmers: Packages, Functions, and Variables

Go’s Familiar Syntax Due to their shared heritage in the C programming language, Go (aka Golang) code should be fairly recognizable to a Java developer.  Here is the canonical “Hello world” program, which you can execute and modify through your browser on the Go Playground site:           package mainimport "fmt"func main() { fmt.Println("Hello world") } Functions and control structures begin and end with curly-braces.  Function parameters are enclosed in parentheses, with empty parentheses for functions having zero parameters.  Strictly speaking, Go statements terminate with semicolons just as in Java, although the convention is to let the compiler insert them implicitly.  The naming convention for variables and functions is “camelCase”, rather than using underscores (Python people tend to hate this!). Other Go fundamentals closely mirror their Java counterparts, too.  Go code is grouped into “packages”.  A function main(), located in the package main, is the entry-point to a Go program… just like the main method in a Java application: package com.mycompany;public class MyApplication {public static void main(String args[]) { System.out.println("Hello world"); }} Packages, Variables, and Functions However, there are of course differences.  Compare this extended Java code:package com.mycompany;import java.util.Date;public class MyApplication {private Date currentTime;public static void main(String args[]) { MyApplication instance = new MyApplication(); String message = instance.sayHello("world"); System.out.println(message); System.out.println("The time is currently: " + instance.currentTime.toString()); }public MyApplication() { currentTime = new Date(); }private String sayHello(String listener) { return "Hello, " + listener; }} … to a Go counterpart:package mainimport ( "fmt" "time" )var currentTime time.Timefunc init() { currentTime = time.Now() }func main() { message := sayHello("world") fmt.Println(message) fmt.Println("The time is currently: " + currentTime.String()) }func sayHello(listener string) string { return "Hello, " + listener } As you can see, Go variable and function declarations work in reverse order from Java.  Like all Go functions, the sayHello declaration here begins with the keyword func rather than a return type.  The return type, string in this case, comes at the very end just before the opening curly-brace.  The same is true for function parameters.  Instead of String listener, the parameter declaration is listener string. Variables are declared with the keyword var, with the type likewise following the variable name. However, line 15 illustrates a convenient shorthand notation.  When the colon-equals operator := is used rather than a plain equals sign, both the var keyword and the variable type can be omitted.  The compiler is smart enough to deduce the correct type from what’s on the right-hand side on the operator. Scope and Lifecycle Because the variable message is declared inside of main, its scope is limited to that function.  However, currentTime is declared at the package level, and therefore is visible to all functions in the package.  Notice the lack of access level modifiers on the variables and functions here.  Java uses the keywords public, private, etc to control access from outside of a class or package.  Go does this through capitalization.  A variable or function beginning with a lower-case character is analogous to private in Java.  If the currentTime variable had been declared like this instead: ... var CurrentTime time.Time ... … then it would be analogous to Java’s public, and would be accessible from other packages as well.  The same convention applies for functions, as you can see on lines 16 and 17.  Because it starts with an upper-case “P”, the Println function may be used outside of the standard fmt package. Lastly, notice the init() function on line 10.  Although main() is the primary entry-point for a Go application, init() is a special (optional) function that is automatically called before anything else.  It is typically used to initialize variables, or other setup and validation tasks.  For now, you can think of init() is roughly comparable to a Java constructor, even though in Go the distinction between static and instance methods doesn’t quite apply.  More detail on how Go compares to Java’s object-orientation will come later in this series, in a post about Go types. Multiple Return Types?!? Java methods can take any number of input parameters, but always return no more than ONE return type.  If you need a method to return more than one distinct piece of information, then you would either create a custom type to hold the multiple pieces… or else give up and refactor the method to avoid that clutter. One of the surprises with Go functions is that they quite commonly return multiple values in a single call!  Consider this example function which trims whitespace from a string, and returns both the trimmed string and the number of characters removed in the process: package mainimport ( "fmt" "strings" )func main() { trimmedString, numberOfCharsRemoved := trimWithCount("This is a test ") fmt.Printf("%d characters were trimmed from [%s]\n", numberOfCharsRemoved, trimmedString) }func trimWithCount(input string) (string, int) { trimmedString := strings.Trim(input, " ") numberOfCharsRemoved := len(input) - len(trimmedString) return trimmedString, numberOfCharsRemoved } You simply declare a function with a comma-separated list of return types, just as as you would declare a comma-separated list of input parameters.  The return statement must match those types in the correct order.  When the function is invoked, as it is here on line 9, its results should be assigned to a comma-separated list of variables that are likewise in the right order. As we’ll see later in this series when talking about exception handling, Go uses this approach extensively to report errors.  If something could go wrong within a function, is it typical for the function to return both a result and an error type.  Callers can verify the clean success of the function call by checking that the error is nil (i.e. null): ... number, err := strconv.Atoi(someNumericString) if err != nil { // Could not parse this string variable as an integer log.Fatal(err) } ... Deferred Function Calls Often you have logic that you want to ensure happens at the end of a given block, no matter what.  Java supports this with the try-catch-finally construct.  Code inside of a finally block should always be executed following the code in its try block, even if some exception triggers the catch block in between. Java 7 enhanced this idea with the “try-with-resources” mechanism.  Resources such an open file handle or a database connection, which are declared at the outset of a try block, are automatically closed even if you don’t do so manually inside of a finally block:... try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {// Do something with the file} catch(Exception e) { log.error("An error occurred while processing the file: " + e); } finally { log.debug("The 'finally' block was reached"); } ... Go has a similar mechanism, in deferred function calls.  When a function is invoked with the defer keyword, then its execution occurs upon returning from the function in which its invoked.... file, err := os.Open(filename) if err != nil { fmt.Println("Could not open file") return } defer file.Close()// Do something with the filereturn } ... Here, the call to file.Close() on line 7 will always be invoked just before the surrounding function returns, even if the surrounding function “panics” (to be covered later in this series in an article on exception handling).  Any function can be deferred in this manner.  Key things to note are that:Multiple deferred function calls are executed in LIFO order.  If another deferred function were scheduled after the file.Close() call on line 10, then that function would be invoked before the file.Close(). Any parameters passed to a deferred function are evaluated at the point where the function in scheduled, not the point at which it’s actually executed.Conclusion Syntax, packages, functions, and variable in Go are strikingly similar to Java, yet differ in powerful ways.  In the next article of the Go for Java Programmers series, we’ll look at Go’s control structures.   Reference: Go for Java Programmers: Packages, Functions, and Variables from our JCG partner Steve Perkins at the steveperkins.net blog. ...

JavaSE: How to SET/GET your own Files and Directory Attributes

In the previous article “Determining Views Supported by a Particular File System” and see how to ask the file system store, and see supportability of a particular file attribute view. We are going to explore in a nutshell, one of the most advanced and important files attribute views which is User-Defined File Attributes View. Particularly, I am using this feature a lot in my exchanged files during integration between my systems, to hide my files meta-data and security related information from users and contents of the file. So the file content will be only regarding the content of the file only, no more irrelevant meta-data. Therefore If you find that there are not enough built-in attributes for your needs or if you have some unique meta-data (meaningful to the file system) that you want to associate with a file, you can define your own attributes. NIO.2 offers the user-defined file attributes view, extended attributes through the UserDefinedFileAttributeView interface. This facility allows you to associate to a file any attribute that you consider to be useful for your use cases. Here you should know how to:Check User-Defined Attributes Supportability Operations on User-Defined Attributes as the following:Define a User Attribute. List User-Defined Attribute Names and Value Sizes. Get the Value of a User-Defined Attribute. Delete a File’s User-Defined Attribute.Here is the class that has operations defined previously, also you need to use JDK 7+: import static java.lang.System.err; import static java.lang.System.out; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import static java.nio.file.Files.getFileStore; import java.nio.file.Path; import static java.nio.file.Paths.get; import java.nio.file.attribute.UserDefinedFileAttributeView; /** * GET/SET FILES METADATA THROUGH THE NEW JAVA.NIO.FILE.ATTRIBUTE API. * * @author mohamed_taman * * @see java.nio.file.attribute * @see java.nio.file.Files */ public class MetadataOperations { private static FileSystem fs = FileSystems.getDefault(); private static Path path = get("C:", "workspace/NIO2", "resources", "TOC.txt"); public static void main(String... args) { //User-Defined File Attributes View | userDefinedViewsOperations(); } private static void userDefinedViewsOperations() { try { // Check User-Defined Attributes Supportability if (getFileStore(path) .supportsFileAttributeView(UserDefinedFileAttributeView.class)) { // 1- Define a User Attribute. UserDefinedFileAttributeView udfav = Files.getFileAttributeView(path, UserDefinedFileAttributeView.class); out.println("Attrs. before deletion. its size: " + udfav.list().size()); for (String name : udfav.list()) { out.println(udfav.size(name) + " " + name); } int written = udfav.write("file.description", Charset.defaultCharset(). encode("This file contains private information about HOL2846!")); // 2- List User-Defined Attribute Names and Value Sizes. for (String name : udfav.list()) { out.println(udfav.size(name) + " " + name); } // 3- Get the Value of a User-Defined Attribute. int size = udfav.size("file.description"); ByteBuffer bb = ByteBuffer.allocateDirect(size); udfav.read("file.description", bb); bb.flip(); out.println(Charset.defaultCharset().decode(bb).toString()); /** * Note: Using the UserDefinedFileAttributeView.size() method, * you can easily set the correct size of the buffer that represents * the value of the user-defined attribute. * * Note: You can also read an attribute by using the getAttribute() method. * The value is returned as byte array (byte[]). * */ // 4- Delete a File’s User-Defined Attribute. out.println("Attrs. before deletion."); for (String name : udfav.list()) { out.println(udfav.size(name) + " " + name); } udfav.delete("file.description"); out.println("Attrs. after deletion."); for (String name : udfav.list()) { out.println(udfav.size(name) + " " + name); } } else { out.println(path.toAbsolutePath().toString() + ", Doesn't support user defined attributes."); } } catch (Exception e) { err.println(e); } } } ResourcesJavaSE 7,8: Determining Views Supported by a Particular File System JSR 203: More New I/O APIs for the JavaTM Platform (“NIO.2″) Java SE tutorial: File I/O (Featuring NIO.2)Reference: JavaSE: How to SET/GET your own Files and Directory Attributes from our JCG partner Mohamed Taman at the Improve your life Through Science and Art blog....

Best way to learn Java programming? Meet the Java Code Geeks

Java Code Geeks have grown over the years to become a full-fledged Java developers resource center and at the same time one of the most rapidly growing programming communities online. We currently feature a broad collection of Java material to cater to the needs of both the beginner and the seasoned veteran. For the junior developer that is now getting on the Java programming journey, we would suggest to begin with our Java Examples site. There, we feature articles on how to start with Java programming and how to use the basics of the language. There are examples of increasing degree of complexity, so even more experienced Java developers will also benefit from browsing through our archives. For the senior developer, browsing our main website for the latest hot news and premium quality articles is the best option. We feature articles on a vast array of technologies so that even the most demanding readers will get satisfied. Recently, we also launched JCG Academy, full of high-end articles on cutting-edge technologies. Make sure to stop by. We have also grouped those large amounts of Tutorials that have appeared on our site and below are the existing categories:Core Java Tutorials Enterprise Java Tutorials Desktop Java Tutorials Scala Tutorials DevOps TutorialsOur recommended Whitepapers will also help you kick-start your projects in specific technologies ranging from Android and Hadoop, to Linux and Web Development. If you are looking for Java based open source projects, check out our Resources page which mentions various technologies, tools and architectures. If you are already a blogger and feel confident about your programming skills and blogging material, feel free to join our JCG Program which is in ever growing mode (500+ partners). If you are in the search for career opportunities, check out our Job Board with the latest job openings in the industry. Additionally, we recently launched our JCG Newsletter with weekly updates on the latest technologies and the most popular articles on both JCG and the community. By joining the newsletter, as an extra bonus, you will get our brand new e-books, published by Java Code Geeks and our JCG partners for your reading pleasure! The books are titled “JVM Troubleshooting Guide” and “JPA Mini Book”. Hop on the newsletter here. Of course, we have an online presence to all major social channels. Feel free to get social and follow us:Twitter Facebook G+ LinkedInIf you prefer old school RSS, you can find our feed here and you can also get RSS by email here. Finally, when you have some free time, take a look at our About page to find out who are the people behind Java Code Geeks. And of course, feel free to shoot us an email to say “Hi”, we would love to hear from you. That’s all folks! Feel free to share with a friend to show your JCG love! ...

Update the AndroidManifest Version Number automatically

Recently I needed to automate the update of the versionName element in the AndroidManifest.xml file. This needed to be timed stamped and updated with the correct version number when a build was run. We use maven as part of the build, a few plugins come in handy. We want to use POM’s version number so that tools like the maven-release-plugin or maven versions plugin can be used. When these are run the new version number should reflect in the built APKs. The following magic added to the build portion of the pom handles this.       <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>parse-version</id> <goals> <goal>parse-version</goal> </goals> <phase>validate</phase> </execution> </executions> </plugin> <plugin> <groupId>com.google.code.maven-replacer-plugin</groupId> <artifactId>maven-replacer-plugin</artifactId> <version>1.4.1</version> <executions> <execution> <id>replace-version</id> <phase>validate</phase> <goals> <goal>replace</goal> </goals> </execution> </executions> <configuration> <file>AndroidManifest.xml</file> <replacements> <replacement> <token>0.0.0</token> <value>${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}.${maven.build.timestamp}</value> </replacement> </replacements> <quiet>false</quiet> </configuration> </plugin> </plugins> You can add this as part of a profile, and only enable it when you are building say on Jenkins or when you are doing a release. Your AndroidManifest.xml should have the versionName value set to 0.0.0, and when the build runs with the profile enabled it’ll replace this with the pom’s version and also add a time stamp.Reference: Update the AndroidManifest Version Number automatically from our JCG partner David Carver at the Intellectual Cramps blog....

Creating beautiful release notes with git, gradle and markdown

During the last days I asked myself how to generated releases notes from information that are available in commit  / tag messages from git. The decisions My first approach was to create the list of changes directly from the commit messages, but this approach has multiple drawbacks.        The commit messages must be written very disciplined An marker is required to collect messages that belongs to a release (A usual tag would be sufficient for that) The content of the commit messages must follow conventions, so that features, bugfixes and changes could be collected and displayed in one blockSo I go for annotated tags, which must provide a message with a tag. Creating them is fairly easy with git git tag -a v.1.0.0 -m "This is an annotated tag" Sidenote: This kind of tags has a nice addition, it allows to check which commits belongs a specific tag. The next decision was about the markup language that should be used for the messages. Because I’m a fan of markdown, I decided to go for that. This will lead to human readable messages and a well known and working parsing. Important hint Git interprets # usually as the start of a comment. The annotated tags must be created with the option –cleanup=verbatim to suppress this feature if you would like to use more than the first and second header. With this decisions I started to implement a small example in gradle, which creates the release notes during the build process. I the next section I show you the required code Implementation Prerequisites Because I want to have also a beautiful version of the release notes I decided to convert the markdown directly to a html page. For doing this I use PegDown as Markdown processor and twitter bootstrap with bootswatch themes for styling the output. Initial build script buildscript { repositories { mavenCentral() mavenLocal() } dependencies { classpath 'org.pegdown:pegdown:1.4.1' } } import org.pegdown.PegDownProcessor import groovy.text.SimpleTemplateEngine  Implementing the logic We start with the task the controls the process of generating the release notes task releaseNotes() { def releaseNotes = new File('releaseNotes.md') releaseNotes.delete() def versions = "" def tags = readTags() tags.each {tag -> versions += "- [$tag](#$tag)\n" } tags.each {tag -> releaseNotes def readTagMessage(String tag) { def message = [] def proc = "git cat-file tag $tag".execute() def startCollection = false proc.in.eachLine { line -> if (line.isEmpty()) { startCollection = true } if (startCollection) { message += line } } proc.err.eachLine { line -> println line } message }  releaseNotes.tpl This template contains three properties application, releaseNotes and versions. Application is substituted with your applications name and used in the title. releaseNotes contains the converted release notes. And finally versions represents: <?xml version="1.0" encoding="iso-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xml:lang='de' xmlns='http://www.w3.org/1999/xhtml' lang='de'> <head> <title>Release Notes of $application</title> <link rel="stylesheet" href="http://bootswatch.com/yeti/bootstrap.min.css"> <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css"> <style type="text/css"> .releasenotes h1 { font-size: 1.5em; } .releasenotes h2 { font-size: 1.2em; } </style> </head> <body> <div class="row"> <div class="navbar navbar-default"> <div class="col-md-4"></div> <div class="col-md-4"> <h1>Releasenotes</h1> </div> <div class="col-md-4"></div> </div> </div> <div class="row releasenotes"> <div class="col-md-4"></div> <div class="col-md-4">$releaseNotes</div> <div class="col-md-4"><h1>Versions</h1>$versions</div> </div> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> </body> </html> As already stated in the prerequisites twitter bootstrap and a theme from bootswatch is applied to beautify the code. Final After putting everything together we can create a annoated tag and call simply gradle releaseNotes and gradle will read all the messages and tags and create two filesreleaseNotes.md and releaseNotes.html (Example - Thanks to a colleague of mine for his thoughts on layout and design for this version)Conclusion With this simple build script and a little bit conventions we can create release notes from our repository information. Additionally we don’t have to maintain multiple places of release notes, because everything is directly stored in the repository. By using Markdown we have a simple markup and human readable markup language that allows us to create beautiful release notes for our web applications. It’s possible to parse the markdown information directly to a html page, as I did in this example, but you can also provide the simple markdown file and parse it on the client side or at delivery time on your server.As usual the complete code is available on github https://github.com/coders-kitchen/tut-releaseNotesFromTags  Reference: Creating beautiful release notes with git, gradle and markdown from our JCG partner Peter Daum at the Coders Kitchen blog. ...

SpringMVC4 + Spring Data JPA + SpringSecurity configuration using JavaConfig

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

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

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

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