Tuesday, October 8, 2013

sharding

sharding


Sharding is a type of database partitioning that separates very large databases the into smaller, faster, more easily managed parts called data shards. The word shard means a small part of a whole.

A database shard is a horizontal partition of data in a database or search engine. Each of multiple shards is held on a separate database server instance, to spread load. Some data within a database remains present in all shards, but some appears only in a single shard.

What is the difference between sharding and partitioning?

Sharding is a method of splitting and storing a single logical dataset in multiple databases.
Sharding is also referred as horizontal partitioning.

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 :-)


Wednesday, March 27, 2013

SSL certificates


This is the day, when I need use secure SSL certificate now...

I have checked information from some articles as the following example below and there is no magick now :-)
http://www.symantec.com/connect/articles/apache-2-ssltls-step-step-part-2

I need to create a valid web server certificate, in order to successful authentication the web server by the web browser.
So web server certificate should possess:
    public key of the web server
    dates of validity (both: start and expiration dates)
    supported cipher algorithms
    the serial number of the certificate
    X.509 attributes that will tell web browsers about the type and usage of the certificate
    name and signature of trusted Certification Authority (CA)
    URI of the CRL distribution point (if exists)
    URI of the X.509v3 Certificate Policy (if exists)
    Common Name (CN), which is the distinguish name (DN).
         DN must contain fully qualified domain name (FQDN) of the web server.
         Optionally it may also contain some other attributes, like:
               Organization's name (O),
               Organization Unit's name (OU),
               Country (C),
               State (S),
               Location (L)
               and more.

A fully qualified domain name (FQDN) is a domain name that specifies its exact location in the tree hierarchy of the Domain Name System (DNS):
http://en.wikipedia.org/wiki/Fully_qualified_domain_name

As wikipedia.org can explain... web browsers know how to trust HTTPS websites based on certificate authorities that come pre-installed in their software. Certificate authorities (e.g. VeriSign/Microsoft/etc.) are in this way being trusted by web browser creators to provide valid certificates. Logically, it follows that a user should trust an HTTPS connection to a website if and only if all of the following are true:
    The user trusts that the browser software correctly implements HTTPS with correctly pre-installed certificate authorities.
    The user trusts the certificate authority to vouch only for legitimate websites.
    The website provides a valid certificate, which means it was signed by a trusted authority.
    The certificate correctly identifies the website (e.g., when the browser visits "https://example.com", the received certificate is properly for "Example Inc." and not some other entity).
    Either the intervening hops on the Internet are trustworthy, or the user trusts that the protocol's encryption layer (TLS/SSL) is sufficiently secure against eavesdroppers.

Let's study the structure of British certificate of https://www.zalando.co.uk:
   
   



     
   
    
   

   

Let's study the structure of Polish certificate of *.nazwa.pl:





[[PODGLAD CERTYFIKATU:*.nazwa.pl]]

[OGOLNE]
1.
Niniejszy certyfikat zostal zweryfikowany do wykorzystania przez:
  Certyfikat SSL serwera
  Certyfikat osoby podpisujacej wiadomosc
  Certyfikat adresata wiadomosci
2.
Wystawiony dla
2.1.
Nazwa pospolita (CN):
  *.nazwa.pl
2.2.
Organizacja (O):
 
2.3.
Jednostka organizacyjna (OU):
 
2.4.
Numer seryjny:
  5D:B1:05:BA:A9:53:BD:59:DC:7A:3F:76:BD:56:22:46

3.
Wystawiony przez
3.1.
Nazwa pospolita (CN):
  Certum Level II CA
3.2.
Organizacja (O):
  Unizeto Technologies S.A.
3.3.
Jednostka organizacyjna (OU):
  Certum Certification Authority

4.
Waznosc
4.1.
Wystawiony dnia:
2013-02-21
4.2.
Wygasa dnia:
2014-02-21

5.
Odciski
5.1.
Odcisk SHA1:
65:40:7F:B7:55:54:9A:17:08:E7:CB:89:F5:AF:9D:45:E3:73:E9:69
5.2.
Odcisk MD5:
02:C5:38:39:50:FF:FA:8B:66:E7:00:B2:DF:F1:C1:0C




[SZCZEGOLY]
Hierarchia certyfikatu:
1.
Certum CA
1.1.
Certum Level II CA
1.1.1.
  *.nazwa.pl


Pola certyfikatu:
2.
  *.nazwa.pl
2.1.
Certyfikat
2.1.1.
Wersja:
  Wersja 3
2.1.2.
Numer seryjny:
  5D:B1:05:BA:A9:53:BD:59:DC:7A:3F:76:BD:56:22:46
2.1.3.
Algorytm sygnatury certyfikatu:
  PKCS #1 SHA-1 z szyfrowaniem RSA
2.1.4.
Wystawca:
  CN = Certum Level II CA
  OU = Certum Certification Authority
  O = Unizeto Technologies S.A.
  C = PL
