Saturday, April 13, 2013

Thursday, April 11, 2013

org.mockito

Sometimes we need Stub or Mock objects as following:

import org.mockito.Mock;
import org.mockito.Mockito;

    @Mock
    private EntityManager em;
(...)

        @SuppressWarnings("rawtypes")
        public Object find(Class class1, Object obj) {
            Object object = Mockito.mock(Object.class);
            return object;
        }

Let me look at definitions from DZone Refcardz (by M.Zajaczkowski) about Mockito:

1. Dummy = an empty object passed in an invocation (usually only
to satisfy a compiler when a method ar- gument is required)

2. Fake = an object having a functional implementation, but usually
in a simplified form, just to satisfy the test (e.g., an in-memory
database)

3. Stub = an object with hardcoded behavior suitable for a given
test (or a group of tests)

4. Mock = an object with the ability to a) have a programmed
expected behavior, and b) verify the interactions occurring in its
lifetime (this object is usually created with the help of mocking
framework)

5. Spy = a mock created as a proxy to an existing real object; some
methods can be stubbed, while the un- stubbed ones are forwarded
to the covered object

We can create a mock iterator or mock list, for example in such way:

import static org.mockito.Mockito.*;
import java.util.Iterator;
import org.junit.Test;
(...)
    @Test
    public void mockito_example_test01(){
        Iterator iter = mock(Iterator.class);
         List mockedList = mock(List.class);
         mockedList.add("one");


Another example is related with return value. Stubs can also return different values depending on arguments passed into the method, for example...

    @Test
    public void with_return_value(){
        Comparable c = mock(Comparable.class);
        when(c.compareTo("Test")).thenReturn(1);
        assertEquals(1,c.compareTo("Test"));
    }

Sunday, April 7, 2013

The paradox of RELATIONSHIP: NoSQL vs. RDBMS

The paradox of RELATIONSHIP: NoSQL vs. RDBMS

The real paradox of RELATIONSHIP existence in current databases is that, in my opinion, a NoSQL graph database is MORE RELATIONAL than RDBMS can be. And this is an advantage of NoSQL, because its RELATIONSHIPS are richer and complete.
Why?
An example: a “friend” RELATIONSHIP in NoSQL graph database can include a “friends since” datetime stamp (a whole lifecycle of relationship), together with information in properties describing the degree and quality of this friendship (measure!!!), and so on. So we can automatically understand these rich relationships in runtime  :-)
As I have read this in my favorite book "Graph Databases" (authors: Ian Robinson, Jim Webber and Emil Eifrem) richer RELATIONSHIP is only one of many advantages of using NoSQL graph databases.
The very beginning of graph theory started in the 18th century by Leonhard Euler, who is a daddy and first pioneer of it. The graph theory is the study of graphs, which are mathematical structures used to model pairwise relations between objects. A graph may be undirected or directed, and it is just a collection of vertexes and lines called edges that connect them or in simpler way: a set of nodes and the RELATIONSHIPS that connect them.

The whole world for RELATIONSHIPS in a single graph…

Unlike RDBMSs, which require a level of specialized training to understand, graph databases store information in ways that much more closely resemble the ways humans think about data. In this context, we can easier understand the architecture of different networks (electronic and social), circuits, management and rules. And that is why graph databases have been proven to solve some of the more relevant current data management challenges, including important problems in the areas of social networking, master data management, geospatial, recommendations engines, and more. This increased focus on graph is driven by successes of companies such as Facebook, Google, and Twitter. So where we can use it? From the supply-chain to medical history for populations, and from the construction of a space shuttle, to a system of roads, and so on.
Major matter of the unique things about graph databases that makes them especially adapted to
modeling the real world is that they elevate RELATIONSHIP to be first-class principal citizens of the
data model.

Is there a great hope for economic world in graphs?

We live in a spacetime of the continuous threat of the “supersonic” domino effect, when the biggest worldwide bank can fall tomorrow without a special causes. Graph databases address one of the great macroscopic current business trends: leveraging complex and dynamic relationships to generate insight and competitive advantage.
For us it is hard to understand dynamic and “supersonic” relationships between worldwide supply and demand chain, customer’s needs, networks of power and energy, access elements in a
telephone or datacenter network, producers and consumers of entertainment, or genes
and proteins, gaming and military. Such RELATIONSHIPS are like protein neural networks in our brains which can starts with a one idea and occur real for ages. Maybe graph databases is the best tool to use theories of John Nash, an American mathematician whose works are used in market economics, computing, evolutionary biology, artificial intelligence, accounting, politics and military theory. The ability to understand and analyze such data in graphs is a key factor over the coming decade.

BASE vs. ACID

As I have read this in "Graph Databases", instead of using ACID (Atomic, Consistent, Isolated,Durable), the term BASE has arisen as a popular way of describing the properties of a more optimistic storage strategy:
1. (BA) Basic Availability:
The store appears to work most of the time.
2. (S) Soft-state:
Stores do not have to be write-consistent, nor do different replicas have to
be mutually consistent all the time.
3. (E) Eventual consistency:
Stores exhibit consistency at some later point (e.g. lazily at
read time).

Now I use Neo4j for the beginning from Neo Technology. MongoDB will be the next station soon  :-)

Saturday, April 6, 2013

Barcode scanner

Barcode scanner


Everybody knows QR code format, and we can generate it at http://www.the-qrcode-generator.com:

1.
 http://kdabrowski.blogspot.com


2.
http://jeeprojectsnippets.com

3.
http://jeeproject.com

4.
Bus ticket:



We focus on barcodes now...

An example of EAN-13 format of barcode:



Another example of CODE39 format of barcode:



CODE128/EAN-128 format of barcode:


EAN-8 format of barcode:


Interleaved 2 of 5:


How can we use it?
Assume that we have barcode scanner, printer and display and we want to build single point of sale.

Let's begin...

-----------------------------------------
package com.jeeprojectsnippets.pos.entity;

import java.io.Serializable;

import com.jeeprojectsnippets.pos.entity.base.EntTable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 * Entity class for table: "pos_Product"
 */

@Entity
@Table(name = "pos_Product")
@NamedQueries({
    @NamedQuery(name = "EntProduct.findById", query = "SELECT p FROM EntProduct p WHERE id = :id "),
    @NamedQuery(name = "EntProduct.findByBarcode", query = "SELECT p FROM EntProduct p WHERE barcode = :barcode ")
})
public class EntProduct extends EntTable implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name = "barcode")
    private Long barcode;
   
    @Column(name = "price")
    private double price;

    /**
     * @return the barcode
     */
    public Long getBarcode() {
        return barcode;
    }

    /**
     * @param barcode the barcode to set
     */
    public void setBarcode(Long barcode) {
        this.barcode = barcode;
    }

    /**
     * @return the price
     */
    public double getPrice() {
        return price;
    }

    /**
     * @param price the price to set
     */
    public void setPrice(double price) {
        this.price = price;
    }
}

-------------------------------------------
package com.jeeprojectsnippets.pos.entity.base;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 * Auxliary class for Entity classes
 */
public class EntTable implements Serializable {

    private static final long serialVersionUID = -2L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "name")
    private String name;

    /**
     * @return the id
     */
    public Integer getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
}
-------------------------------------------
USE `myDB`;

CREATE TABLE pos_Product
(
    `id` INTEGER NOT NULL,
    `name` VARCHAR(45) NULL DEFAULT NULL,
    `barcode` LONG NULL,
    `price` DOUBLE NULL,
    PRIMARY KEY (`id`)
) ;

COMMIT;

INSERT INTO `sio2`.`pos_product` (`id`, `name`, `barcode`, `price`) VALUES (33, 'cheese', '1234567890123', 13.3);
INSERT INTO `sio2`.`pos_product` (`id`, `name`, `barcode`, `price`) VALUES (34, 'butter', '1234567890124', 14.44);
INSERT INTO `sio2`.`pos_product` (`id`, `name`, `barcode`, `price`) VALUES (35, 'milk', '1234567890125', 15.0);
INSERT INTO `sio2`.`pos_product` (`id`, `name`, `barcode`, `price`) VALUES (36, 'bread', '1234567890126', 16);

COMMIT;

-------------------------------------------
package com.jeeprojectsnippets.pos.entity.manager;

import javax.ejb.Local;

import com.jeeprojectsnippets.pos.entity.EntProduct;

@Local   
/**
 * ProductManager interface to DAO operations of EntProduct object
 */                                                                               
public interface ProductManager     {
    public EntProduct saveAndRefresh(EntProduct entProduct);
    public EntProduct findById(int id);
    public EntProduct findByBarcode(Long barcode);
    public T find(Class entityClass, int id);
}
-------------------------------------------
package com.jeeprojectsnippets.pos.entity.manager.impl;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jeeprojectsnippets.pos.entity.EntProduct;
import com.jeeprojectsnippets.pos.entity.manager.ProductManager;
import com.jeeprojectsnippets.pos.io.PosConstants;

@Stateless(name = "ProductManagerImpl")
/**
 * Class, which implements ProductManager interface
 */                                                                           
public class ProductManagerImpl    implements ProductManager, PosConstants {

    @PersistenceContext(unitName = "Scanning")
    private EntityManager em;

    @Override
    public EntProduct saveAndRefresh(EntProduct entProduct) {
        em.persist(entProduct);
        em.refresh(entProduct);
        return entProduct;
    }
   
    @Override
    public EntProduct findById(int id) {
        EntProduct entProduct = em.find(EntProduct.class, id);
        return entProduct;
    }

    @Override
    public T find(Class entityClass, int id) {
 
        return em.find(entityClass, id);
    }

