StubbyDB: create stubs and simulators quickly

Stubmatic 5 is live now

February 25, 2017 Leave a comment

Stubmatic is a npm tool which runs from CLI and it can be used to mock or proxy HTTP(s) calls. It helps to create simulators/stub/mocks of HTTP(s)/REST/SOAP easily. You can create mocked dynamic response without any programming. I recently published it’s 5th version yesterday with following additional features;

  • Robust: 97%+ code coverage. Many bugs are fixed. Code quality and structure is improved.
  • Now you can map multiple HTTP methods to a single method (not in short notations)
  • Short notations
  • Now you can proxy selected requests to other servers/simulators. This feature open many possibilities.
  • You can validate yaml, json from CLI for quick feedback. I’ll add the support to validate XML soon.
  • 2 more file stratigies are added.
  • You can debug HTTP requests from CLI
  • Support of yarn for fast installation
  • Now stubmatic can be started from nodejs code as well

You can visit the site for latest updates and tutorials.

Advertisements
Categories: Other

Life is so Simple, Dont make it Complex

February 16, 2017 Leave a comment

Every tear is a sign of brokenness Cutting Onions!,

Every silence is sign of lonliness Zero balance,

Every smile is sign of kindness Daily Brushing,

Every sms is sign of remembrance extra balance.

:

Life is so Simple

Don’t make it Complex with difficult Explanations ..

Dealing with FEAR

tv_fear_cartoon

when the source of our fear is the news, there is a really simple solution

Just turn it off

read more

Often the problem is serious, but the solution may be very simple

A patient walks into a psychiatrist’s office and says to the doctor:

“Whenever I’m laying down, I feel like there’s someone under my bed. When I look under the bed, I feel like someone’s on top of the bed. Under, over, under, over. I’m going crazy!”

“I have a 2 year treatment plan,” says the psychiatrist.

“Come three times a week and you’ll be cured from this problem,” he continues.

“How much will you charge for this treatment?” asks the patient.

“$70.00 per session,” replies the psychiatrist.

“Well, I’m going to think about it,” concludes the patient.

They bump into each other six months later.

“Why didn’t you come see me anymore?” asks the psychiatrist.

“At 70 bucks, three times a week, for 2 years, your sessions were going to be too expensive. So I met this guy at the bar and he cured me for $5.00,” says the patient.

“Oh really? How?”

The patient replies, “For $5.00, he cut the legs off my bed…”

Often the problem is serious, but the solution may be very simple!

Categories: Other

StubbyDB : Introduction video tutorial

September 9, 2016 Leave a comment

How fast and easy we can make simulators without programming knowledge but regular expression. Best for QAs for integration testing.

Fix for floating div

April 3, 2016 Leave a comment

First refer CSS snippet given below which is about to be used while discussing this problem & solution.

