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

Sunday, December 30, 2012

The Rest is Silence... Not yet? Mapping CRUD methods to HTTP methods...

The Rest is Silence...
Not yet? Mapping CRUD methods to HTTP methods for RESTful Services

The most useful HTTP methods are four methods: POST, GET, PUT, and DELETE.
These correspond to create, read, update, and delete (generally speaking CRUD) operations.
We can also use OPTIONS and HEAD sometimes as HTTP methods...

Recommended return values (http://www.restapitutorial.com/httpstatuscodes.html)
of four most useful REST HTTP methods are as follows:

With an entire Collection (e.g. /products):
HTTP Method/Verb   
    GET     200 (OK), list of products. Use pagination, sorting and filtering to navigate big lists.   
    PUT     404 (Not Found), unless you want to update/replace every resource in the entire collection.   
    POST     201 (Created), 'Location' header with link to /products/{id} containing new ID.   
    DELETE     404 (Not Found), unless you want to delete the whole collection—not often desirable.   
      
With a specific Item (e.g. /products/{id}):
HTTP Method/Verb
    GET     200 (OK), single product. 404 (Not Found), if ID not found or invalid.
    PUT     200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid.
    POST     404 (Not Found).
    DELETE     200 (OK). 404 (Not Found), if ID not found or invalid.

Summarizing up:
Create  --> POST to a base URI returning a newly created URI
            PUT with a new URI
Read    -->  GET
Update  -->  PUT with an existing URI
Delete  -->  DELETE
  
GET (along with HEAD) requests are used only to read data and not change it.
Do not expose unsafe operations via GET. It should never modify any resources on the server.

PUT is not a safe operation, in that it modifies (or creates) state on the server, but it is idempotent.
In other words, if you create or update a resource using PUT and then make that same call again,
the resource is still there and still has the same state as it did with the first call.

It is recommended to keep PUT requests idempotent.
It is strongly recommended to use POST for non-idempotent requests.

The POST verb is most-often utilized for creation of new resources.
POST is neither safe nor idempotent.
It is therefore recommended for non-idempotent resource requests.
Making two identical POST requests will most-likely result in two resources containing the same information.

DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.

There is a caveat about DELETE idempotence, however.
Calling DELETE on a resource a second time will often return a 404 (NOT FOUND) since
it was already removed and therefore is no longer findable.

Friday, December 28, 2012

Using GROUP BY with HAVING and aggregation function

Using GROUP BY with HAVING and aggregation function

Suppose that we need use SQL sentence to sum up the prices of invoices grouping by Product,
and display the result under condition that sum is less than 777.

We can use general SQL HAVING Syntax:

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

Then I can use the following SQL statement:

SELECT Product, SUM(InvoicePrice)
FROM Invoices
GROUP BY Product
HAVING SUM(InvoicePrice) < 777;

Thursday, December 27, 2012

Republic of Garbage Collections

Republic of Garbage Collections
...and rules of life of GC Citizens:




package com.jeeprojectsnippets.gc.eligible;

public class Eligible {
      
       int j;

       public static void main(String[] args) {
             Eligible first = new Eligible(11);      // 11
             Eligible second = new Eligible(12);     // 12
             Eligible third = new Eligible(13);      // 13
             Eligible fourth = new Eligible(14);     // 14
             fourth = first.run(third); // fourth is set to null and marked for GC
             second = null; // second and fourth have been set to null and marked for GC

             tryTest("First: ", first);
             tryTest("Second: ", second);
             tryTest("Third: ", third);
             tryTest("Fourth: ", fourth);
            
             System.gc();
            
             tryTest("First: ", first);
             tryTest("Second: ", second);
             tryTest("Third: ", third);
             tryTest("Fourth: ", fourth);
       }

       public Eligible(int j) {
             this.j = j;
       }

       private Eligible run(Eligible eligible) {
             eligible = null;    // third is not set to null - this copy of 
                                 // eligible reference exists!
             return eligible;    // null is returned
       }

       public String toString() {
             return "" + j;
       }

       public static void tryTest(String msg, Eligible eligible) {
             try {
                    System.out.print(msg);
                    System.out.println(eligible);
             } catch (Exception e) {
                    System.out.print(msg);
                    System.out.println((String) null);
             }
       }
}
And the output of the test is:
First: 11
Second: null
Third: 13
Fourth: null
First: 11
Second: null
Third: 13
Fourth: null


An object becomes eligible for garbage collection in Java in following situations:
a. If an object has only live references via WeakHashMap
b. Parent object is set to null
c. All references of that object explicitly are set to null e.g. obj = null
d. Object is created inside a block/loop and reference is out of scope.

Java objects are created in Heap, and we can say about Heap Generations.
Heap is divided into 3 generations for sake of garbage collection in Java:
1. Young generation,
2. Tenured or Old Generation,
3. and Perm Area of Heap.

New objects are created into young generation and subsequently moved to old generation.

Young/New Generation is further divided into 3 parts known as:
1.1.  Eden space,
1.2.  Survivor 1 space
1.3.  and Survivor 2 space.

Perm Area of Heap (Permanent generation) is somewhat special and it is used to store Meta data related to classes and method in JVM. It also hosts String pool provided by JVM. That can explain why String is immutable in Java.

We can use methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM, but it is not guaranteed that garbage collection will happen at all.

The garbage collection thread invokes finalize() method before removing an object from memory of the object and gives us an opportunity to perform any sort of cleanup required.

Garbage collection tuning generally depends on fact what kind of object application has and what are there average lifetime etc.

Read more: