BDD: Cucumber Hello World Using Java and IntelliJ

Categories: Java; Tagged with: ; @ March 14th, 2015 16:42


Feature: Convert between different currencies
  Scenario: Convert SGD to CNY
    Given currency:"SGD", amount:10
    Given fxRate is 4.60
    When convert to "CNY"
    Then the result is 46 in CNY

JUnit Test: it can be generated by cucumber plugins, but not perfect for my IDE. (cannot generate all steps, but you still can copy the generated JUnit code from the output)

package com.liguoliang.bdd;

import cucumber.annotation.Before;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import org.junit.Assert;

import java.math.BigDecimal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

 * Created by guoliang on 3/14/15.
public class FxConverterTest {

    private FxConverter fxConverter;

    public void setUp() {
        fxConverter = new FxConverter();

    @Given("^currency:\"([^\"]*)\", amount:(\\d+)$")
    public void currency_amount(String currency, BigDecimal amount) throws Throwable {

    @Given("^fxRate is (.+)$")
    public void fxRate_is_(BigDecimal rate) throws Throwable {

    @When("^convert to \"([^\"]*)\"$")
    public void convert_to(String currency) throws Throwable {


    @Then("^the result is (.+) in CNY$")
    public void the_result_is_in_CNY(BigDecimal resultExpected) throws Throwable {
        assertTrue(resultExpected.compareTo(fxConverter.getAmountResult()) == 0);


Java: calculate number complement using BitSet

Categories: Java; Tagged with: ; @ March 10th, 2015 20:15

Two’s complement is the way every computer I know of chooses to represent integers. To get the two’s complement negative notation of an integer, you write out the number in binary. You then invert the digits, and add one to the result.

    	Integer input = 50;
    	String binString = Integer.toBinaryString(input);
    	BitSet bitSet = BitSet.valueOf(new long[] {input});
    	for (int i = 0; i < binString.length(); i++) {

Switch: throw an exception if default section shouldn’t be reached? #Route 85 – Quick Tip: Don’t Default that Switch!

Categories: Java; Tagged with: ; @ March 8th, 2015 21:32

There’s a quick tip from Google developers about switch, the suggestion is getting rid of throwing exception in switch default section if the default handler shouldn’t be reached.

Here’s an example in Java:


 * Created by Guoliang, Li( on 3/8/2015.

public class SwitchDefaultDemo {

    public static void main(String[] args) {
;    }

    private static String getBookCategoryDesc(BookCategory bookCategory) {
        String desc = null;
        switch (bookCategory) {
            case JAVA:
                desc = "It's a Java book";
            case PYTHON:
                desc = "It's a PHP book";
                throw new RuntimeException("Unknown book category");

        return desc;

    public static enum BookCategory {
        JAVA, PYTHON, PHP;

The tip’s point is if developer added a new enum and forgot to update the switch statement accordingly, there’ll be a issue, it may fail the test or crash the application.

so to improve the switch statement, the video suggest to remove the default section. if some client calls getBookCategoryDesc(PHP), the method will be executed normally, instead of throwing an exception.

it seems debatable for me, I prefer to keep the exception,  throwing an exception to exposure the risk instead of hiding it, because the exception tells the details, developers can fix the bug immediately. otherwise, developers will realize the issue and start to debug until user reporting it.

Google Protocol Buffers Helloworld(Java)

Categories: Java; Tagged with: ; @ July 3rd, 2014 0:15

This is a Protocol Buffers hello world project following

you may find all source code from github:


Code Generation

The message definition: addressbook.proto;

D:\dev\tools\protoc-2.5.0-win32>protoc.exe -I=D:\dev\..\src\main\resosurce\ --java_out=D:\dev..\src\main\java  D:\dev\…\resosurce\addressbook.proto is the generated Java class;



public class ProtocolBuffersTest {
     private static final String name = "google";

     public void testBuildInstance() throws Exception {
         Person person = buildNewPerson();
         assertEquals(name, person.getName());

     public void testWriteInstanceToFile() throws Exception {
         String path = "./src/test/resources/address.txt";
         AddressBook.Builder addressBookBuilder = AddressBook.newBuilder();
         AddressBook addressBook =;
         FileOutputStream outputStream = new FileOutputStream(path);
         System.out.println("AddressBook write to :\n " + path);
         URL url = Resources.getResource("./address.txt");
         String contentInFile = Resources.toString(url, Charsets.UTF_8);
     public void testParseInstanceFromFile() throws FileNotFoundException, IOException {
         AddressBook.Builder addressBookBuilderRead = AddressBook.newBuilder();
         addressBookBuilderRead.mergeFrom(new FileInputStream("./src/test/resources/address-test.txt"));
         AddressBook addressBookRead =;
         System.out.println("AddressBook loaded: \n" + addressBookRead.toString());
         assertEquals(1, addressBookRead.getPersonCount());
         Person person = addressBookRead.getPerson(0);
         assertEquals(name, person.getName());
     private Person buildNewPerson() {
         Person.Builder personBuilder = Person.newBuilder();
         Person person =;
         return person;


Quick Setup a Project Using JDBC & Derby DB/Java DB

Categories: DatabaseJava; Tagged with: ; @ May 8th, 2014 0:03

Set up Maven dependences



Connect to the DB using JDBC

This method will print out all Tables;  // before you do anything with the Database, there should be some System tables already.

package com.liguoliang;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCTest {

	private static final String DB_URL = "jdbc:derby:tempDBForTest;create=true";	
	public static void main(String[] args) {
	    Connection conn = null ;
	    try {
	        Class.forName("org.apache.derby.jdbc.EmbeddedDriver") ;
	        conn = DriverManager.getConnection(DB_URL);
			PreparedStatement ps = conn.prepareStatement(sql);
	        ResultSet rs = ps.executeQuery();
	        while ( {
				System.out.println("Rs: " + rs.getString(1));
	    } catch (SQLException se) {
	    } catch(ClassNotFoundException e){
	        System.out.println("JDBC Driver not found in CLASSPATH") ;
	    }finally {
	        if(conn != null){
	                conn.close() ;
	            } catch(SQLException se){


Use Eclipse to manage your Derby

Switch to ‘Database Development’ perspective, you may create/manage  Derby DB/table.

Older Posts

// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.