Wednesday, 28 June 2017

Object-Oriented Declarative Input/Output in Cactoos

Cactoos is a library of object-oriented Java primitives we started to work on just a few weeks ago. The intent was to propose a clean and more declarative alternative to JDK, Guava, Apache Commons, and others. Instead of calling static procedures we want to use objects, the way they are supposed to be used. Let’s see how input/output works in a pure object-oriented fashion.
Let’s say you want to read a file. This is how you would do it with the static method readAllBytes() from the utility class Files in JDK7:

Tuesday, 27 June 2017

Use Precise Java Method Parameters

Learn how to pick the right method parameter types and get more robust and shorter code in your Java applications.

We Java developers generally have a bad habit of using method parameters without thinking of what is actually needed and just picking whatever we are used to, what we have available or whatever first comes into mind. Consider the following representative example:

Thursday, 22 June 2017

How to Convert JSON data from file to ArrayList?

In below example file student_data.txt having collections of students data in JSON form and through these Jacson API’s will convert JSON data to ArrayList java object.

Pre-Requisite 


Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

Wednesday, 21 June 2017

Java 8 New Features : Lambda Expressions, Optional Class, Defender Methods With Examples

Java 8 is already released by Oracle last year. It is the most feature rich update then the previous version 6 and 7 , which both were somehow minor updates .

The major features of the java 8 are as follows :
  1. Introduction of Optional
  2. Defender Methods
  3. Lambda Expressions

Tuesday, 20 June 2017

Threads, Lifecycle Explained With Example

What is Thread ?


Thread is a sequence of code executed independently with other threads of control with   in a single executed program .

for example : Here we are going to calculate the sum of next hundred numbers from the given input number by the user.

Monday, 19 June 2017

6 Difference between forward() and sendRedirect() in Servlet - Java

Servlet in JEE platform provides two methods forward() and sendRedirect() to route an HTTP request to another Servlet for processing. Though, both are used for forwarding HTTP requests for further processing there are many differences between forward() and sendRedirect() method e.g. forward is performed internally by Servlet, but a redirection is a two-step process, where Servlet instruct the web browser (client) to go and fetch another URL, which is different from the original. That's why forward() is also known as a server-side redirect and sendRedirect() is known as the client-side redirect. Becuase of their usefulness, the difference between forward() and sendRedirect is also a frequently asked Servlet interview question.

Thursday, 15 June 2017

How to unzip files from zip file by java?

In Java java.util.zip package provide below classes and api’s to convert files to zip file.

ZipInputStream: This class implements an input stream filter for reading files in the ZIP file format.

ZipEntry: Class is used for zip entry.

In below example will show to unzip files from a zip file  and store in folder

Wednesday, 14 June 2017

Elasticsearch REST Java Connection Client

For Elasticsearch connection, Elasticsearch REST Java API provide RestClient and RestClient.build() to get connection.

Below connection client class covers all the ways of connectivity to elastic search depend of elastic servers configuration and  accessibility accordingly you can uncomment below methods in customize Http Client.  I made this class as Singleton because Elasticsearch client keep connection persistent.

Tuesday, 13 June 2017

How to Convert JSON to Java Object and Java Object to JSON?

In below java codes consider both the cases from JSON to Java Object and Java Object to JSON by ObjectMapper by Jacson API’s

I have given generic method for both the cases as convertJavaObjectToJSON and convertJSONToJavaObject.

Pre-Requisite : Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

Saturday, 10 June 2017

How to enable Spring Security in Java Web application?

Spring Security is one of the most popular frameworks to implement security in Java web application in a declarative way. It provides several essential security features e.g. LDAP authentication, authorization, role-based access control,  remembers the password, URL protection, concurrent active sessions management etc. In order to enable Spring security in Java Web application, you need to do configure three things, declare a delegating proxy filter in web.xml, add the ContextLoaderListener in web.xml and provide actual security constraints on applicationContext-Security.xml file. Since Spring security uses a chain of filters to implement various security constraints, also known as Spring's "security chain filter", it relies on web container for the initialization of delegating filter proxy.

Thursday, 8 June 2017

Difference between Servlet and JSP?

Servlet and JSP are two of the most popular Java web technologies to generate dynamic content in Java web applications there is some key difference between them. For example, Servlet is designed for Java developers as most of the coding is done in Java, while JSP was designed and developed for web GUI developer e.g. guys who write HTML and JavaScript and that's why you see the coding in JSP is tag based. Even though you can use HTML tags as String inside Servlet and Java code as Scriptlet inside JSP, both are considered as bad practice and should be avoided at all cost because they are very hard to maintain. The different nature of Servlet and JSP also allows frontend and backend developers to work in parallel, JSP work is mostly done by frontend developers while Servlet work is done by backend developers.

Monday, 5 June 2017

CRUD Java Application with Couchbase, Java EE and WildFly

Couchbase is an open-source, NoSQL, document database. It allows to access, index, and query JSON documents while taking advantage of integrated distributed caching for high performance data access.

Developers can write applications to Couchbase using different languages (Java, Go, .NET, Node, PHP, Python, C) multiple SDKs. This blog will show how you can easily create a CRUD application using Java SDK for Couchbase.

Friday, 2 June 2017

Efficient Counter in Java

You may often need a counter to understand the frequency of something (e.g., words) from a database or text file. A counter can be easily implemented by using a HashMap in Java. This article compares different approaches to implement a counter. Finally, an efficient one will be concluded.

1. The Naive Counter


Naively, it can be implemented as the following:

String s = "one two three two three three";
String[] sArr = s.split(" ");

Thursday, 1 June 2017

What exactly is null in Java?

Let's start from the following statement:

String x = null;

1. What exactly does this statement do?


Recall what is a variable and what is a value. A common metaphor is that a variable is similar to a box. Just as you can use a box to store something, you can use a variable to store a value. When declaring a variable, we need to set its type.

Wednesday, 31 May 2017

Binary tree post order traversal in Java with example

Like many tree algorithms, the easiest way to implement post-order traversal is by using recursion. In fact, if you know how to write pre-order using recursion, you can use the same algorithm with bit of adjustment to implement post order traversal. All you need to do is instead of printing the value of node first, just call the recursive method with left subtree as shown in our example.

Unlike in-order traversal which prints all nodes of binary search tree in sorted order, post-order doesn't provide sorting but its useful while deleting nodes from binary tree, see a good book on data structure and algorithms e.g. Introduction to Algorithms by Thomas H. Cormen to learn more about different usage of post-order traversal in Computer Science and programming.

Monday, 29 May 2017

Java: Read Large XML by Using StAX

The following code shows how to read XML file in Java. It uses StAX API which reads xml files sequentially. If you want to read a large xml file, and get outofmemory error, you should be able to solve the problem by using the code below. The solution below read the xml file sequentially, and can process very large xml files, such as 10G or 20G. Therefore, it is a scalable solution!

Friday, 26 May 2017

java.util.ConcurrentModificationException

This post shows show to solve the problem of java.util.ConcurrentModificationException for ArrayList.

The error message looks like the following:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
...
...

Thursday, 25 May 2017

Constructors of Sub and Super Classes in Java?

This post summarizes a commonly asked question about Java constructors.

1. Why creating an object of the sub class invokes also the constructor of the super class?


class Super {
    String s;

    public Super(){
    System.out.println("Super");
    }
}

Thursday, 18 May 2017

Inheritance vs. Composition in Java

This article illustrates the concepts of inheritance vs. composition in Java. It first shows an example of inheritance, and then shows how to improve the inheritance design by using composition. How to choose between them is summarized at the end.
 

1. Inheritance


Let's suppose we have an Insect class. This class contains two methods: 1) move() and 2) attack().

Wednesday, 17 May 2017

JVM Statistics with jstat

