Sunday, December 30, 2018

Java 8 at a glance

In Java  8 following are the major enhancement.

- Lambda Expression
- Method Reference for Lambda Expression
- Java Streams
- Improved Interface

    a) Now we can have concrete methods in an interface. It can be either static or default. Default methods can be overridden in implemented class. If a class implement two or more interface and there is a collision of default method then it is mandatory to override.
    b) Functional interface. For lambda expression we can define an interface as function it will have only one abstract method.
Here is an good article explaining in details # https://www.journaldev.com/2752/java-8-interface-changes-static-method-default-method

- Enhancement to Annotation
More details # https://www.javatpoint.com/java-8-type-annotations-and-repeating-annotations

- Parallel Array Sorting
    java.util.Arrays support sorting in parallel which will be faster.
- Hash Map performance improvement in case of Key collision
- Removed JDBC-ODBC bridge


More details on Java 8 features
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html

Friday, December 28, 2018

Java Streams

Streams are very popular feature in Java 8. Its another step in the direction of supporting functional programming in Java.
Streams are a way of accessing data from various data source. Data source can be an array, any java collection objects, I/O channel (like files, socket etc) or a generator function. One important thing is Streams are not data structure it doesn't store data, it just convey the data from data source.

Streams facilitate various computational operations like fetch, filter, sort, aggregate, search etc. in a efficient way. But all these operations produces a result while not changing its source.
Stream operations are of two types,  intermediate or terminal .Filter and map are examples of intermediate operation For each and reduce are terminal operation. Intermediate operation doesn't get executed instantly ,it creates a new stream. Only after terminal operation it get evaluated.

Intermediate operations are further divided into stateless or stateful. In case of stateless like filter or map no state of previous element is required. But in case of sateful eg: sort or distinct to process new element previous element details are necessary.

By default streams are executed sequential, Streams support parallelism also. So that the elements can be processed in parallel manner.  

Lets see some code.

package demo.streams;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamDemo {

public static void main (String args[])
{
String[] arr = {"python", "perl", "java", "java script", "c", "c++", "html", "sql"};
List<String> strList =  Arrays.asList(arr);
// steam creation
Stream<String> stream  = strList.stream();
// sort the elements
stream.sorted().forEach(System.out::println);
// find first element starts with j
Stream<String> filteredStream = strList.stream().filter(string-> string.startsWith("j"));
System.out.println(filteredStream.findFirst().get());
// in first 4 element how many elements start with p
System.out.println(strList.stream().limit(4).filter(str->str.startsWith("p")).count());
// map
// prepend hello begin of each string
strList.stream().map(str->"Hello "+str).forEach(System.out::println);
// close
filteredStream.close();
stream.close();
// parallel Stream, count the number of letters
strList.parallelStream().map(str->str + "="+ str.length()).forEach(System.out::println);
}
}


Saturday, December 22, 2018

tnsnames.ora parsing in java

tnsnames.ora is a configuration file which store the information about network service names and connect descriptor. These information are vital to connect the database.  More details about tnsora can be found here. https://docs.oracle.com/database/121/NETRF/tnsnames.htm#NETRF259

The configurations are defined key value manner. value can be literal or one or multiple key values again. Syntax rule can be found here https://docs.oracle.com/cd/A57673_01/DOC/net/doc/NWUS233/apb.htm                                            
To parse the same in Java please refer below code


import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class TnsOraParser {
private static final String COMMENT = "#";
private Stack<Parameter> stack = new Stack<Parameter>();
private List<Parameter> netServiceNames = new ArrayList<Parameter>();
private boolean bracketOpen;
public TnsNamesOra parse(InputStream is) {
Scanner scan = new Scanner(is);
StringBuilder buffer = new StringBuilder();
boolean quote = false;
while (scan.hasNextLine()) {
String aLine = scan.nextLine();
aLine = aLine.trim();
if (aLine.startsWith(COMMENT)) {
continue;
}

for (int i = 0; i < aLine.length(); i++) {
char ch = aLine.charAt(i);
if (ch == '"')
{
quote = !quote;
}
else if (quote)
{
buffer.append(ch);
continue;
}
else if (ch == ' ' || ch == '\n' || ch == '\r') {
continue;
}
if (ch == '=')
{
gotNewParam(buffer);
}
else if (ch == '(')
{
bracketOpen = true;
}
else if (ch == ')')
{
bracketOpen = false;
Parameter cp = stack.pop();
if (cp != null)
{
if (buffer.length() > 0)
{
cp.setValue(buffer.toString());
buffer.delete(0, buffer.length());
}
if (!stack.isEmpty())
{
stack.peek().addParm(cp);
}
}
}
else
{
buffer.append(ch);
}
}
}
scan.close();
return new TnsNamesOra(netServiceNames);
}

private void gotNewParam(StringBuilder buffer) {
Parameter param = new Parameter(buffer.toString());
if (!bracketOpen && stack.size() == netServiceNames.size())
{
netServiceNames.add(param);
}
buffer.delete(0, buffer.length());
stack.push(param);
}

public static void main(String args[]) throws Exception {
FileInputStream testFile = new FileInputStream("D:\\Work\\tnsnames.ora");
TnsOraParser tnsOraParser = new TnsOraParser();
TnsNamesOra tnsOra = tnsOraParser.parse(testFile);
System.out.println(tnsOra.getServiceNames());
}
}


Parameter .java
==============

import java.util.ArrayList;
import java.util.List;

public class Parameter {
private String name;
private String value;
private List<Parameter> parameters;

public Parameter(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public List<Parameter> getParameters() {
return parameters;
}

public void setParameters(List<Parameter> parameters) {
this.parameters = parameters;
}

public void addParm(Parameter cp) {
if (parameters == null) {
parameters = new ArrayList<Parameter>();
}
parameters.add(cp);
}

public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(name + "=(" );
if (value != null)
{
sb.append(value);
}
else if (parameters != null)
{
for (Parameter param : parameters)
{
sb.append(param);
}
}
sb.append(")");
return sb.toString();
}


}

TnsNamesOra.java
==================

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TnsNamesOra {
private List<Parameter> netServiceName;
private final String DESCRIPTION_LIST = "DESCRIPTION_LIST";
private final String DESCRIPTION = "DESCRIPTION";
private final String ADDRESS_LIST = "ADDRESS_LIST";
private final String ADDRESS = "ADDRESS";
private final String PROTOCOL = "PROTOCOL";

public TnsNamesOra(List<Parameter> netServiceNames) {
this.netServiceName = netServiceNames;
}

public List<String> getServiceNames() {
List<String> serviceNames = null;
if (netServiceName != null) {
serviceNames = new ArrayList<String>();
for (Parameter param : netServiceName) {
serviceNames.add(param.getName());
}
}
return serviceNames;
}


}