We used have  Singleton Design Pattern in our applications whenever it is needed. As we know that in singleton design pattern we can create only one instance and can access in the whole application. But in some cases, it will break the singleton behavior.

There are mainly 3 concepts which can break singleton property of a singleton class in java. In this post, we will discuss how it can break and how to prevent those.

Here is sample Singleton class and SingletonTest class.

Singleton.Java

package demo1;

public final class Singleton {

    private static volatile Singleton instance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

SingletonTest.java


package demo1;

public class SingletonTest {
    public static void main(String[] args) {
        Singleton object1 = Singleton.getInstance();
        Singleton object2 = Singleton.getInstance();
        System.out.println("Hashcode of Object 1 - " + object1.hashCode());
        System.out.println("Hashcode of Object 2 - " + object2.hashCode());
    }
}

Here is output, you can see it the same hashcode for objectOne and objectTwo

Hashcode of Object 1 - 1836019240
Hashcode of Object 2 - 1836019240

Now we will break this pattern. First, we will use java reflection.

Reflection

Java  Reflection is an API which is used to examine or modify the behavior of methods, classes, interfaces at runtime. Using Reflection API we can create multiple objects in singleton class. Consider the following example.

ReflectionSingleton.java

package demo1;

import java.lang.reflect.Constructor;

public class ReflectionSingleton {
    public static void main(String[] args)  {

        Singleton objOne = Singleton.getInstance();
        Singleton objTwo = null;
        try {
            Constructor constructor = Singleton.class.getDeclaredConstructor();
            constructor.setAccessible(true);
            objTwo = (Singleton) constructor.newInstance();
        } catch (Exception ex) {
            System.out.println(ex);
        }

        System.out.println("Hashcode of Object 1 - "+objOne.hashCode());
        System.out.println("Hashcode of Object 2 - "+objTwo.hashCode());

    }
}

Example to show how reflection can break the singleton pattern with Java reflect. You will get two hash code as below. It has a break on the singleton pattern.

Hashcode of Object 1 - 1836019240
Hashcode of Object 2 - 325040804

Prevent Singleton pattern from Reflection

There are many ways to prevent Singleton pattern from Reflection API, but one of the best solutions is to throw run time exception in the constructor if the instance already exists. In this, we can not able to create a second instance.

    private Singleton() {
        if( instance != null ) {
           throw new InstantiationError( "Creating of this object is not allowed." );
        }
    }

Deserialization

In serialization, we can save the object of a byte stream into a file or send over a network. Suppose if you serialize the Singleton class and then again de-serialize that object will create a new instance, hence deserialization will break the Singleton pattern.

Below code is to illustrate how the Singleton pattern breaks with deserialization.

Implements Serializable interface for Singleton Class.

DeserializationSingleton.Java

package demo1;

import java.io.*;

public class DeserializationSingleton {

    public static void main(String[] args) throws Exception {

        Singleton instanceOne = Singleton.getInstance();
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text"));
        out.writeObject(instanceOne);
        out.close();

        ObjectInput in = new ObjectInputStream(new FileInputStream("file.text"));
        Singleton instanceTwo = (Singleton) in.readObject();
        in.close();

        System.out.println("hashCode of instance 1 is - " + instanceOne.hashCode());
        System.out.println("hashCode of instance 2 is - " + instanceTwo.hashCode());
    }

}
The output is below and you can see two hashcodes.

hashCode of instance 1 is - 2125039532
hashCode of instance 2 is - 381259350

Prevent Singleton Pattern from Deserialization

To overcome this issue, we need to override readResolve() method in Singleton class and return same Singleton instance. Update Singleton.java, with below method.

   protected Object readResolve() { 
           return instance; 
     }  

Now run above DeserializationDemo class and see the output.

hashCode of instance 1 is - 2125039532
hashCode of instance 2 is - 2125039532

Cloning

Using the "clone" method we can create a copy of original object, samething if we applied clone in singleton pattern, it will create two instances one original and another one cloned object. In this case will break Singleton principle as shown in below code.

Implement the "Cloneable" interface and override the clone method in the above Singleton class.

Singleton.java


    @Override
    protected Object clone() throws CloneNotSupportedException  {
        return super.clone();
    }

Then Test with cloning for breaking the singleton
CloningSingleton.java


public class CloningSingleton {
    public static void main(String[] args) throws CloneNotSupportedException, Exception {
        Singleton instanceOne = Singleton.getInstance();
        Singleton instanceTwo = (Singleton) instanceOne.clone();
        System.out.println("hashCode of instance 1 - " + instanceOne.hashCode());
        System.out.println("hashCode of instance 2 - " + instanceTwo.hashCode());
    }

}

Here is the output

hashCode of instance 1 - 1836019240
hashCode of instance 2 - 325040804

If we see the above output, two instances have different hashcodes means these instances are not the same.


Prevent Singleton Pattern from Cloning

In the above code, breaks the Singleton principle i. e created two instances. To overcome the above issue we need to implement/override clone() method and throw an exception CloneNotSupportedException from clone method. If anyone try to create clone object of Singleton, it will throw an exception as see below code.