2.1.5.
Waznosc
2.1.5.1.
Niewazny przed:
  2013-02-21 15:27:45
  (2013-02-21 14:27:45 GMT)
2.1.5.2.
Niewazny po:
  2014-02-21 15:27:45
  (2014-02-21 14:27:45 GMT)
2.1.6.
Podmiot:
  E = certs@netart.pl
  CN = *.nazwa.pl
  C = PL
2.1.7.
Informacje o kluczu publicznym
2.1.7.1.
Algorytm klucza publicznego:
  PKCS #1 Szyfrowanie RSA
2.1.7.2.
Klucz publiczny:
  Modulo (bitow: 2048):
  bf 40 fe a6 0a fe 6f cc 16 62 fa d7 0d e0 d3 40
  83 a7 e8 28 ae 5a 3f 75 ab 32 ed e4 8c 02 f2 10
  ab 1d a4 94 e4 44 b0 d3 fa ba 07 b9 99 9b ee b1
  b8 c0 21 da d2 f2 c7 7d 71 aa 2e cd 80 65 cc c1
  87 3d 07 df b9 33 46 47 c8 f4 ea 82 30 29 b2 a5
  66 ef 8c 34 7f dd aa 28 42 a3 70 66 a1 0f d7 eb
  e3 a7 f3 70 a2 77 3e dc 1f f4 64 2e ae f7 0c fa
  b9 a0 84 bd 4a 2d 20 04 3e 76 c9 36 0a 92 fd f6
  c6 b2 60 56 7b bd 06 85 89 6a 5c 60 62 cc 2b 72
  be ce fc f6 ea 84 bf 47 65 22 12 8c 38 01 bb 28
  3f 51 24 a1 1e 41 ba 45 bc 1e 30 28 36 3f 35 c3
  cc 89 3d 37 53 4c f0 52 7e 2a 17 4f 29 c3 c9 75
  46 0a 9c 72 fe ed 75 e7 4b 75 1d 77 f3 1c 83 77
  93 cd f6 dd 03 78 aa 45 a0 9b 6c 3c 66 d3 fe 81
  bf 1e aa 57 9a 55 bb e5 35 50 46 33 ad 9f 11 30
  92 67 21 ab a8 b8 3b d1 3f d7 76 e8 3d e5 b7 ab
  Wykladnik (bitow: 24):
  65537
2.1.8.
Rozszerzenia
2.1.8.1.
Podstawowe ograniczenia certyfikatu:
  Krytyczny
  Nie jest organem certyfikacji
2.1.8.2.
Punkty dystrybucji CRL:
  Niekrytyczny
  URI: http://crl.certum.pl/l2.crl
2.1.8.3.
Identyfikator klucza organu certyfikacji:
  Niekrytyczny
  Rozmiar: 20 bajtow / 160 bitow
  80 62 11 de c0 6b a7 10 e1 08 f0 55 b4 30 83 bf
  fa 8f 08 60
2.1.8.4.
Identyfikator klucza podmiotu certyfikatu:
  Niekrytyczny
  Rozmiar: 20 bajtow / 160 bitow
  5c a8 d5 00 24 2f 30 21 8f 7b 9e 18 f0 8f 86 dc
  43 62 36 ed
2.1.8.5.
Warunki uzycia klucza certyfikatu:
  Krytyczny
  Podpisywanie
  Szyfrowanie klucza
2.1.8.6.
Zasady certyfikatu:
  Niekrytyczny
  1.2.616.1.113527.2.2.2:
    Wskazanie regulaminu organu certyfikacji:
      https://www.certum.pl/CPS
    Powiadomienie uzytkownika: Unizeto Technologies S.A. - #15
      Usage of this certificate is strictly subjected to the CERTUM Certification Practice Statement (CPS) incorporated by reference herein and in the repository at https://www.certum.pl/repository.
2.1.8.7.
Rozszerzone uzycie klucza:
  Niekrytyczny
  Uwierzytelnianie serwera WWW TLS (1.3.6.1.5.5.7.3.1)
  Uwierzytelnianie klienta WWW TLS (1.3.6.1.5.5.7.3.2)
  Microsoft Server Gated Crypto (1.3.6.1.4.1.311.10.3.3)
  Netscape Server Gated Crypto (2.16.840.1.113730.4.1)
2.1.8.8.
Typ certyfikatu Netscape:
  Niekrytyczny
  Certyfikat SSL klienta
  Certyfikat SSL serwera
2.1.8.9.
Dostep do informacji o organach certyfikacji:
  Niekrytyczny
  OCSP: URI: http://ocsp.certum.pl
  Wydawcy CA: URI: http://www.certum.pl/l2.cer
2.1.8.10.
Alternatywna nazwa podmiotu certyfikatu:
  Niekrytyczny
  Nazwa DNS: *.nazwa.pl
  Nazwa DNS: nazwa.pl