div {border:#000 1px solid; width: 50px;}
.L {float:left;}
.R {float:right;}

Let’s start.

Case 1

< div class="L">1< / div >
< div >Amit Gupta< / div >
< div class="R">2< / div >
< div >articlestack.wordpress.com< / div >

Result :

1
Amit Gupta
2
articlestack.wordpress.com

Explanation:

First Div will let its upcoming elements take place in its right ie div containing “Amit Gupta” word. This is the basic property of a floated div. But a simple DIV never let any upcoming element take place to its right or left. So the 3rd div is shifted to next line. Similar to First DIV, Third DIV will also let its upcoming element place it’s left.

Doubt : Why 4th DIV is not starting from starting of line?

SubCase 1

<div> Container
<div> child </div>
</div>

Output

Container

child

 

SubCase 2

<div> Container
<div class="L"> child </div>
</div>

Output

Container

child

 

Explanation:

Height of a simple DIV with default width 100% is increased by the height of its element. On the opposite side, Height of floated DIV may increased and can pop out from its container on y-axis. So it doesn’t let any other element draw on y-axis.

Revised case 1

<div class="L" style="width: 150px">1</div>
<div>Amit Gupta</div>
<div class="R">2</div>
<div>articlestack.wordpress.com</div>

Output:

1
Amit Gupta
2
articlestack.wordpress.com

Solution:

Use of clear property removes floating effect and let other element flow in normal way. For example;

<div class="L">1</div>
<div>Amit Gupta</div>
<div style="clear: left"></div>
<div class="R">2</div>
<div>articlestack.wordpress.com</div>

Output

1
Amit Gupta
2
articlestack.wordpress.com

Now if you increase the height of floated DIV it doesn’t affect upcoming elements.

<div class="L" style="width: 150px">1</div>
<div>Amit Gupta</div>
<div style="clear: left"></div>
<div class="R">2</div>
<div>articlestack.wordpress.com</div>

Output:

1
Amit Gupta
2
articlestack.wordpress.com

Warning:

For Browser’s compatibility

  1. Never use clear property with DIV using for displaying contents like
  2. Try to use clear:both instead of clear:left or clear:right.
Categories: Other, Tutorial Tags:

Serialization – a Sci Fi story

April 3, 2016 Leave a comment

Short story about serialization

After hard work of many years, Earth’s scientist developed a robot who can help them in daily work. But this robot was less featured than the robots which were developed by the scientist of Mars planet.

After a meeting between both planet’s scientist, it is decided that mars will send their robots to earth. But a problem occurred. The cost of sending 100 robots to earth was $100 millions. And it takes around 60 days for traveling.

Finally, Mar’s scientist decided to share their secret with Earth’s scientists. This secret was about the structure of class/robot. Earth’s scientists developed the same structure on earth itself. Mar’s scientists serialized the data of each robot and send it to earth. Earth’s scientists deserialized the data and fed it into each robot accordingly.

This process saved the time in communicating mass amount of data.

Some of the robots were being used in some defensive work on Mars. So their scientists marked some crucial properties of those robots as transient before sending their data to Earth. Note that transient property is set to null(in case of reference) or to default value(in case of primitive type) when the object gets deserialized.

One more point which was noticed by Earth’s scientists is that Mars’s scientists ask them to create some static variables to keep environmental detail. This detail is used by some robots. But Mars’s scientists dint share this detail since the environment on earth was different than Mars environment.

Even though knowing about the robot class structure and having serialized data Earth’s scientist were not able to deserialize the data which can make robots working.

Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:

Mars’s scientists were waiting for the complete payment. Once the payment was done Mars’s scientists shared the serialVersionUID with Earth’s scientists. Earth’s scientist set it to robot class and everything became fine.

One of the Mar’s Scientist: Earth’s scientists are very slow to deserialize some of our best Robots. They must be using old version of java. They should either switch to new java version or to implement Externalizable.

Terms highlighted in above example are:

  1. Serialization
  2. Deserialization
  3. Transient variables
  4. Static variables
  5. Externalizable

Technically

Serialization is nothing but storing current state of an object to physical file. So the data can be used later by deserializing it.

When it is required:

  1. When a system gets crashed.
  2. When a player want to save all played game data so he can continue playing later.
  3. When a process need to be stopped by some reason. But it must continue working the next time with the same data.

How to

a. Implements Serializable or Externalizable
b. Serialize:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("fileName"));
out.writeObject(obj);

c. Deserialize:

ObjectInputStream in = new ObjectInputStream(new FileInputStream("fileName"));
in.readObject();

 

1.       Object of class A can’t be deserialized to the object of class B.

2.       Object of class A can’t be deserialized to the object of class A itself if any of the instance variable changes its nature. For example

  1. Name
  2. Data type
  3. Removed from the class
  4. Make it transient or static

But if serialVersionUID is added to the class of serialized and deserialized object with same value then deserialization will not generate any error (excluding point b). So if variable is not found then its value is not set.

In short, deserialization finds instance variable with the same name they were used to serialize. If variable name is changed or they are removed from the class then it throws error. But if serialVersionUID is same then it skips initialization for not found variables.

In addition, if a variable is found with the same name but its datatype is changed then it generate error of casting even if serialVersionUID is same.

Changing their access level doesn’t impact.

3.       If serialVersionUID is not same for the class of serialized and deserialized object then deserialization throws error even if class structure are exact same.

4.       Methods, transient variables and static variables are not transient.

5.       An object can be serialized only if its class implements either Serializable or Externalizable.

6.       If extra variables found than the variables which are serialized then they are set to their default value at the time deserialization.

7.       Making a class part of inheritance tree is allowed. But moving a class in existing inheritance tree up/down is not allowed since it can affect saved/serialized object tree.


Why Externalizable

  1. It provides control of reading/writing object to/from an output/input stream.
  2. It was very useful till Java 1.2 since reflection was slow
  3. You can decide which object has to left from object tree or what default value has to be set to transient variables while deserialization.

Methods of Externalizable

public void writeExternal(ObjectOutput out) throws IOException {
out.writeFloat(x);
out.writeFloat(y);
out.writeFloat(z);
out.writeFloat(w);
}

public void readExternal(ObjectInput in) throws IOException {
x = in.readFloat();
y = in.readFloat();
z = in.readFloat();
w = in.readFloat();
}

