Sunday, September 21, 2014

Ruby on Rails Getting Started


Pre-request

Ruby Getting Started
http://ben-bai.blogspot.tw/2014/09/ruby-getting-started.html

SQLite Getting Started
http://ben-bai.blogspot.tw/2014/09/sqlite-getting-started.html

Note

You can also use rails installer to install ruby, sqlite and rails at once.
see http://railsinstaller.org/en

Simple Note

Follow tutorial
http://guides.rubyonrails.org/getting_started.html

But not works



Follow Installation Instructions at
https://github.com/oneclick/rubyinstaller/wiki/Development-Kit
to install Development Kit



Test Development Kit



Install Rails again



Still has some error, but seems rails is installed.

Follow tutorial, type "rails new blog" to create a blog and run server



Hello, Rails!


Ruby Getting Started


Simple Note

Go to http://rubyinstaller.org/downloads/ and
choose latest stable version (1.9.3 for now)
or
check the recommanded version in download page of RoR.
http://rubyonrails.org/download/
I prefer the stable one.

Download it

run installer

follow tutorial to run first gem
http://guides.rubygems.org/make-your-own-gem/#first-gem

testing process and result
https://github.com/benbai123/RubyOnRails/blob/master/Practice/Ruby_Getting_Started/test.png

Full test project at github
https://github.com/benbai123/RubyOnRails/tree/master/Practice/Ruby_Getting_Started

Friday, September 19, 2014

SQLite Getting Started


Simple Note


Go to http://www.sqlite.org/

Go to download page

Download Precompiled Binaries for Windows
(sqlite-shell and sqlite-dll here)

Unzip them into a folder (e.g. C:\programs\sqlite)

Add the folder above into Path (the Environment variable)
or you will need to cd to that folder each time.

Open cmd

Type "sqlite3 test.db"
test.db created

now you can use SQL to access test.db

you can also execute "sqlite3" then choose database with attach command,
e.g. attach "test.db" as test
see http://stackoverflow.com/questions/9057787/opening-database-file-from-within-sqlite-command-line-shell

Monday, July 7, 2014

Flyweight Pattern in Java


Simple Note

From reference "Flyweight pattern":
flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.


Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/flyweight

Run TestMain.java to test.

Assume you need to calculate lots of sum of a range of Fibonacci Numbers.
There are 2 shared items in FibRangedSum:
1. Calculated results (a Map, with Multiton Pattern)
2. Fibonacci sequence (a List, not Multiton Pattern but still Flyweight Pattern)

References:

Flyweight pattern

Fibonacci number

Thursday, June 19, 2014

Java Weak Reference


Simple Note

From reference:
A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself.

Program

https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/JAVA/Commons/src/test/WeakReferenceTest.java

References:

Understanding Weak References

Sunday, June 15, 2014

Composite Pattern in Java


Simple Note

From reference:
the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/composite

Run TestMain.java to test.

A Calculator probably consists of several child Calculators, you can change mode from parent Calculator then get result as needed.

References:

Composite pattern

Saturday, June 14, 2014

Bridge Pattern in Java


Simple Note

From reference:
The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently". The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as two layers of abstraction.

Difference between Bridge Pattern and Adapter Pattern:
See reference.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/bridge

Run TestMain.java to test.

Assume there are several calculator implements interface DesiredCalculator and you access them via a Bridge class rather than access them directly.
Once the API of DesiredCalculator is changed, you just need to update the content within Bridge class, all other parts of your program can stay unchanged.

References:

Bridge pattern

Difference between Bridge pattern and adapter pattern

Monday, June 9, 2014

Adapter Pattern in Java


Simple Note

From reference:
The adapter design pattern is used when you want two different classes with incompatible interfaces to work together. Interfaces may be incompatible but the inner functionality should suit the need. The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/adapter

Run TestMain.java to test.

Assume you hope all calculators implement the interface DesiredCalculator but the PowerOfTwoCalc didn't, and assume it is provided by 3rd party in a jar.
Now you can use Adapter Pattern to create DesiredPowerOfTwoCalculator that implements DesiredCalculator and let PowerOfTwoCalc do real operation inside rather than rewrite all functions yourself.

Reference:

Adapter pattern

Object Pool Pattern in Java


Simple Note

From reference:
The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished, it returns the object to the pool rather than destroying it; this can be done manually or automatically.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/objectpool

Run TestMain.java to test.

The ThreadPool create and handle WorkingThread to execute Runnable task,
and use Decorator Pattern to wrap Runnable task to restore WorkingThread automatically for reuse.

Reference:

Object pool pattern

Singleton Pattern in Java


Simple Note

From reference:
singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/singleton

Run TestMain.java to test.

There is only one Config instance in whole application.

