Sunday, April 27, 2014

Resolve Element 'mvc:annotation-driven' must have no character

To resolve the error

cvc-complex-type.2.1: Element 'mvc:annotation-driven' must have no character or element information item [children], because the type's content type is empty.

chagne the mvc schemaLocation to newer version, for example, 3.2 works for me.
<beans xmlns="http://www.springframework.org/schema/beans"
        ...
 xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        ...
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

Tuesday, April 8, 2014

Compute SHA checksum for a string on MAC terminal

$echo -n <the_string> | shasum -a 256

Explanation:
The option -n tells echo not to output the trailing newline.
The option -a 256 of shasum specifies to use 256 algorithm.

Tuesday, March 25, 2014

MongoDB error E11000 duplicate key error index on Spring

When trying to insert the document with the same id on MongoDB, MongoDB will return an error of E11000 duplicate key error index.
> db.users.insert({"_id":"jsmith", "firstname": "John", "lastname": "Smith"})
> db.users.insert({"_id":"jsmith", "firstname": "John", "lastname": "Smith"})
E11000 duplicate key error index: database.users.$_id_  dup key: { : "jsmith" }

But you might have chance to be surprised that the MongoOperations(more precisely, org.springframework.data.mongodb.core.MongoOperations) does not complain even you insert the same object twice in Spring.

As of today, the latest release of spring-data-mongodb
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.4.0.RELEASE</version>
</dependency>

The POJO class, User.java
public class User {
 
    @Id
    private String id;
    private String firstname;
    private String lastname;

    public User(String id, String username, String password) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
    }

    getters and setters
    ...
}

The main function
User user = new User("jsmith", "John", "Smith");
mongoOps.insert(user);
User user = new User("jsmith", "John", "Smith");
mongoOps.insert(user);

The code will run with no exception, but only one entry will be inserted. In order to see the "E11000 duplicate key error index" error in Spring, configure mongo with write-concern, e.g. <mongo:mongo host="localhost" port="27017" write-concern="SAFE" />

Then you will see org.springframework.dao.DuplicateKeyException is thrown.

Reference
Where's My Exceptions, Spring Data MongoDB?
MongoDB: No exception when saving duplicate value to an attribute annotated with @Indexed(unique=true)

Wednesday, September 25, 2013

Spring MVC and Cookie

In a common scenario, a cookie may be set on the client side using JavaScript

function setCookie() {
    var c_name = "javascriptCookie";
    var c_value = "this cookie was set by JavaScript";
    document.cookie=c_name + "=" + c_value;
}

Spring MVC can also write cookie while returning a page

@RequestMapping(value="/setcookie", method = RequestMethod.GET)
public String setCookie(HttpServletResponse response){
    response.addCookie(new Cookie("srpingCookie", "this cookie was set by Spring"));
    return "cookieIsSet";
}

To read cookies on Spring

// all the cookies can be seen here regardless of that the cookie was set on client side or server side
@RequestMapping(value="/readcookie", method = RequestMethod.GET)
public String showCookie(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null){
 for (Cookie cookie : cookies){
     System.out.println(cookie.getName() + " : " + cookie.getValue());
        }
    }
        
    ...
}

or

// mycookie must be available otherwise HTTP 400 occurs
// the cookie value will be unescape'd automatically
@RequestMapping(value="/readparticularcookie", method = RequestMethod.GET)
public String showDinoCookie(@CookieValue("mycookie") String cookie){
    System.out.println(cookie);

    ...
}

Reference
http://www.w3schools.com/js/js_cookies.asp

Tuesday, September 24, 2013

class vs primitive data type in Java

Java has 8 primitive data types, they are byte, short, int, long, float, double, boolean, and char, and also has class of each of them.

A class is a wrapper of a primitive variable, for example, the Integer class document states "The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int."

But there is still difference in usage, the class type variable can be assigned with value null and stored in the container while a primitive variable cannot. But primitive type is found to have advantage in performance, here is the discussion, Why do people still use primitive types in Java?

Monday, September 16, 2013

Hibernate one-to-many with child entity using composite primary key

Scenario: A customer can have multiple orders. The customer entity has cid as primary key, the order has composite primary key (order_id + cid)

Database tables:

 CREATE TABLE customers (
    cid VARCHAR(8) PRIMARY KEY,
    name VARCHAR(255)
 );

 CREATE TABLE orders (
    order_id INT,
    customer_id VARCHAR(8),
    amount REAL,
    PRIMARY KEY(order_id, customer_id),
    FOREIGN KEY(customer_id) REFERENCES customers(cid)
 );

The Java code using Hibernate ORM will be

Customer.java

@Entity
@Table(name="customers")
public class Customer implements Serializable {
    @Id
    @Column(name="cid")
    private String customerId;

    @OneToMany(fetch=FetchType.EAGER, mappedBy="orderRecordPK.customer")
    @Cascade(CascadeType.ALL)
    private Set<OrderRecord> orderRecords = new HashSet<OrderRecord>();

    ...
    constructor, other fields, getters and setters
}    

OrderRecord.java

@Entity
@Table(name="orders")
public class Order implements Serializable {
    @EmbeddedId
    private OrderRecordPK orderRecordPK;

    ...
    constructor, other fields, getters and setters
}

OrderRecordPK.java

@Embeddable
public class OrderRecordPK implements Serializable{
    @Column(name="order_id")
    private int orderId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="customer_id", nullable=false)
    private Customer customer;

    ...
    constructor, other fields, getters and setters
}


Hibernate one-to-many with child entity using id as primary key

Scenario: A customer can have multiple phones. The customer entity has cid as primary key, and the phone has phone_id as primary key

Database tables:

 CREATE TABLE customers (
    cid VARCHAR(8) PRIMARY KEY,
    name VARCHAR(255)
 );

 CREATE TABLE phones (
    phone_id INT PRIMARY KEY,
    customer_id VARCHAR(8),
    number INT,
    FOREIGN KEY(customer_id) REFERENCES customers(cid)
 );

The Java code using Hibernate ORM will be

Customer.java

@Entity
@Table(name="customers")
public class Customer implements Serializable {
    @Id
    @Column(name="cid")
    private String customerId;

    @OneToMany(fetch=FetchType.EAGER, mappedBy="customer")
    @Cascade(CascadeType.ALL)
    private Set<OrderRecord> phones = new HashSet<OrderRecord>();

    ...
    constructor, other fields, getters and setters
}    

Phone.java

@Entity
@Table(name="phones")
public class Phone implements Serializable {
    @Id
    @Column(name="phone_id")
    private int phoneId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="customer_id", nullable=false)
    private Customer customer;

    ...
    constructor, other fields, getters and setters
}

Next, Hibernate one-to-many with child entity using composite primary key