I have written about several command-line tools provided with the Oracle and/or OpenJDK Java Development Kits (JDKs) in the past, but I’ve never written exclusively about the jstat tool. The Oracle JDK 9 Documentation Early Access states that jstat is used “to monitor Java Virtual Machine (JVM) statistics.” There is also a warning, “This command is experimental and unsupported.” Although I quoted the JDK 9 documentation, jstat has been a part of the Sun/Oracle JDK in some form (known at one time as jvmstat) in Java SE 8, Java SE 7, Java SE 6, and J2SE 5. Instrumentation for the HotSpot JVM was introduced with Java 1.4.1 (only enabled when -XX:+UsePerfData was set) and has provided “always-on instrumentation” since Java 1.4.2.

Tuesday, 16 May 2017

The Introduction of Java Memory Leaks

One of the most significant advantages of Java is its memory management. You simply create objects and Java Garbage Collector takes care of allocating and freeing memory. However, the situation is not as simple as that, because memory leaks frequently occur in Java applications.

Monday, 15 May 2017

The substring() Method in JDK 6 and JDK 7

The substring(int beginIndex, int endIndex) method in JDK 6 and JDK 7 are different. Knowing the difference can help you better use them. For simplicity reasons, in the following substring() represent the substring(int beginIndex, int endIndex) method.

Thursday, 11 May 2017

Introduction to JDBC

Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. JDBC can also be defined as the platform-independent interface between a relational database and Java programming. It allows java program to execute SQL statement and retrieve result from database.

JVM Architecture in Java

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

JVM Architecture , Java Tutorials

Wednesday, 10 May 2017

Java OOPs Concepts

In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming paradigm where everything is represented as an object, is known as truly object-oriented programming language.

Smalltalk is considered as the first truly object-oriented programming language.

Thursday, 4 May 2017

JDBC from the Oracle Service Bus

There are different ways to do database calls from the Oracle Service Bus. In this blog post I look at several methods.

The methods looked at;
1 using an external webservice (without OSB)
2 using an external webservice proxied by the OSB
3 using the fn-bea:execute-sql function from the OSB
4 using the JCA DbAdapter from the OSB provided by Oracle as part of Oracle SOA Suite

Oracle Java, JDBC, Oracle Java Tutorials and Materials, Oracle Java Guide

Monday, 1 May 2017

Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Sunday, 30 April 2017

Java Force Garbage Collection – Code Example

Garbage collection in java can not be enforced. But still sometimes, we call the System.gc( ) method explicitly. System.gc() method provides just a "hint" to the JVM that garbage collection should run. It is not guaranteed!

The API documentation for System.gc() states that "When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects." The responsibility for a programmer is to make sure no references remain for objects.

Friday, 28 April 2017

What Is Inner Interface in Java?

What is Inner Interface in Java?


Inner interface is also called nested interface, which means declare an interface inside of another interface. For example, the Entry interface is declared in the Map interface.

public interface Map {
interface Entry{
int getKey();
}

void clear();
}

Monday, 24 April 2017

When and how a Java class is loaded and initialized?

In Java, you first write a .java file which is then compiled to .class file during compile time. Java is capable of loading classes at run time. The confusion is what is the difference between "load" and "initialize". When and how is a Java class loaded and initialized? It can be clearly illustrated by using a simple example below.

What does it mean by saying "load a class"?


C/C++ is compiled to native machine code first and then it requires a linking step after compilation. What the linking does is combining source files from different places and form an executable program. Java does not do that. The linking-like step for Java is done when they are loaded into JVM.

Wednesday, 19 April 2017

How does Java handle aliasing?

What is Java aliasing?


Aliasing means there are multiple aliases to a location that can be updated, and these aliases have different types.

In the following example, a and b are two variable names that have two different types A and B. B extends A.

B[] b = new B[10];
A[] a = b;

Friday, 14 April 2017

Java Thread: notify() and wait() examples

This post contains two code examples to demonstrate Java concurrency. They stand for very typical usage. By understanding them, you will have a better understanding about notify() and wait().

1. Some background knowledge

  1. synchronized keyword is used for exclusive accessing.
  2. To make a method synchronized, simply add the synchronized keyword to its declaration. Then no two invocations of synchronized methods on the same object can interleave with each other.
  3. Synchronized statements must specify the object that provides the intrinsic lock. When synchronized(this) is used, you have to avoid to synchronizing invocations of other objects' methods.

Thursday, 13 April 2017

So Java passes object by reference or by value?

This is a classic interview question which confuses novice Java developers. In this post I will use an example and some diagram to demonstrate that: Java is pass-by-value.

1. Some Definitions


Pass by value: make a copy in memory of the actual parameter's value that is passed in.
Pass by reference: pass a copy of the address of the actual parameter.

Wednesday, 12 April 2017

How Static Type Checking Works in Java?

Java uses static type checking to analyze the program during compile-time to prove the absence of type errors. The basic idea is never let bad things happen at runtime. By understanding the following example, you should have a good understanding of how static type checking works in Java.

Oracle Java Tutorials and Materials, Oracle Java Certifications, Oracle Java Guide

Tuesday, 11 April 2017

What do Java objects look like in memory during run-time?

We know functions are implemented in memory as a stack of activation records. And we know Java methods are implemented as a stack of frames in JVM Stack and Java objects are allocated in Heap.

How do Java objects look like in heap? Once an object is laid out in memory, it's just a series of bytes.

Then how do we know where to look to find a particular field? Keep an internal table inside the compiler containing the offsets of each field.

Monday, 10 April 2017

What does a Java array look like in memory?

Arrays in Java store one of two things: either primitive values (int, char, ...) or references (a.k.a pointers).

When an object is creating by using "new", memory is allocated on the heap and a reference is returned. This is also true for arrays, since arrays are objects.

Wednesday, 5 April 2017

Java Web Application sending JSON messages through WebSocket to HTML5 browser application for real time push

This article describes a Java EE 7 web application that exposes a REST service that handles HTTP POST requests with JSON payload. Any message received is sent through a Web Socket to the web socket (server) endpoint that is published by a Java Class deployed as part of the web application. A static HTML page with two associated JavaScript libraries is opened in a web browser and has opened a web socket connection to this same end point. The message sent from the REST service endpoint to the web socket endpoint is pushed through the web socket to the browser and used to instantly update the web page.

Saturday, 1 April 2017

Best Practices for Multithreading in Java

A thread is a path of execution within a process. Multithreading is the ability to improve the overall throughput of an application by providing a way to execute many threads simultaneously. This article presents a discussion on the best practices that should be adopted when working with multi-threading in enterprise applications.

What is multithreading and why is it useful?


Multithreading may be defined as the ability to have multiple threads in memory with one of them in the execution state. Threads share the resources of a process that includes memory resources, process data and open files. This, though it helps to make your application more efficient, might cause issues at runtime due to concurrent access to the same resource.

Tuesday, 21 March 2017

Java Callout from Business Rules

Goal and warning


This blog will show how to invoke java code directly from within a Business Rules component. I didn’t manage to find this in the Oracle product documentation, which is actually a good thing. Invoking java code with business logic directly from within the Business Rules is normally bad design. The proper way to do it would be to first invoke business rules and then – depending on the outcome – invoke the appropriate business logic. Hence, the proper place for business logic is outside of the business rules.
However, for more technical requirements, it may be convenient to do a java callout from within the business rules. The sample situation we have is that a logging line will be generated upon a ‘case start event’. No business logic!

Friday, 3 March 2017

JDBC from the Oracle Service Bus

There are different ways to do database calls from the Oracle Service Bus. In this blog post I look at several methods.

The methods looked at;
1 using an external webservice (without OSB)
2 using an external webservice proxied by the OSB
3 using the fn-bea:execute-sql function from the OSB
4 using the JCA DbAdapter from the OSB provided by Oracle as part of Oracle SOA Suite

Wednesday, 22 February 2017

Implementing the Singleton Design Pattern in Java

The Singleton design pattern is one of the most popular design patterns in use. The Singleton design pattern is one of the Gang of Four's (GOF) design patterns and belongs to the Creational Design Pattern category. This article presents a discussion on the Singleton design pattern, its benefits and how it can be implemented in Java.

What is the Singleton Design Pattern?

The Singleton design pattern is used to restrict instances of a class to just one instance. This design pattern states that there can be one — and only one — instance of a class throughout the application's lifecycle. Essentially, a singleton class is one that can have just one instance throughout the application's life cycle and provides a global point of access to it.

Tuesday, 21 February 2017

Working with Files and I/O in Java

The java.nio package contains the types required to perform input output operations in Java. The introduction of the java.nio package has simplified input — output operations. This article presents a discussion on how to perform input — output operations in Java with special focus on the java.nio package.

When you work with files for I/O, you basically work with streams. A stream may be defined as a sequence of bytes. There are two types of streams. These include: input stream and output stream. While the former is used to read data from a source, the latter is used to write data to a destination.

Wednesday, 11 January 2017

Extracting JavaDoc documentation from source files using JavaParser

A lot of people are using JavaParser for the most different goals. One of these is extracting documentation. In this short post we will see how you can print all the JavaDoc comments associated to classes or interfaces.

Code is available on GitHub: https://github.com/ftomassetti/javadoc-extractor

Getting all the Javadoc comments for classes

Tuesday, 10 January 2017

HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap

Map is one of the most important data structures in Java. In this post, I will illustrate how to use different types of maps, such as HashMap, TreeMap, HashTable and LinkedHashMap.

1. Map Overview


HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap

Monday, 9 January 2017

Java read a file line by line – How Many Ways?

The number of total classes of Java I/O is large, and it is easy to get confused when to use which. The following are two methods for reading a file line by line.

Method 1:

private static void readFile1(File fin) throws IOException {
FileInputStream fis = new FileInputStream(fin);

Friday, 6 January 2017

Monitors – The Basic Idea of Java Synchronization

If you took operating system course in college, you might remember that monitor is an important concept of synchronization in operating systems. It is also used in Java synchronization. This post uses an analogy to explain the basic idea of "monitor".

1. What is a Monitor?

A monitor can be considered as a building which contains a special room. The special room can be occupied by only one customer(thread) at a time. The room usually contains some data and code.

Thursday, 5 January 2017

Why do we need Generic Types in Java?

Generic types are extensively used in Java collections. Why do we need Generic types in Java? Understanding this question can help us better understand a lot of related concepts. In this article, I will use a very short example to illustrate why Generic is useful.

Wednesday, 4 January 2017

Working with Abstract Classes and Interfaces in Java

There are three important constructs in Java — concrete classes, abstract classes and interfaces. An abstract class is a special type of a class that is marked with the abstract keyword to indicate that the class cannot be instantiated but can be inherited if need be. An interface is actually a purely abstract class. We will explore more on both of these as we progress through this article. This article presents a discussion on when and how to use abstract class and interface when working with enterprise applications in Java.

Tuesday, 3 January 2017

Unit testing Java data classes immutability with the Mutability Detector

In all our project, we use data classes which, by definition, contain data (fields) but no (business) logic.

According to the best coding practices, a data class should preferably be immutable because immutability means thread safety.

An immutable class has several interesting properties:

Monday, 2 January 2017

How to create a ZIP File in Java? ZipEntry and ZipOutputStream Compression Example

Since compressing and archiving old log file is an essential housekeeping job in any Java application environment, a Java programmer should know how to compress files in .zip format and then how to read them programmatically if required. The JDK provides full support to create and read ZIP files in Java. There is a separate package java.util.zip to hold all classes related zipping and unzipping files and streams.