    @Override
    protected Object clone() throws CloneNotSupportedException  {
        throw new CloneNotSupportedException();
    }

Now we can run the CloningSingleton class, it will throw CloneNotSupportedException while creating a clone object of Singleton object.


13

View comments

  1. Well explained . Great article on singleton pattern . There is also good singleton pattern example visit Singleton class example

    ReplyDelete
  2. It is amazing to visit your site. Thanks for sharing this information, this is useful to me...

    Microservices Online Training
    Microservices Training in Hyderabad

    ReplyDelete
  3. Are you looking for where to buy hemp oil in Australia? Visit Ricks Hemp Oil store to choose from a premium organic range of hemp seed oil products today!


    cbd oil for sale australia
    what is hemp oil
    medicinal hemp oil

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Yes, Nowadays mobile application is an Important one, This blog is more informative. Thank you For sharing your knowledge About react Native App Development.

    ReplyDelete
  6. Nice information. It is very useful for me to learn and understand easily. Thanks for sharing
    react js online training

    ReplyDelete
  7. Thanks for providing this useful knowledge! In the field of mobile development, Slack clone React Native has a significant presence. And it gets better and better with each new release in terms of development speed and performance. Building a business application used to take a long time, but now that react-native is available, it's possible to construct a messaging platform app in minutes.

    ReplyDelete
  8. microservices

    Transform your legacy application with a microservices architecture that breaks your application into small components independent from each other.

    to get more - https://www.nitorinfotech.com/services/microservices/

    ReplyDelete
  9. Great blog, keep sharing such good work.
    Hire Backend Developer | Hire Developer | Hire Node JS Developer

    ReplyDelete
  10. A very informative blog! \Hire React Developers to create interactive user interfaces using JavaScript library.

    ReplyDelete
  11. Great post on ReactJS and the Virtual DOM! The explanation of how these technologies work together is very insightful. On a related note, if anyone is interested in Full-stack web development USA, I found a fantastic resource that offers comprehensive web development services. You can learn more about it here. Thanks for sharing this informative content!
    Visit https://l4rgdigitalplus.com/web-development-services-in-usa

    ReplyDelete

We used have  Singleton Design Pattern in our applications whenever it is needed. As we know that in singleton design pattern we can create only one instance and can access in the whole application. But in some cases, it will break the singleton behavior.

13

Microservices can have a positive impact on your enterprise. Therefore it is worth to know that, how to handle Microservice Architecture (MSA) and some Design Patterns for Microservices. General goals or principles for a microservice architecture.

12

Last few years has been a great year for API Gateways and API companies. APIs (Application Programming Interfaces) are allowing businesses to expand beyond their enterprise boundaries to drive revenue through new business models.

1

kubectl (Kubernetes command-line tool) is to deploy and manage applications on Kubernetes. Using kubectl, you can inspect cluster resources; create, delete, and update components.

NOTE

You must use a kubectl version that is within one minor version difference of your cluster.

2

WSO2 Enterprise Integrator is shipped with a separate message broker profile (WSO2 MB). In this Post I will be using message broker profile in EI (6.3.0).

1

When two or many applications want to exchange data, they do so by sending the data through a channel that connects the each others.

2

Microservices are going completely over the enterprise and changed the way people write software within an enterprise ecosystem.

Let build you microservices with msf4j for Auto Mobile.

The SMPP inbound endpoint allows you to consume messages from SMSC via WSO2 ESB OR EI.

1.  Start SMSC

2.  Create custom inbound end point with below parameter. (Make sure you pick correct system-id and password correct for your SMSC)

3. Create Sequence for Inbound EP.

4. Once ESB or EI start.

1

WSO2 APIM Components

WSO2 API Manager includes five main components as the Publisher, Store, Gateway, Traffic Manager and Key Manager.

API Gateway - responsible for securing, protecting, managing, and scaling API calls.

There is REST Back-End end-point in Vehicle registration services as below

GET /car?name=prius HTTP/1.1

Host: localhost:8080

color: White

Company need to expose it 3rd part companies and above End-point should not change as internal services are using it.

1

Estimation for Software project development is the process of predicting the most realistic amount of effort (expressed in terms of person-hours or money) required to develop or maintain software based on incomplete, uncertain and noisy input.

1

In this post give some basic on JAVA Stream API which is added in Java 8. It works very well in conjunction with lambda expressions. Pipeline of stream operations can manipulate data by performing operations like search, filter, count, sort, etc.

The Lifecycle Management(LCM) plays a major role in SOA Governance. WSO2 Governance Registry Lifecycle Management supports access control at multiple levels in lifecycle state.

1.

1

Enterprise Data Integration is a broad term used in the integration landscape to connect multiple Enterprise  applications and hardware systems within an organization. All these enterprise data integration lead to achieve to remove the complexity by simplifying data management as a whole.

Post is very basic one, Since Talend is all about data integration. Finding a BigDecimal [1] in such data set is very common.

BigDecimal VS Doubles

A BigDecimal is an exact way of representing numbers. A Double has a certain precision.

Vehicles registration services using REST services on government TAX department system. That REST services give the TAX information for the Vehicle.

{"Tax": {"Amount": 58963}}

Vehicles registration Depart planning to extend the service and expose as below.

1

Data integration is the combination of technical and business processes used to combine data from disparate sources into meaningful and valuable information. Today some systems may store data in a denormalized form and data integration tools able handle those.

There is few thing that make my work enjoyable with WSO2 ESB as it provides support for JavaScript Object Notation (JSON) payloads in messages. It is not very new feature and it old feature.

Working on an Alienvault IDS system or OSSIM you can come across over huge amount of alarms are created will system migrations.

If you’re familiar with SEIM tools or OSSEC, then you know syscheck. Syscheck is the integrity checking daemon within OSSEC. It’s purpose is simple, identify and report on changes within the system files.

Triggering action over the event occurrence in OSSIM is going to explain in this article.

There is agent in the system with IP, 192.168.80.22. Email is to be send to server admins whenever this agent disconnect and reconnect to SEIM server.

We need to have extra user data field on our security event. We need to know

event occurred time Host Server IP Editing particular event on ‘/etc/ossim/agent/plugins/ossec-single-line.cfg’. We can achieve it. We are interest on Web group and ID 0030. We added below line as our need.

Pre request

Test OSSEC new log from ‘ossec-logtest’

Here is the custom created rules.

In here I am using well known decoder in OSSEC if you need new OSSEC decoder you can write new decoder also [1]. Add new file to  rules directory in OSSEC.

Creating new OSSEC rule set

$ vi var/ossec/rules/custom_access_rules.xml

In here I am interest to monitor web user behavior model.

1

Introductions

In OSSEC, the rules are classified in multiple levels from the lowest (00) to the maximum level 16. But some levels are not used right now and below explain level details.

A brute-force attack consists of an attacker trying many passwords or passphrases with the hope of eventually guessing correctly. The attacker systematically checks all possible passwords and passphrases until the correct one is found.

Unfortunately Windows does not support Fdisk anymore. But there is another good command line tool to solve this problem. DiskPart in windows is useful format unallocated spaces in USB pen.

1. Enter ‘diskpart’ in cmd

Then disk part will start

2. List down storage in PC by

list disk

3.

The Linux kernel in Ubuntu provides a packet filtering system called netfilter, and the traditional interface for manipulating netfilter are the iptables suite of commands. The Uncomplicated Firewall (ufw) is a frontend for iptables and is particularly well-suited for host-based firewalls.

Count line when words has been matched

$ grep -c 'word' /path/to/file

Pass the -n option to precede each line of output with the number of the line in the text file

$ grep -n 'root' /etc/passwd

Ignore word case

$ grep -i 'word' /path/to/file

Use grep recursively under each directory

$ grep -r

Each application contains it's own log record format.

Access log moves to sensor / data source then I mapping to event id with considering the rules in ossim.

Data sources can be found in “ossim ->configuration –> threat_intelligence –> data_source” and search for source as below. Pick “AlienVault HIDS-accesslog” and it reads the access log.

It provides the SSH authentication to the host you want to access. For Cisco devices (PIX, routers, etc), you need to provide an additional parameter for the enable password. The same thing applies if you want to add support for “su”, it must be the additional parameter.

1. Log into AlienVault USM.

1. Download the image file of OSSIM

2. Make bootable pen with OSSIM ISO file

3. Boot drive

Make sure you have internet connection

4. Select OSSIM server to install

5. Just follow the the wizard

6. Add the net work details correctly with unique new IP for OSSIM server.

7.

Finding the logs in my server. I generally use lsof to list what is my server.

lsof | grep log

I check which log are reading by OSSEC

Check cat /var/ossec/etc/ossec.conf  |grep "<location>/"

Add new access log to OSSCE.

I am
I am
Archives
Total Pageviews
Total Pageviews
2 0 5 7 7 0 6
Categories
Categories
Loading