a tiny JSON path parser

A tiny JSON path parser. This project fetches only given JSON object and JSON value for given key. There are two types of delimiter, first delimiter is object delimiter which is “:” character. The other delimiter is “,” character. Left side of “:” indicates JSON objects, right side of “:” indicates keys. Comma separated objects represent nested objects, for example “vehicle,car,sport car:price” means the “sport car” JSONObject is covered by “car” object and “car” object is covered by “vehicle” object.
Example JSON object:

{
    "vehicle":{  
        "color":"white", 
        "bicycle":{ 
            "color": "red", 
            "price": 19.95 } ,
        "car": { 
            "color": "blue", 
            "price":49.95, 
            "sport car":{ 
                "color":"black", 
                "price": 119.95 
            }
        }
    }
}

“vehicle:”

{
  "color":"white",
  "bicycle":{
    "price":19.95,
    "color":"red"
  },
  "car":{
    "price":49.95,
    "color":"blue",
    "sport car":{
      "price":119.95,
      "color":"black"
    }
  }
}

“vehicle:color”

white

“vehicle,bicycle:”

{
  "price":19.95,
  "color":"red"
}

“vehicle,bicycle:price”

19.95

“vehicle,car:”

{
  "price":49.95,
  "color":"blue",
  "sport car":{
    "price":119.95,
    "color":"black"
  }
}

“vehicle,car,sport car:price”

119.95

Project github address.

RabbitMQ worker like a bridge between two queues

RabbitMQ is a well known messaging broker. It gives a common platform for sending and receiving messages. RabbitMQ has some good tutorials in five programming languages. This post wants to show a little example about a message receiver likes a bridge between two message queues. Actually it’s very simple, the receiver send messages from the first messaging queue, after the processing of messages it sends them the second messaging queue.

The skeleton of our example is:
Producer#1 -> Queue#1 -> Worker (in another perspective Producer#2) -> Queue#2 -> Receiver

Producer#1 -> Queue#1
The first part is establishment of the first messaging queue and producer code sends messages to our message receiver (let be “worker”). This part is almost same as official tutorial.


public class Producer {
private static final String TASK_QUEUE_NAME = "first_task_queue";

public static void main(String[] argv)
throws java.io.IOException {

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

String message = "Hello from Queue#1";

channel.basicPublish( "", TASK_QUEUE_NAME,
MessageProperties.PERSISTENT_TEXT_PLAIN,
message.getBytes());
System.out.println(" Sent '" + message + "'" + "to Queue#1");

channel.close();
connection.close();
}
}

Queue#1 -> Worker (in another perspective Producer#2) -> Queue#2
The second part is heart of our example, this part receives messages from the first queue and send it to the second queue. The worker code has two different queue definitions.


public class Worker {
private static final String FIRST_TASK_QUEUE_NAME = "first_task_queue";
private static final String SECOND_TASK_QUEUE_NAME = "second_task_queue";

public static void main(String[] argv)
throws java.io.IOException,
java.lang.InterruptedException {

The first queue definition.


ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

channel.queueDeclare(FIRST_TASK_QUEUE_NAME, true, false, false, null);
System.out.println(" Waiting for messages from Queue#1.");

channel.basicQos(1);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(FIRST_TASK_QUEUE_NAME, false, consumer);

The second queue definition.


ConnectionFactory factory2 = new ConnectionFactory();
factory2.setHost("localhost");
Connection connection2 = factory2.newConnection();
Channel channel2 = connection2.createChannel();
channel2.queueDeclare(SECOND_TASK_QUEUE_NAME, true, false, false, null);

Receiving from Queue#1 and sending to Queue#2


while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" Received '" + message + "'" + "from Queue#1");
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

channel2.basicPublish( "", SECOND_TASK_QUEUE_NAME,
MessageProperties.PERSISTENT_TEXT_PLAIN,
message.getBytes());
System.out.println(" Sent '" + message + "'" + "to Queue#2");
}
}
}

And the final part is an ordinary receiver. Official tutorials are very helpful and simple, so in my opinion RabbitMQ is a simple tool for sending and receiving messages. I use it on different a producer machine, five worker machines and a saver machine.

java observer pattern

A good example to picture observer pattern is a newspaper subscription service with its publisher and subscribers. The observer pattern defines a one-to-many relationship between a set of objects. When the state of one object changes, all of its dependents are notified. A visualized example of observer pattern is below.

I prepared a little example code of java observer pattern(*). The example acts like a tracker agent that it follows price and stock changes of a product. When price/stock information changes, all observers are updated new price/stock information.

The code includes three interfaces. “Subject” interface which is subscription service. The others are “Observer” and “DisplayProduct”.


public interface Subject {
public void registerObserver(Observer observer);
public void removeObserver(Observer observer);
/**
* Notify all observers when the Subject's state has changed.
*/
public void notifyObservers();
}

/**
* The Observer interface is implemented by all observers,
* all observers have to implement the update() method.
*/
public interface Observer {
public void update(float price, boolean stock);
}

/**
* It will be called when display product needs to be displayed.
*/
public interface DisplayProduct() {
public void display();
}

The code includes three classes. “Tracker” implements Subject interface that Tracker object is our subject object as above picture.


public class Tracker implements Subject {
private ArrayList observers;
private int price;
private boolean stock;

public Tracker() {
observers = new ArrayList();
}

public void registerObserver(Observer observer) {
observers.add(observer);
}

public void removeObserver(Observer observer) {
int index = observers.indexOf(o);
if (index >= 0) {
observers.remove(index);
}
}

public void notifyObservers() {
for (int i=0; i < observers.size(); i++) {
Observer observer = (Observer)observers.get(i);
observer.update(price,stock);
}
}

public void stockPriceChanged() {
notifyObservers();
}

public void setStockPrice(float mPrice, boolean mStock) {
this.price = mPrice;
this.stock = mStock;
stockPriceChanged();
}
}

One of the other classes is “FollowedProductDisplay” which is implements both of Observer and DisplayProduct interfaces. FollowedProductDisplay objects are our observers.


public class FollowedProductDisplay implements Observer, DisplayProduct {
private float price;
private boolean stock;
private Subject tracker;

public FollowedProductDisplay(Subject mTracker) {
this.tracker = mTracker;
tracker.registerObserver(this);
}

public void update(float mPrice, boolean mStock) {
this.price = mPrice;
this.stock = mStock;
display();
}

public void display() {
System.out.println("Followed product: price -> "
+ price + " stock -> " + stock);
}
}

The last class is “TrackerAgent” that it contains our subject and observer objects.


public class TrackerAgent {
public static void main(String[] args) {
Tracker tracker = new Tracker();
FollowedProductDisplay followedProduct =
new FollowedProductDisplay(tracker);
tracker.setStockPrice(124.50,true);
tracker.setStockPrice(114.50,true);
}
}

The result of the example is below:


Followed product: price -> 124.50 stock -> true
Followed product: price -> 114.50 stock -> true

(*) I get remarkable help from the book. Head First Design Patterns, Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra, O’Reilly Media, 2004.