com.bryanreinero.purchase.PurchaseDAO.java Source code

Java tutorial

Introduction

Here is the source code for com.bryanreinero.purchase.PurchaseDAO.java

Source

/**
Copyright (c) 2013 Bryan Reinero
    
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/

package com.bryanreinero.purchase;

import com.bryanreinero.twophase.Transaction;
import com.bryanreinero.twophase.State;
import com.bryanreinero.twophase.TransactionDAO;
import com.bryanreinero.twophase.TransactionException;

import com.mongodb.*;

public class PurchaseDAO implements TransactionDAO<Purchase> {

    private final DBCollection principals;
    private final DBCollection transactions;

    public PurchaseDAO(MongoClient mongo) {
        principals = mongo.getDB("twophase").getCollection("principals");
        transactions = mongo.getDB("twophase").getCollection("transactions");
    }

    @Override
    public void insertTransaction(Purchase purchase) throws TransactionException {
        transactions.insert(toDBObject(purchase));
    }

    @Override
    public Transaction getTransaction(State state) throws TransactionException {
        DBObject query = new BasicDBObject("state", state);
        return toPurchase((DBObject) transactions.findOne(query));
    }

    @Override
    public Transaction getTransactionsInProgress() throws TransactionException {

        DBObject query = new BasicDBObject("$nor",
                new BasicDBObject[] { new BasicDBObject("state", State.complete.toString()),
                        new BasicDBObject("state", State.cancelled.toString()) });

        try {
            DBObject object = (DBObject) transactions.findOne(query);
            if (object == null)
                return null;

            return toPurchase(object);
        } catch (MongoException e) {
            throw new TransactionException("Transaction read exception", e);
        }
    }

    @Override
    public void setTransaction(Integer id, State state) throws TransactionException {
        DBObject query = new BasicDBObject("_id", id);
        DBObject update = new BasicDBObject("$set", new BasicDBObject("state", state.toString()));

        try {
            WriteResult result = transactions.update(query, update);

            if (!result.getLastError().ok())
                throw new TransactionException("Transaction update failure: " + result.getError());

            if (result.getN() == 0)
                throw new TransactionException(
                        "Transaction update failure: updated " + result.getN() + " transaction");

        } catch (MongoException e) {
            throw new TransactionException("Pricipal update failure", e);
        }

    }

    private static DBObject toDBObject(Purchase purchase) {
        DBObject object = new BasicDBObject();
        object.put("_id", purchase.getId());
        object.put("state", purchase.getState().toString());
        object.put("buyer", purchase.getBuyer());
        object.put("seller", purchase.getSeller());
        object.put("value", purchase.getValue());
        return object;
    }

    private static Purchase toPurchase(DBObject object) {
        return new Purchase((Integer) object.get("_id"), (String) object.get("buyer"),
                (String) object.get("seller"), (Integer) object.get("value"),
                State.parseState((String) object.get("state")));
    }

    @Override
    public void updatePrincipal(String principal, Integer transactionId, int value) throws TransactionException {
        DBObject q = new BasicDBObject("_id", principal);
        q.put("pendingTransactions", new BasicDBObject("$ne", transactionId));
        DBObject o = new BasicDBObject("$inc", new BasicDBObject("balance", value));
        o.put("$push", new BasicDBObject("pendingTransactions", transactionId));
        try {
            WriteResult result = principals.update(q, o);

            if (!result.getLastError().ok())
                throw new TransactionException("Pricipal update failure: " + result.getError());
        } catch (MongoException e) {
            throw new TransactionException("Pricipal update failure", e);
        }
    }

    @Override
    public void removePendingTransaction(String principal, Integer transactionId) throws TransactionException {
        DBObject q = new BasicDBObject("_id", principal);
        DBObject o = new BasicDBObject("$pull", new BasicDBObject("pendingTransactions", transactionId));
        try {
            WriteResult result = principals.update(q, o);

            if (!result.getLastError().ok())
                throw new TransactionException("Pricipal update failure: " + result.getError());

        } catch (MongoException e) {
            throw new TransactionException("Pricipal update failure", e);
        }
    }

    @Override
    public void cancellTransaction(String principal, Integer transactionId, int value) throws TransactionException {

        DBObject q = new BasicDBObject("_id", principal);
        q.put("pendingTransactions", transactionId);
        DBObject o = new BasicDBObject("$pull", new BasicDBObject("pendingTransactions", transactionId));
        o.put("$inc", new BasicDBObject("balance", value));

        try {
            WriteResult result = principals.update(q, o);
            if (!result.getLastError().ok())
                throw new TransactionException("Pricipal update failure: " + result.getError());

        } catch (MongoException e) {
            throw new TransactionException("Pricipal update failure", e);
        }
    }
}