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;
}


}



Sunday, December 16, 2018

Java Interview Preparation article : OOPS concept

This is continuation of Java Interview Preparation . Here we will see OOPS concept. Encapsulation, Abstraction, Inheritance and Polymorphism are the basic pillars of object oriented programming language. And how Java adhere to these principle is crucial. These topics are covered in almost all the java book or can be found over internet also. Here is one link.

While answering abstraction and encapsulation it may sound overlapping. My explanation for encapsulation is, inside class all the members would be private to prohibit direct access of them from out side of the class. The public methods are for carry out various operation. And the caller of those methods need not know the internal implementation, only the meaning of required arguments to invoke the method is sufficient to achieve the goal. This is called abstraction.

In Java inheritance is achieved by "extends" and "implements" key word. It means either by extending another class or implementing a interface.
Child class is always a super set of parent class. Its also known as "is a" relation ship. There cloud be many questions under this topic. How the objects get created, the order of invocation of constructors. How a parent class reference can hold a child class object etc. Why java doesn't allow multiple inheritance. What are marker interface ? Several questions fall under this.

This is an nice article to understand polymorphism. There are two aspects of this compile time polymorphism and run time polymorphism.

https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/
https://www.dineshonjava.com/compile-time-polymorphism-in-java/

There could be other question like difference between aggregation vs composition.
"is a" vs "has a"
How can you achieve multiple inheritance in java ? ( By interface)

But I feel the major three concepts will put you in good spot to attempt the question around it.

Sunday, December 9, 2018

Java Interview Preparation article :1

Time and again I get requests to write on preparation for interviews in Java. So I am planning to write series of post targeting interview preparation.
To start if the interview is for service based company the key is breadth. And for product based company its the depth. The exception for (breadth/depth) is directly proportional to years of experience.
Another point I want to make entry level roles (0 years to 5 years) you need to do well in java interview rounds to get selected. For more experience this round is kind of elimination round.

Topics in core Java

  1. OOPs concept
  2. Java key word, more priority to the latest released key words.
  3. Inheritance, interface, marker interface, abstract class and is a has a relationship  
  4. Enums
  5. The details about java.lang.Object 
  6. Strings 
  7. Exception handling
  8. Collections 
  9. Threads and Concurrent Package
  10. Design Pattern
All these topics will cover good amount of ground. There might be some here and there question about garbage collection, jvm architecture, java memory management etc. Those questions were more relevant when java was dominant. Now we see the increase popularity of python, Scala so its kind of ok to focus energy in understanding other topics.

Once you get thorough these topic next stage is Java in web development, which we will see in another post. 

Tuesday, August 7, 2018

BlockingQueue

Producer - consumer problem arises in multi thread environment. This can be defined when there are one or more threads generate data independently and same time one or many threads read those data to process independently.

To solve this we can have an array and there would be synchronized method to access. So when one thread only can either read/write at same time. If the array is full, producer threads need to wait. And if the array is empty consumer threads need to wait.

java.util.concurrent package comes with Blocking queue which is very handy to solve this problem.
Blocking queue is an interface. ArrayBlockingQueue  is an concrete implementation of interface. It allow both wait or fail for producer if the queue is full, same way for consumer it fails or waits if the queue is empty.

Some sample codes can be foundin https://github.com/pallabrath/myexpjava/tree/master/myexpjava/src/demo/blockingQueue

What we discussed here is in the scope of single instance. If we want scale then there would be more than one instance. In that case of distributed environment we need different kind of solution. Java message queue fit into this situation.

Again if we scale further and we want to process data in large volume, Kafka goes well in the distributed environment. Kafka itself run on one or many node to scale.

We will discuss Kafka in a separate thread.

Saturday, June 10, 2017

I too want to be cloud developer

In last few years cloud was one of those word which we developer hardly spend a day with out listening. In fact its becoming quite louder and in future we will see more software run in cloud. As a developer I always wonder cloud means what change in my design and coding. Any way my java program need a JVM whether its on premise or in cloud how does it change. Users will see my web app through a browser what changes if it served from a on premise web server or a cloud web server at the end we need a Java servlet container to run our server side code. So how will I adapt to this cloud computing ?

As I started seeing cloud from more close quarter, I can say with some minor tweaks we can leverage the power of cloud computing. While talking about the cloud the next word come to my mind is "elasticity". It means our IT resources like computing storage etc can seamlessly expand and contract based on the need. With out upfront H/W cost we will pay as we use and we will use as we need. This particular things bring down the cost of IT. So for a developer like us increase the scope of further imagination. We can have more storage and compute as we need.

To appreciate the elasticity nature of the cloud our software design should be truly distributed and loosely coupled. If the software is segregated in different independent component then its very easy for a particular component can scale to meet demand, which will be the most efficient use of resource. All these things are also popularly known as micro service architecture.

Another good thing is cloud vendors provide a lots of standard software building blocks and technique. So we can quickly turn around new features and software.

I believe that cloud will make software more affordable so that more people can use the power computing.

Sunday, April 9, 2017

Automation is boon or bane

"Automation" dictionary meaning is "the use or introduction of automatic equipment in a manufacturing or other process or facility. And the next line is ‘unemployment due to the spread of automation’. This word is quite old probably its in practice from 1940. So when we read lots of stories like impact of automation and job loss because of it, I wonder how this problem is not solved yet.
If we look back Human evolution, apart from the biological changes we are continuously improving tools and adapting to use them. So we invent and discover something lets say motor car. then we try to produce them in scale by setting up factory and establishing process. And slowly we delicate these task to different tools which are machine, robots and computers. In this process we force our fellow human from one form of job to another. So we always move to more productive things.

I belong to digital industry which thrives on the possibility of automation. Computers and software are catalyst for automation. After automating different industry now we are looking inside. It means IT will be more efficient in term of economy more people can afford and use.

For a developer perspective if we look beyond job risk, there are lots of possibilities are in horizon. Now all the development platform or systems are automatically provisioned. So we can have more servers, compute more storage to write and test our code. With test automation we will be more confident on our changes and quality. With automatic monitoring the health of our production system and software our systems will be more reliable. We are having smart editor which generate some part of code to assist developers. So in less time we can code more features.

My point is automation is a contentious process and an ultimate truth. The one who adapts it open to learn new productive way of doing always thrive.


Thursday, June 16, 2016

Magic with Computers

The expectation from a computer is always to do something which surprise us, which complement human brain in terms of memory, processing, decision making, thinking and imagining. When I say computer, it includes smart phone, tablets or wearable devices. When we compare it with washing machine, refrigerator or lift, we always expect more out of a computer.
First time when ATM machines were introduced,  people were amazed how banking can be experienced seamlessly. You can deposit money in one location and withdraw from a different location instantly. When we first time sent an email, or did video chat all were magical experience.

But Now a days all these look normal and nothing great about it. So for a programmer whats next ?
what are the things or feature will get that "wow" from the user, keeping in mind now a days almost every one has been introduced to Facebook and google.

I feel below points will help to do the magic.

Simple UI

Its very easy to say simple ui, all of us know and its a quite old rule. But still it holds good and the people consciously or sub consciously decide whether to use or not based on user experience.

There is no rule or some way you can measure whether the one design is better than other. But certainly there are lots of good practices. I believe deeper understanding of the problem and solution based on user perspective, knowing different attribute of your target audience like region, language, age group, popular culture of target audience will certainly help enhance for better user experience.

User experience is so important that, if you skip reading the below points from now, still you can get a wow from the user.

Input / Command

We appreciate some one obey the commands and do our work, But we love and addict to those who do the required task with out the command.
The less input,intervention is required for system to work enhance user experience . While designing system we can follow some philosophy like  don't ask for explicit input, rather than observe it from the environment or historical data.

Prediction

Dare to predict and suggest and improve your prediction based on time. Always try to add some more value to the user.

Its a continuous process, reiterate the above point  time to time.

Let me know your thoughts how to get a wow ....




Monday, June 29, 2015

Java Immutable Object

The simple definition of immutable object is "An object called immutable whose states can't be changed after it constructed". It means every time we need to alter the state we actually end up having a new object. The best example is "java.lang.String".

Some body might be thinking its actually overhead, this practice ends up creating too many objects. Actually over the time with optimization of garbage collection and the cost of creating new objects decreases. So in a situation where you want to define constant, or say a multi threading case immutable objects work well. As the value doesn't change at any stage, we are assured of dirty or inconsistent value.

Lets understand how to create our own immutable object.

1) Make the class final, to stop any other class to extend.
2) All fields in the class should be private and final.
3) Since we don't want the state of the object to change,  there should not be any setter method.
4) Any method which require to change the state, must create a new object with updated state.

For Ex:

final public class MyCar
{
     private final String registrationNumber;
     public MyCar(String registrationNumber)
     {
        this.registrationNumber = registrationNumber;
     }
     public String getRegistrationNumber()
    {
        return registrationNumber;
    }
    public MyCar upgradeCar(String newCarRegNo)
    {
       return new MyCar(newCarRegNo);
    }
}