2.1.9.
Algorytm sygnatury certyfikatu
  PKCS #1 SHA-1 z szyfrowaniem RSA
2.1.10.
Wartosc sygnatury certyfikatu
  Rozmiar: 256 bajtow / 2048 bitow
  c8 13 42 7f b0 7a b9 e1 c9 69 8e 79 30 d7 02 13
  f0 e4 3a 3f e2 d5 50 d0 fa 89 2a a6 69 67 19 ab
  e8 3d 85 c1 67 cf b4 ec ef 09 4a 90 b3 9b e6 87
  56 74 b8 6c ad f7 72 a6 d5 ff 0a fb 0d bb 39 bc
  c1 8b 3e 5f 8e 7e 4f 47 9e e2 cc 26 40 9e 3b 0c
  28 d7 4b 63 eb cf b1 41 fb 79 e2 c7 f2 22 6d ed
  e2 59 58 b5 b8 cf 65 10 3f 69 c4 66 77 e0 51 0d
  3e e1 e3 b1 dc 54 93 8b 05 f5 cb 1b 50 6c 25 09
  b7 b1 6e 19 97 4a 71 e6 c4 59 bb 5d 92 bb 97 8e
  0c 64 fc 41 8b 37 87 f2 3d a7 76 60 e4 36 55 20
  29 3f b6 8e 43 25 0b 8d 20 3f 8f ae b6 6a 6e b7
  8b 05 91 18 e5 ec 0a 56 54 f0 3b e5 54 c6 62 5c
  ac f2 b3 89 74 92 3b 2c fb 72 30 ba 79 3a 75 10
  55 dd 04 91 bc 60 54 a2 71 59 00 09 6f 07 7a 3b
  f2 56 99 3d 80 d9 f8 ec 37 13 fb 7b 9a b4 75 81
  e5 3f a7 2d 00 16 2d 07 c5 2b f6 b0 c7 35 69 73

Tuesday, January 22, 2013

Me


This is me.
The author is about 2,5 years old :-)

Friday, January 4, 2013

PrivateStaticVolatile

JeeProjectSnippets class is a simple Singleton implementation. This example demonstrates when is useful to use volatile keyword for the creation of an instance in Java. I use volatile variable in this example to ensure that every thread can see already updated value of instance:


package com.jeeprojectsnippets.serialization;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class JeeProjectSnippetsTest {

    public static void main(String[] args) throws IOException,
            ClassNotFoundException {

        JeeProjectSnippets singleton = null;

        for (int i = 1; i < 6; i++) {
            singleton = JeeProjectSnippets.getInstance();

            File file = new File("ser" + i + ".txt");

            ObjectOutputStream oos = new ObjectOutputStream(
                    new FileOutputStream(file));
            JeeProjectSnippets.a++;
            singleton.b++;
            JeeProjectSnippets.c++;
            singleton.d++;
            JeeProjectSnippets.f++;

            oos.writeObject(singleton);
            oos.close();

            ObjectInputStream ois = new ObjectInputStream(
                    new FileInputStream(file));
            JeeProjectSnippets jps = (JeeProjectSnippets) ois.readObject();

            System.out.println(i + ".\na_static: " + JeeProjectSnippets.a);
            System.out.println("b_transient: " + jps.b);
            System.out.println("c_static_volatile: " + JeeProjectSnippets.c);
            System.out.println("d_volatile: " + jps.d);
            System.out.println("e_final_static: " + JeeProjectSnippets.e);
            System.out.println("f_static_transient: "
                    + JeeProjectSnippets.f + "\n\n");
            ois.close();

        }
    }

    /**
     * JeeProjectSnippets class is a simple Singleton implementation. This
     * example demonstrates when is useful to use volatile keyword in Java. I
     * use volatile variable in this example to ensure that every thread can see
     * already updated value of instance.
     */
    public static class JeeProjectSnippets implements Serializable {

        private static final long serialVersionUID = 4408143805430443067L;

        private static int a = 10;
        private transient int b = 20;
        private static volatile int c = 30;
        private volatile int d = 40;
        public final static int e = 50;
        private static transient int f = 60;

        private static volatile JeeProjectSnippets instance;

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

Testing output of transient and static volatile variables:
1.
a_static: 11
b_transient: 0
c_static_volatile: 31
d_volatile: 41
e_final_static: 50
f_static_transient: 61


2.
a_static: 12
b_transient: 0
c_static_volatile: 32
d_volatile: 42
e_final_static: 50
f_static_transient: 62


3.
a_static: 13
b_transient: 0
c_static_volatile: 33
d_volatile: 43
e_final_static: 50
f_static_transient: 63


4.
a_static: 14
b_transient: 0
c_static_volatile: 34
d_volatile: 44
e_final_static: 50
f_static_transient: 64


5.
a_static: 15
b_transient: 0
c_static_volatile: 35
d_volatile: 45
e_final_static: 50
f_static_transient: 65