    @Override
    public EntProduct findByBarcode(Long barcode)
            throws javax.persistence.NoResultException,
            javax.persistence.NonUniqueResultException{

        Query que = em.createNamedQuery("EntProduct.findByBarcode");
        que.setParameter("barcode", barcode);
       
        EntProduct resu = (EntProduct) que.getSingleResult();
        return resu;
    }
}
-------------------------------------------
package com.jeeprojectsnippets.pos;

import java.util.ArrayList;
import java.util.List;

import com.jeeprojectsnippets.pos.io.PosConstants;
import com.jeeprojectsnippets.pos.entity.EntProduct;
import com.jeeprojectsnippets.pos.entity.manager.ProductManager;

import javax.ejb.EJB;
   
public class POSApp implements PosConstants {
   
    private static Scanner scanner = null;
    private static Display display = null;
    private static Printer printer = null;
    private static UserButtonListener userButtonListener = null;
   
    private static EntProduct entProduct = null;
    private static List entProductList = null;
   
    @EJB
    private static ProductManager productManager = null;
   

   
    public static void init(){
        setScanner(new Scanner());
        setDisplay(new Display());
        setPrinter(new Printer());
        setUserButtonListener(new UserButtonListener());
    }
   
    private static void run() throws Exception{
        try{
            Long barcode = Long.parseLong(getScanner().scan());
            setEntProduct(getProductManager().findByBarcode(barcode));
            getEntProductList().add(getEntProduct());
            getDisplay().display(getEntProduct().getName() + " " + getEntProduct().getPrice() + "\n");
        } catch (java.lang.NumberFormatException e){
            getDisplay().display(ERROR_MSG_INVALID_BARCODE_NAME);
        } catch (javax.persistence.NoResultException e) {
            getDisplay().display(ERROR_MSG_PRODUCT_NOT_FOUND_NAME);
        } catch (javax.persistence.NonUniqueResultException e) {
            getDisplay().display(ERROR_MSG_MORE_THAN_ONE_PRODUCT_FOUND_NAME);
        }catch(Exception ex){
            // TODO logger.debug(ex.getMessage());
            System.out.println(ex.getMessage());
            throw new Exception(ex.getMessage());
        }finally{
            // TODO clean if needed
        }
       
    }
   
    protected static String act() throws Exception{
        double sum = 0;
            while(!EVENT_EXIT.equals(getUserButtonListener().watch())){
                setEntProductList(new ArrayList(1));
                run();
                for (EntProduct entProduc : getEntProductList()){
                    getPrinter().print(entProduc.getName() + " " + entProduc.getPrice() + "\n");
                    sum += entProduc.getPrice();
                }
            }
            getPrinter().print("TOTAL: " + sum + "\n");
            getDisplay().display("TOTAL: " + sum + "\n");
            return Double.toString(sum);
    }
   

    public static void main(String[] args) throws Exception {
        init();
        while(true){
            act();
        }
    }

    /**
     * @return the scanner
     */
    public static Scanner getScanner() {
        return scanner;
    }
   
    (...)

}
-------------------------------------------

package com.jeeprojectsnippets.pos;

import com.jeeprojectsnippets.pos.io.BarCodeReader;
import com.jeeprojectsnippets.pos.io.impl.BarCodeReaderImpl;

class Scanner implements BarCodeReader {
    private BarCodeReader adaptee = new BarCodeReaderImpl();

    public String read() {
        return adaptee.read();
    }

    public String scan() {
        return read();
    }
}


-------------------------------------------

package com.jeeprojectsnippets.pos;

import com.jeeprojectsnippets.pos.io.DisplayWriter;
import com.jeeprojectsnippets.pos.io.impl.DisplayWriterImpl;

class Display implements DisplayWriter
{
    private DisplayWriter adaptee = new DisplayWriterImpl();
    public boolean write(String msg) {
        return adaptee.write(msg);
    }

    public boolean display(String msg) {
        return write(msg);
    }
}


-------------------------------------------

package com.jeeprojectsnippets.pos;

import com.jeeprojectsnippets.pos.io.PrinterWriter;
import com.jeeprojectsnippets.pos.io.impl.PrinterWriterImpl;

class Printer implements PrinterWriter {
    private PrinterWriter adaptee = new PrinterWriterImpl();

    public boolean write(String msg) {
        return adaptee.write(msg);
    }

    public boolean print(String msg) {
        return write(msg);
    }
}

-------------------------------------------

package com.jeeprojectsnippets.pos;

import com.jeeprojectsnippets.pos.io.UserReactionReader;
import com.jeeprojectsnippets.pos.io.impl.UserReactionReaderImpl;

class UserButtonListener implements UserReactionReader {
    private UserReactionReader adaptee = new UserReactionReaderImpl();

    public String listen() {
        return adaptee.listen();
    }
   
    public String watch() {
        return listen();
    }
}

-------------------------------------------
So we have a little shop now :-)