Posts

Showing posts with the label Java

Java Streaming API recipes

Image
In Java, elements in the stream are subdivided into subsets (can be subdivided into further) which are processed in parallel using different cores of the CPU. Therefore, only stateless, non-interfering and associative subsets are eligible to run parallel. These subsets are combined for the short-circuit/terminal process for the final result. The sequential(default) or parallel mode depends on the last used method in the pipeline. Fig.1: Stream Streams API Short-Circuit terminal operations Stream Aggregation Collectors Streams API In the blog post Use of default and static methods , I have introduce how to write a factorial lambda functions using UnaryOperator . You can use the java.util.stream.IntStream.reduce function to calculate the factorial value in the stream as follows. var r =IntStream.range(1, 10).reduce(1,(a,b) -> a*b); Streams handling interfaces: use Java generics. BaseStream - defines core stream behaviours, such as managing the stre...

Java 9 Parallelism

Image
A current computer programming paradigm is not object-oriented anymore; it is about parallelism 1 . In the programming perspective, concurrency is the composition of independently executing processes. Parallelism is the simultaneous execution of computations. Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once. Concurrency is about structure , parallelism is about execution . Introduction Executor CompletableFuture Fig.1: Threading vs parallel tasking Java Futures are the way to support asynchronous operations. The Java fork/join framework and parallel streams divide a task into multiple subtasks and perform those subtasks parallelly on different cores in a single machine. This will avoid blocking a thread and wasting CPU resources. Introduction The key goal of parallelism is to efficiently partition tasks into sub-tasks(fork) and combine results(join). That will improve the performance in the way...

JSF and RichFaces

Image
Recently, I got a project to work on JSF RichFaces 1 . RichFaces project reached end-of-life in June 2016. Thanks to Java backward compatibility I managed to run the RichFaces application on TomEE 7 using Intellij Idea as IDE. Run the following maven archytype in your command prompt as explained in the JBoss Community guide 2 : mvn archetype:generate -DarchetypeGroupId=org.richfaces.archetypes -DarchetypeArtifactId=richfaces-archetype-simpleapp -DarchetypeVersion=4.5.17.Final -DgroupId=au.com.blogspot.ojitha.jsf.ex1 -DartifactId=JSFEx1 Import the project into IntelliJ IDEA (I am using Ultimate 2020.2) Download and install TomEE 3 7.0.81: nothing more than unzip. As shown in the following screenshot, you have to configure TomEE First, open the configuration configure TomEE After configuring the TomEE home directory, goto the deployment tab and add the exploded project because development is easy: changes reflected without redeployment. Add exploded web project to TomE...

Java Collectors recipes

Java Collectors is a utility class with several reduction operations. Here a few of the example you can do with the Collectors class. For example, grouping functionality first. import java.util.stream.Collectors; import java.util.stream.Stream; // basic functionality of the collector Stream.of("one", "two", "three", "four", "five") .collect(Collectors.groupingBy(n -> n.length())); // = {3=[one, two], 4=[four, five], 5=[three]} In the above code, n -> n.length() is the classifier . The return type is Map<Integer, List<String>> in the line# 5 - 6. The grouping allows having a downstream collector which do the subsequent collection operation. For example, // basic functionality of the collector Stream.of("one", "two", "three", "four", "five") .collect(Collectors.groupingBy(n -> n.length() , Collectors.counting())); // = {3=2, 4=...

Java 8: Remedies for What cannot be done in Generics

Image
Generic programming the way to reuse code for Objects of many different types. The unbounded wild card is "?" (which is actually "? extends Object"). You can read from it, but you cannot write. If your type variable is T then you can use only extends (never super ) with T then, the upper-bounded wildcard is "? extends T". you can define read from but can not add (only super support with wildcards) The term covariant preserves the ordering of types from more specific to more general. Collections are covariant when they use extends wildcard. The lower-bounded wildcard is "? super T". Collections are contravariant when they use super with a wildcard. The term contravariant preserves the ordering of types from more general to more specific. Here supplied element must be itself or above of the T . The rule of thumb is "producer => extends and consumer => super": PECS.  As shown in the above, you can copy the eleme...

Java 8: Exception Handling

Image
According to Oracle 1 , Java SE 8 class called java.util.Optional<T> that is inspired from the ideas of Haskell and Scala. In the functional programming, exceptions are side effects and need to avoid. Optional in a Nutshell The Optional class includes methods to explicitly deal with the cases where a value is present or absent. You can create variable Optional<Something> sc = Optional.empty() or Optional<Something> sc = Optional.ofNullable(Something); for null object. Otherwise the Optional<Something> sc = Optional.of(Something) create the Something object. Patterns of using Optional This blog is the summary of the video 2 I went through. The problem is very simply demonstrated in the following code: package au.com.blogspot.ojitha.trainings.exception; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class ExExample { public static void main(String[] args) { Stream.of("a.txt"...

Java Tip: Append a text to a file

Here the simple tip, how to append text to a file. package ojitha.blogspot.com.au; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; /** * Append to the file. * */ public class App { public static void main ( String[] args ) { try { PrintWriter printWriter = new PrintWriter( new BufferedWriter( new FileWriter( "test.txt" , true ))); //PrintWriter printWriter = new PrintWriter("test.txt"); // not the way printWriter.printf( "Hello, how are you %s day!\n" , new Date().toString()); printWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } In the above code, the true parameter in the FileWriter constructor enable to append to the file instead create new one again. Written with StackEdit .

RAD 2– Spring for Vaadin without Spring Boot

Image
In my previous blog RAD 1 – Spring for Vaadin , I have introduced the recommended way of integrating Spring and Vaadin. In this blog, I am going to use the alternative way which is without Spring Boot explained in the article“ Getting started with Vaadin Spring without Spring Boot ”.  This is the hardest way. I’ve configured this in the Intellij Idea 14. Create a maven archetype as explained in the Creating a Project with Intellij Idea :2.8.3 Create Maven Project. Create a new folder WEB-INF under the webapp folder. Create a applicationContext.xml under the WEB-INF folder. Now you have to add the Spring Facet to the project. You have to add the Spring Context created in the step 3. However, I first add the Spring module. My applicationContext.xml is as follows <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance...

RAD–1: Spring for Vaadin 7.4.0

My whole effort to create rapid application development (RAD) stack for Java Web Development. I chose Vaadin for front end development. My development environment is Intellij Idea 14. In this example, I am going to use the recently released Vaadin Spring Add on . As a first, create a spring boot web application. You have to select the “war” option for the packaging and select the option “web” for the dependencies. <dependency> <groupId>com.vaadin</groupId> <artifactId>vaadin-spring-boot</artifactId> <version>1.0.0.alpha2</version> </dependency> <dependency> <groupId>com.vaadin</groupId> <artifactId>vaadin-themes</artifactId> <version>7.4.0</version> </dependency> <dependency> <groupId>com.vaadin</groupId> <artifactId>vaadin-clie...

Java Generics Covariant and Contravariant

Image
Introduction Here the getter method ( ) => A Covariant A <: B ( ) => A <: ( ) => B If a A is subtype of B, then getter or A is subtype of getter of B. Here the setter method A => ( ) Contravariant B => ( ) <: A => ( ) Above Covariant and Contravariant can be explained from the following code: Say A is Animal public class Animal { @Override public String toString(){ return "I am a Animal"; } } Say B is Bear as follows public class Bear extends Animal { @Override public String toString(){ return "I am a Bear"; } }   As shown in the above code Bear is subtype of Animal. Here the Zookeeper class where getter and setter methods are public class Zookeeper { private Animal animal; public void setFeed(Animal animal){ this.animal =animal; } public Animal getFed(){ return this.animal; } } As shown in the above Zookeeper class, there is no indication of Bear, ...

Java Trick: Generic Array Converter

I had a problem of increasing size of the array. Of course I have to copy the array. But it is not easy with java Generics, because of the following problem: public class ArrayUtils<T>{ public T[] resizeArray(T[] source, int offset){ int length = source.length+offset; Object[] aNew = new Object[length]; System.arraycopy(source, 0, aNew, 0, source.length); return (T[])aNew; } } Of course you can compile the ArrayUtils class, but you cannot use this method as shown in the following code segment: public static void main(String[] args){ Integer[] ints = new Integer[2]; ints[0]=0; ints[1]=1; Integer[] newInts = new ArrayUtils<integer>().resizeArray(ints, 3); System.out.println(newInts.length); } Here the error: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; at net.au.abc.abcid.test.ArrayCopyTest.main(ArrayCopyTest.java:9) the problem, aNew never is possible to cast t...

Java Trick: Double brace initialization

This is a trick I found from the Core Java™: Volume I—Fundamentals, Ninth Edition, 6.4.6. Anonymous Inner Classes. import java.util.ArrayList; import java.util.List; public class TestArrayList { private String s1; private static String s2; public static void main(String[] args) { TestArrayList tl = new TestArrayList(); tl.printList(new ArrayList (){ {add("a"); add("b"); add(s2);} }); } public void printList(/*only final variables are accessible to local inner classes*/final List sList){ printDynamicList(new ArrayList (){{add(s1); addAll(sList);}}); } public void printDynamicList(List dList){ } } As shown in the above code: As shown in the line# 10, you can add elements to the anonymous array: this is called Double brace initialization. Again in the line# 16, in the double brace initialization, s1 is added to the array which is a property fo the outer class. To add the parameter in line# 16, it should be final, this is the rule of l...

Spring 3 Part 7: Spring with Databases

Image
This is the 7 th part of the Spring 3 Series . Create MySQL 5.6 database ‘payroll’, CREATE DATABASE payroll; Next create a user for example, user ‘ojitha’ CREATE USER 'ojitha'@'localhost' IDENTIFIED BY 'ojitha'; Need to grant the ‘payroll’ access to user ‘ojitha’ as shown in the following. GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP ON payroll.* TO 'ojitha'@'localhost'; You can download freeware of TOAD for MySQL from here . Let create a first table, that contains all the states in Australia. You can create a table using visually using the icon given directly below the Tables tab in the Object Explorer as shown in the above diagram. CREATE TABLE payroll.STATE ( CODE CHAR(3) ASCII COMMENT 'State code', STATE VARCHAR(30), PRIMARY KEY (CODE) ) ENGINE = InnoDB COMMENT = 'Australian states' ROW_FORMAT = DEFAULT; In the my sql console you can the newly added table using the following command SHOW ...