References:

Singleton pattern

Difference between static class and singleton pattern?

Why use a singleton instead of static methods?

Friday, June 6, 2014

Prototype Pattern in Java


Simple Note

From reference:
The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
* avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
* avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/prototype

Run TestMain.java to test.

There are several default membership packages of a gym and you can always talk to salesmen to obtain a customized package that better for you.

Reference:

Prototype pattern

Design patterns in the test of time: Prototype

Thursday, May 22, 2014

Multiton Pattern (Registry of Singletons) in Java


Simple Note

From reference:
The multiton pattern expands on the singleton concept to manage a map of named instances as key-value pairs.
Rather than having a single instance per application (e.g. the java.lang.Runtime object in the Java programming language) the multiton pattern instead ensures a single instance per key.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/multiton

Run TestMain.java to test.

Put Vitamin into VitaminBox, there is only one VitaminBox for a kind of Vitamin.

Reference:

Multiton pattern

Wednesday, May 21, 2014

Smart Proxy Pattern in Java


Simple Note

From reference:
A smart proxy interposes additional actions when an object is accessed. Typical uses include:
Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer),
Loading a persistent object into memory when it's first referenced,
Checking that the real object is locked before it is accessed to ensure that no other object can change it.

Smart References: providing a sophisticated access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/smartproxy

Run TestMain.java to test.

OperatorProxy will limit the operation performed by RealOperator, at most 3 operation at a time.

Reference:

Proxy Design Pattern

Proxy Pattern

Protection Proxy Pattern in Java


Simple Note

(From Reference)
Protective Proxy – The protective proxy acts as an authorisation layer to verify if the actual user has access to appropriate content. An example can be thought about the proxy server which provides restrictive internet access in office. Only the websites and contents which are valid will be allowed and the remaining ones will be blocked.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/protectionproxy

Run TestMain.java to test.

ProxyMouseController will check role first then control mouse via RealMouseController

Reference:

Gang of Four – Proxy Design Pattern

Tuesday, May 20, 2014

Remote Proxy Pattern in Java


Simple Note

(From Reference)
Remote Proxy – A remote proxy can be thought about the stub in the RPC call. The remote proxy provides a local representation of the object which is present in the different address location. Another example can be providing interface for remote resources such as web service or REST resources.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/remoteproxy

Run TestMain.java to test.

Access Google Geo Services via GeoServiceProxy

The sample is based on Java Practice: java.net practice, Use Google Geocode Web Service

Reference:

Gang of Four – Proxy Design Pattern

Sunday, May 18, 2014

Control Mouse Move in Java


Simple Note

Use java.awt.Robot class.

Code

package proxy.remoteproxy;

import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Robot;

public class TestMain {
    public static void main (String args[]) throws AWTException, InterruptedException {
        // get X/Y position of mouse cursor
        int posX = (int)MouseInfo.getPointerInfo().getLocation().getX();
        int posY = (int)MouseInfo.getPointerInfo().getLocation().getY();

        Robot bot = new Robot();
        // move around a rect
        bot.mouseMove(posX-30, posY-30);
        Thread.sleep(1000);
        bot.mouseMove(posX+30, posY-30);
        Thread.sleep(1000);
        bot.mouseMove(posX+30, posY+30);
        Thread.sleep(1000);
        bot.mouseMove(posX-30, posY+30);
        Thread.sleep(1000);
        bot.mouseMove(posX-30, posY-30);
        Thread.sleep(1000);
        // back to start position
        bot.mouseMove(posX, posY);
    }
}


Reference

Class Robot

Get X/Y Position of Mouse Cursor in Java


Simple Note

Use java.awt.MouseInfo as below:

        MouseInfo.getPointerInfo().getLocation().getX();
        MouseInfo.getPointerInfo().getLocation().getY();

Reference

Get Mouse Position

Saturday, May 17, 2014

Virtual Proxy Pattern in Java


Simple Note

(From SO)
A Virtual Proxy creates expensive objects on demand

(From Wiki)
Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/virtualproxy

Run TestMain.java to test.

ProxyFactorial will create and cache the Factorial object on demand.

Reference:

Proxy pattern

Lazy initialization

Great answer at SO

Factorial

Friday, May 16, 2014

Decorator Pattern in Java


Simple Note

(From wiki):
The decorator pattern (also known as Wrapper, an alternative naming shared with the Adapter pattern) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/decorator

Run TestMain.java to test.

OldSiren().alarm() will only output a message in console, BeepDecorator can wrap OldSiren to add a beep.

Reference:

Decorator pattern

Grate answer at stackoverflow

Thursday, May 15, 2014

Builder Pattern in Java


Simple Note

(From wiki):
the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/builder

Run TestMain.java to test.

Add base rice and lots of ingredients one by one to DonburiBuilder then build Donburi.

Reference:

Builder pattern

Grate answer at stackoverflow

Donburi

Factory Method Pattern in Java


Simple Note

(From wiki):
The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/factory/factorymethod

Run TestMain.java to test.

abstract class Audience has a method enjoy, will get a Player to play something then enjoy.
the abstract method getPlayer can be overridden by subclass to provide different Player as needed.

Reference:

Factory method pattern (wiki)

Wednesday, May 14, 2014

Abstract Factory Pattern in Java


Simple Note

(From wiki):
The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.
(From OODesign)
Offers the interface for creating a family of related object, without explicitly specifying their classes.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/factory/abstractfactory

Run TestMain.java to test.

A FoodStore  that sells Bread from BreadFactory in odd weeks and sells PASTA from PastaFactory in even weeks.

In my opinion, Abstract Factory Pattern is most likely 'Chained Simple Factory Pattern'.

Reference:

Abstract factory pattern

Abstract Factory

Simple Factory Pattern in Java


Simple Note

Simple Factory Pattern:
A method that can return different hardcoded subtypes.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/factory/simplefactory

BreadFactory that produce WonderfulBread at 3rd day of a week and produce CommonBread in other days

Can rely on the abstract class "Bread" in program, do not need to know whether it is a WonderfulBread or CommonBread

Reference:

Factory (object-oriented programming)

Simple Factory vs. Factory Method vs. Abstract Factory

Saturday, May 10, 2014

JAVA Protected Modifier Testing


Simple Note

A little bit confused by protected modifier in JAVA:

Test cases:
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/Commons/src/modifier/protectedtest

see derived class in packagea/packageb.

References

Controlling Access to Members of a Class
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Sunday, May 4, 2014

JMX Getting Started: Standard MBean


Simple Note

Introduction

From official site:
The JMX technology provides the tools for building distributed, Web-based, modular and dynamic solutions for managing and monitoring devices, applications, and service-driven networks. By design, this standard is suitable for adapting legacy systems, implementing new management and monitoring solutions, and plugging into those of the future. 

This article describe how to write JMX Standard MBeans.

Result

View demo on line
http://screencast.com/t/R80hAMjZcggm

Program

Test.java
The testing class to run.

TestBean.java
Test java bean, contains some operations and attribute.

TestBeanMBean.java
The interface for TestBean, according to JMX Standard MBean convention the name should be TestBeanMBean.

How to Run (Windows7/JDK6)

1. Download the bin/test  folder to some where.

2. Open cmd, go to the folder that contains the downloaded test folder.

3. Run it with "java -cp . test.Test".

4. Open jconsole.exe at your jdk/bin folder and try it.

Note:
1. If you didn't setup PATH properly (i.e. cannot execute java command any where) you can copy test folder to path_to_your_jdk_folder/bin.

2. You may need to change TMP folder to different location, please refer to the related thread on oracle community.

Reference

Standard MBean
http://docs.oracle.com/javase/tutorial/jmx/mbeans/standard.html

TMP Issue
https://community.oracle.com/thread/1176284?start=0&tstart=0

Download

Full project at github
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/JMX/MBeans/StandardMBean

Thursday, April 3, 2014

ZK, AngularJS and Pure HTML Template


Introduction

As we already know ZK used to generate all html content within 'redraw' function of a ZK Widget, this is a little bit (?) hard to maintain and customize dom structure and style of component.

This article describe how to create ZK Component with AngularJS Directive so you can use a pure HTML template to generate dom elements of ZK Component and has some advantages:
1. Easier to maintain.
2. Easier to customize.

And also some drawbacks (part of them has workaround):
1. Need to load html template via several ajax call.
  Workaround: You can load all templates at once,
       for more information please refer to
       AngularJS: load all templates in one file or AngularJS Merge Template
2. Will blink while rerender, you can use a fake dom to avoid blinking but this may affect the client side performance.
3. Has issue of dynamically insert and compile complex dom elements so need to rerender if dynamically add children.

Note:

1. This is just a POC done in a short time, probably not well organized and has some unknown issues.
2. I am not familiar with AngularJS so this POC may contains bad practice.

Pre-request

AngularJS Create Components

ZK Component Development Tutorial: Getting Started

ZK CDT: Fire Event to Server to Create a SelectableTextNote

Result

Online demo
http://screencast.com/t/nlLsNdbV8A

Description:

The concept is simple.

In AngularJS, a directive which support pure html template is a function that returns an Object Literal, and registered with a specific name (see Creating Custom Directives).
Both of them -- the name and the function -- can be declared at any places.
e.g. inside the Javascript of ZK Widget.

So we can specify Angular Tag (ngTag) and Angular Template Url (ngTemplateUrl) to each ZK Component and do below:

In ZK Component:
* Server Side:
** Make sure that each templateUrl maps to different tag.
* Client Side:
** Output ngTag in redraw function.
** Store component to zk.ngcomponents in redraw function.
** Register Angular Directive with ngTag.

In Angular Directive
* Use ngTemplateUrl as templateUrl in directive.
* Store $scope, $compile and controller to $element in controller function of directive.
* Bind ZK Widget with Angular Objects above in link function of directive.

Then we can use AngularJS Directive with pure HTML Template then control ZK Widget from AngularJS Directive and vice versa.

See

NgComp.java#fixTemplateMapping
NgComp.js#redraw
tabs.js#registerTemplate
zacomponents.js#addComponent
zacomponents.js#storeNgObjects
zacomponents.js#directive
zacomponents.js#bindng_

for more information.

Program Introduction

Testing zul page
index.zul

Testing Composer
TestComposer.java

AngularJS Library
angular.min.js

Bootstrap3 CSS Library
bootstrap.min.css

Utils for AngularJS ZK Widget
zacomponents.js

Basic APIs of AngularJS ZK Widget
NgComp.js

The Folder Contains All Default Templates
templates

Basic Java Class for AngularJS ZK Component
NgComp.java

Others:
Please refer to the full project below

Download

Full project at github

Demo Flash (click View Raw to download)

Sunday, March 30, 2014

ZK MVVM Command Data -- Loose Coupling More


Introduction

ZK MVVM already support Parameter of Command, it slightly increased the coupling since it bind the data with "parameter names", means you need to update both .zul and .java files if you want to change the naming.

This article describe a way to reduce the coupling, it bind the data with event name (instead of parameter names) with a custom component tag and retrieve command data by EventInterceptor.

Note:
Please ignore the implementation detail when you look into this sample, they are not the important part here and can be replaced by any other implementation (e.g. implemented by ZK MVVM mechanism itself in the future).
The only key point is "bind data with event name instead of parameter names".

Pre-request

ZK Create Helper Tag to Make Programmer Happier

Demo

video


Program

index.zul

TestVM.java

Item.java

Cparam.java

ComponentParameterInterceptor.java

zk.xml

lang-addon.xml

Download

Full project at github

Demo Flash

Tuesday, March 11, 2014

JSP Fileupload Progress Bar


Simple Note

JSP fileupload with Apache Commons FileUpload
Display upload progress bar

Pre-request

JSP Fileupload without Redirect/Refresh

Full Project

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/Tools/FileUpload

Testing files

WebContent/fileupload_progressbar.jsp
src/test/UploadProgressServlet.java

JSP Fileupload without Redirect/Refresh


Simple Note

JSP fileupload with Apache Commons FileUpload
Upload file without page redirect, page refresh or open new page.

Pre-request

JSP Apache Fileupload

Full Project

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/Tools/FileUpload

Testing files

WebContent/fileupload_norefresh.jsp
src/test/UploadServlet.java

Sunday, March 9, 2014

JSP Apache Fileupload

Simple Note

Practice project of Fileupload in JSP

Full Project
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/Tools/FileUpload

First Page
WebContent/test.jsp
src/test/UploadServlet.java

Monday, February 3, 2014

AngularJS Wireup Backend


Simple Note

Official sample with personal comments.

To run this sample you will need need to setup a server since this sample rely on ajax that need to be run under http protocol.

Personally I do not like this sample, mixing too many things and not described well.

Pre-request

AngularJS Controller


Testing Files

Run test.html to test

https://github.com/benbai123/HTML_CSS_Javascript_practice/tree/master/Frameworks/Angularjs/Basic/Basic_003__Wireup_Backend

JS Libs

https://github.com/benbai123/HTML_CSS_Javascript_practice/tree/master/Frameworks/Angularjs/lib

Reference

http://angularjs.org/

AngularJS Controller


Simple Note

Official sample with personal comments.

Pre-request

AngularJS getting started

Testing Files

https://github.com/benbai123/HTML_CSS_Javascript_practice/tree/master/Frameworks/Angularjs/Basic/Basic_002__Controller

JS Libs

https://github.com/benbai123/HTML_CSS_Javascript_practice/tree/master/Frameworks/Angularjs/lib

Reference

http://angularjs.org/

AngularJS getting started


Simple Note

Official sample with personal comments.

Code

https://github.com/benbai123/HTML_CSS_Javascript_practice/blob/master/Frameworks/Angularjs/Basic/Basic_001__Getting_Started/test.html

JS Libs

https://github.com/benbai123/HTML_CSS_Javascript_practice/tree/master/Frameworks/Angularjs/lib

Reference

http://angularjs.org/