Sample Code

I am attaching source code, I practiced on, for serialization and externalization.

Download

Categories: Java, Other Tags: , ,

Thread Tracer

January 24, 2016 Leave a comment

This program can be integrated with your any java program to trace various states of a thread. It can help you to understand the flow of a thread. But remember, Tracer runs a thread to trace states of a thread. Tracer will not able to print all states of a thread. since there might be a situation when Tracer thread get served to CPU very late or with big interval and another thread changes its 3-4 states in between. I generally run Tracer 2-3 times for proper understanding.

I took its help to find out deadlock in my one of the program over nested monitor.


import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.sql.Timestamp;
import java.util.ArrayList;

public class Tracer {
    private ArrayList <WrapperThread> threadList;

    Tracer() {
        threadList = new ArrayList < WrapperThread > ();
    }
 
    public void add(Thread t) {
        threadList.add(new WrapperThread(t));
    }
 
    static {
        new Thread(() -> {
                System.out.println("Monitoring Deadlocks");
                while (Thread.activeCount() >= 2) deadLockMonitor();
        }, "DeadLock Monitor").start();
    }
 
    private static void deadLockMonitor() {
        ThreadMXBean mx = ManagementFactory.getThreadMXBean();
        long[] DevilThreads = mx.findDeadlockedThreads();
        if (DevilThreads != null && DevilThreads.length > 0) {
            System.out.println(currentTime() + " :: Deadlock detected");
            for (int i = 0; i < DevilThreads.length; i++) {
                System.out.println("Thread id :" + DevilThreads[i]);
            }
            System.out.println("Exiting from system");
            System.exit(0);
        }
    }
 
    public void trace() {
        new Thread(() -> {
                while (Thread.activeCount() >= 2) {
                    if (isStateChanged()) System.out.println (currentTime() + " :: "+threadList);
                }
        }, "Tracer").start();
    }
 
    private boolean isStateChanged(){
    	for (WrapperThread wT : threadList) {
    		if(wT.isStateChanged()) return true;
	}
    	return false;
    }
 
    public static String currentTime() {
        return (new Timestamp(System.currentTimeMillis())).toString();
    }
}

Wrapper Thread

import java.lang.Thread.State;

public class WrapperThread{
	private String name;
	protected Thread originalThread;
	private State lastState;

	public WrapperThread(Thread t) {
		originalThread = t;
		name = t.getName();
		lastState = originalThread.getState();
		System.out.println(Tracer.currentTime() + " :: " + this);
	}

	public boolean isStateChanged() {
		State state = originalThread.getState();
		if(lastState != state){
			lastState = state;
			return true;
		}
		return false;
	}

	public State currentState() {
		return originalThread.getState();
	}
	
	@Override
	public String toString() {
		return name+":"+currentState();
	}
}

How to use it in your program

Tracer t = new Tracer();
t.add(A);
t.add(B);
t.trace();

Happy coding 🙂

Categories: Java, Multithreading

CyclicBarrier

January 23, 2016 Leave a comment

CyclicBarrier = Cycle + Barrier

CyclicBarrier just force threads to wait until their count reached to N. Then release them to run on a wide road. And force next N threads to wait. and so on.

 

public class CycleBarrierDemo implements Runnable {
    CyclicBarrier controller;

    CycleBarrierDemo() {
        controller = new CyclicBarrier(1);
    }
    @Override
    public void run() {
        try {
            Thread.sleep(100);
            System.out.println(controller.getNumberWaiting());
            System.out.println(Thread.currentThread().getName() + " has been arrived");
            controller.await();
            System.out.println(Thread.currentThread().getName() + " has been Passed");
        } catch (Exception bbx) {
            System.out.println(bbx.getMessage());
        }
    }
    public static void main(String[] argc) {
        CycleBarrierDemo cd = new CycleBarrierDemo();
        Thread A = new Thread(cd, "A");
        Thread B = new Thread(cd, "B");
        Thread C = new Thread(cd, "C");
        Thread D = new Thread(cd, "D");

        A.start();
        B.start();
        C.start();
        D.start();
    }
}

Output: [When barrier size was 1]

0
A has been arrived
A has been Passed
0
B has been arrived
B has been Passed
0
C has been arrived
C has been Passed
0
D has been arrived
D has been Passed

Output:[When barrier size was 2]

A has been arrived
1
B has been arrived
A has been Passed
B has been Passed
0
C has been arrived
1
D has been arrived
C has been Passed
D has been Passed

Categories: Java, Multithreading
%d bloggers like this: