Wednesday, April 29, 2015

VIM hex editing

http://usevim.com/2012/06/20/vim-binary-files/
http://blog.changyy.org/2010/01/vim-hex-mode-16.html
http://vim.wikia.com/wiki/Hex_dump
http://vim.wikia.com/wiki/Improved_hex_editing

Thursday, April 23, 2015

My choice of UML diagramming tool

When reading OO codes, it's always good habits to draw UML diagrams for them(Class diagram, Sequential diagram, etc.) to help memorizing them better.

Currently I choose ArgoUML:
ArgoUML is the leading open source UML modeling tool and includes support for all standard UML 1.4 diagrams. It runs on any Java platform and is available in ten languages.

Steps to download and install under Ubuntu:
1. Download http://argouml-downloads.tigris.org/nonav/argouml-0.34/ArgoUML-0.34.tar.gz
2. Unzip to ~/ws/pkg/argouml-0.34/
3. Run by java -jar ~/ws/pkg/argouml-0.34/argouml.jar
4. Have fun.

Tutorials:
http://www.objectmentor.com/resources/articles/umlClassDiagrams.pdf
http://creately.com/diagram-type/article/simple-guidelines-drawing-uml-class-diagrams
http://www.tutorialspoint.com/uml/uml_class_diagram.htm
http://www.visual-paradigm.com/features/uml-and-sysml-modeling/?src=google&kw=class%20diagram&mt=p&net=g&plc=&gclid=CjwKEAjwsOKpBRCDtfOnzaDg3HsSJAAJ2oji0gt4d4JNFeLU8-fEveRwYXuEsXVxsLP4lJasV5IPmhoCz-zw_wcB#class-diagram

Reference:
http://stackoverflow.com/questions/15376/whats-the-best-uml-diagramming-tool
http://argouml.tigris.org/


Sunday, April 5, 2015

Boost.PropertyTree

What is Property Tree?
http://www.boost.org/doc/libs/1_57_0/doc/html/property_tree.html#boost_propertytree.intro

Five Minute Tutorial
http://www.boost.org/doc/libs/1_57_0/doc/html/boost_propertytree/tutorial.html

How to Populate a Property Tree
http://www.boost.org/doc/libs/1_57_0/doc/html/boost_propertytree/parsers.html






What do real-user-sys mean in the output of time(1)

[From http://man7.org/linux/man-pages/man1/time.1.html and http://man7.org/linux/man-pages/man2/times.2.html]
---------------------------------------------------------------------------
(i)   the elapsed real time between invocation and termination,
(ii)  the user CPU time (the sum of the tms_utime and tms_cutime values in a struct tms as returned by times(2))
(iii) the system CPU time (the sum of the tms_stime and tms_cstime values in a struct tms as returned by times(2)).

real  = Elapsed real (wall clock) time
user  = tms_utime + tms_cutime
sys   = tms_stime + tms_cstime

struct tms {
  clock_t tms_utime;  /* user time */
  clock_t tms_stime;  /* system time */
  clock_t tms_cutime; /* user time of children */
  clock_t tms_cstime; /* system time of children */
};
---------------------------------------------------------------------------

[From Ubuntu "$ man time"]
---------------------------------------------------------------------------
real %e
user %U
sys %S

The resource specifiers, which are a superset of those recognized by the tcsh(1) builtin `time' command, are:
%      A literal `%'.
E      Elapsed real (wall clock) time used by the process, in [hours:]minutes:seconds.
P      Percentage of the CPU that this job got.  This is just user + system times divided by the total running time. It also prints a percentage sign.
S      Total number of CPU-seconds used by the system on behalf of the process (in kernel mode), in seconds.
U      Total number of CPU-seconds that the process used directly (in user mode), in seconds.
e      Elapsed real (wall clock) time used by the process, in seconds.
---------------------------------------------------------------------------

References:
http://stackoverflow.com/questions/556405/what-do-real-user-and-sys-mean-in-the-output-of-time1
http://blog.he96.com/2011/01/linux-timewhat-do-real-user-and-sys.html
http://yuanfarn.blogspot.tw/2012/08/linux-time.html

Use valgrind's callgrind tool to find out the most time consuming function in your application

  1. Use "$ valgrind --tool=callgrind ./APPLICATION ..." to analyze application performance,
     it will generate a callgrind output(ex:callgrind.out.7722) to help you get performance informations:
      $ valgrind --tool=callgrind ./your_application param1 param2 ...
     
  2. Use kcachegrind tool to visualize callgrind output:
      $ sudo apt-get install kcachegrind
      $ kcachegrind callgrind.out.7722
     
  3. REF: http://baptiste-wicht.com/posts/2011/09/profile-c-application-with-callgrind-kcachegrind.html

Monday, March 9, 2015

Using gvim under Cygwin

Today I am trying to using gvim under Cygwin console but it failed:
$ which vim
/usr/bin/vim

$ which gvim
/usr/bin/gvim

$ gvim
E233: <δΈθƒ½ι–‹ε•Ÿ X Server DISPLAY>
Press ENTER or type command to continue

From below link we know I have to install X-Server to Cygwin:
http://stackoverflow.com/questions/12430633/how-can-i-get-mintty-cygwin-terminal-to-open-gvim-in-a-new-window

Here are how to install and enable X-Server under Cygwin:
[Official site]
http://x.cygwin.com/

[Installing Cygwin/X]
A listing of the Cygwin/X packages is given below; a listing of the general Cygwin packages would be beyond the scope of this document.
Cygwin/X packages are located in the X11 category.
  • xorg-server (required, the Cygwin/X X Server)
  • xinit (required, scripts for starting the X server: xinit, startx, startwin (and a shortcut on the Start Menu to run it), startxdmcp.bat )
  • xorg-docs (optional, man pages)
  • xlaunch (optional, a wizard for starting X sessions)
  • You may also select any X client programs you want to use, and any fonts you would like to have available.
  • You may also want to ensure that the openssh package is selected if you wish to use ssh connections to run remote X clients.
  • You may also want to ensure that the inetutils or rsh packages are selected if you wish to use telnet or rsh connections to run remote X clients. (not recommended)
[Starting Cygwin/X]
$ startxwin

Welcome to the XWin X Server
Vendor: The Cygwin/X Project
Release: 1.17.1.0
OS: CYGWIN_NT-6.1 TW1W7D-400077 1.7.35(0.287/5/3) 2015-03-04 12:09 x86_64
OS: Windows 7 Service Pack 1 [Windows NT 6.1 build 7601] (Win64)
Package: version 1.17.1-2 built 2015-02-23

XWin was started with the following command line:

/usr/bin/XWin :0 -multiwindow -auth /home/linst/.serverauth.7912

(II) xorg.conf is not supported
(II) See http://x.cygwin.com/docs/faq/cygwin-x-faq.html for more information
LoadPreferences: /home/linst/.XWinrc not found
LoadPreferences: Loading /etc/X11/system.XWinrc
LoadPreferences: Done parsing the configuration file...
winDetectSupportedEngines - DirectDraw4 installed, allowing ShadowDDNL
winDetectSupportedEngines - Returning, supported engines 00000005
winSetEngine - Multi Window or Rootless => ShadowGDI
winScreenInit - Using Windows display depth of 32 bits per pixel
winAllocateFBShadowGDI - Creating DIB with width: 3520 height: 1080 depth: 32
winFinishScreenInitFB - Masks: 00ff0000 0000ff00 000000ff
winInitVisualsShadowGDI - Masks 00ff0000 0000ff00 000000ff BPRGB 8 d 24 bpp 32
MIT-SHM extension disabled due to lack of kernel support
XFree86-Bigfont extension local-client optimization disabled due to lack of shared memory support in the kernel
glWinSelectGLimplementation: Loaded 'cygnativeGLthunk.dll'
(II) AIGLX: Testing pixelFormatIndex 5
GL_VERSION:     4.5.0 NVIDIA 347.25
GL_VENDOR:      NVIDIA Corporation
GL_RENDERER:    GeForce GT 640/PCIe/SSE2
(II) AIGLX: enabled GLX_SGI_make_current_read
(II) AIGLX: enabled GLX_MESA_copy_sub_buffer
(II) AIGLX: enabled GLX_SGI_swap_control and GLX_MESA_swap_control
(II) AIGLX: enabled GLX_SGIX_pbuffer
(II) AIGLX: enabled GLX_ARB_multisample and GLX_SGIS_multisample
(II) 482 pixel formats reported by wglGetPixelFormatAttribivARB
(II) AIGLX: Set GLX version to 1.4
(II) 323 fbConfigs
(II) ignored pixel formats: 0 not OpenGL, 54 RBGA float, 69 RGBA unsigned float, 0 unknown pixel type, 36 unaccelerated
(II) GLX: Initialized Win32 native WGL GL provider for screen 0
winPointerWarpCursor - Discarding first warp: 1760 540
(--) 8 mouse buttons found
(--) Setting autorepeat to delay=500, rate=31
(--) Windows keyboard layout: "00000409" (00000409) "US", type 4
(--) Found matching XKB configuration "English (USA)"
(--) Model = "pc105" Layout = "us" Variant = "none" Options = "none"
Rules = "base" Model = "pc105" Layout = "us" Variant = "none" Options = "none"
winInitMultiWindowWM - DISPLAY=:0.0
winMultiWindowXMsgProc - DISPLAY=:0.0
winProcEstablishConnection - winInitClipboard returned.
winClipboardThreadProc - DISPLAY=:0.0
OS maintains clipboard viewer chain: yes
winInitMultiWindowWM - XOpenDisplay () returned and successfully opened the display.
winMultiWindowXMsgProc - XOpenDisplay () returned and successfully opened the display.
winClipboardProc - XOpenDisplay () returned and successfully opened the display.
winMultiWindowXMsgProcErrorHandler - ERROR: BadMatch (invalid parameter attributes)

After that, a new window will opened, you can now start gvim($ gvim) correctly!

[Switching out of Cygwin/X]
[Stopping Cygwin/X]

Qt 5.4 CMake Manual

This manual details the specifics of how to use Qt 5 with CMake. The minimum version required to use Qt5 is CMake 2.8.3, but 2.8.11 is recommended.

http://doc.qt.io/qt-5/cmake-manual.html

Friday, February 27, 2015

Using Homebrew to install missing cscope/Exuberant Ctags/wget package on my MAC

I am using Homebrew as my MAC package manager now, here's my steps to install missing wget/cscope packages to my macbook pro:

1. Search if there is a "cscope" FORMULA in current Homebrew library:
$ brew search cscope
cscope


2. Start to install cscope:
$ brew install cscope
==> Downloading https://homebrew.bintray.com/bottles/cscope-15.8a.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring cscope-15.8a.yosemite.bottle.tar.gz
🍺  /usr/local/Cellar/cscope/15.8a: 10 files, 736K


3. Install Exuberant ctags:
$ brew search ctags
ctags      rbenv-ctags
homebrew/php/phpctags

$ brew install ctags
==> Downloading https://homebrew.bintray.com/bottles/ctags-5.8.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring ctags-5.8.yosemite.bottle.tar.gz
==> Caveats
Under some circumstances, emacs and ctags can conflict. By default,
emacs provides an executable `ctags` that would conflict with the
executable of the same name that ctags provides. To prevent this,
Homebrew removes the emacs `ctags` and its manpage before linking.

However, if you install emacs with the `--keep-ctags` option, then
the `ctags` emacs provides will not be removed. In that case, you
won't be able to install ctags successfully. It will build but not
link.
==> Summary
🍺  /usr/local/Cellar/ctags/5.8: 8 files, 364K


4. Same way to install wget:
$ brew install wget
==> Installing wget dependency: openssl
==> Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring openssl-1.0.2.yosemite.bottle.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl/certs

and run
  /usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Mac OS X already provides this software and installing another version in
parallel can cause all kinds of trouble.

Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
🍺  /usr/local/Cellar/openssl/1.0.2: 459 files, 18M
==> Installing wget
==> Downloading https://homebrew.bintray.com/bottles/wget-1.16.1.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring wget-1.16.1.yosemite.bottle.tar.gz
🍺  /usr/local/Cellar/wget/1.16.1: 9 files, 940K


References:
http://bearlin001.blogspot.tw/2015/02/homebrew-missing-package-manager-for-os.html

Homebrew: The missing package manager for OS

This is the steps I install homebrew to my macbook pro:

1. Install Homebrew itself:
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
==> This script will install:
/usr/local/bin/brew
/usr/local/Library/...
/usr/local/share/man/man1/brew.1

Press RETURN to continue or any other key to abort
==> /usr/bin/sudo /bin/mkdir /usr/local

WARNING: Improper use of the sudo command could lead to data loss
or the deletion of important system files. Please double-check your
typing when using sudo. Type "man sudo" for more information.

To proceed, enter your password, or type Ctrl-C to abort.

Password:
==> /usr/bin/sudo /bin/chmod g+rwx /usr/local
==> /usr/bin/sudo /usr/bin/chgrp admin /usr/local
==> /usr/bin/sudo /bin/mkdir /Library/Caches/Homebrew
==> /usr/bin/sudo /bin/chmod g+rwx /Library/Caches/Homebrew
==> Downloading and installing Homebrew...
remote: Counting objects: 233669, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 233669 (delta 0), reused 0 (delta 0), pack-reused 233666
Receiving objects: 100% (233669/233669), 29.63 MiB | 423.00 KiB/s, done.
Resolving deltas: 100% (175242/175242), done.
From https://github.com/Homebrew/homebrew
 * [new branch]      master     -> origin/master
HEAD is now at 00667c7 go: show what arch and os is currently building
==> Installation successful!
==> Next steps
Run `brew doctor` before you install anything
Run `brew help` to get started


2. Run Homebrew doctor:
$ brew doctor
Your system is ready to brew.

3. Install package:
$ brew install wget
==> Installing wget dependency: openssl
==> Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring openssl-1.0.2.yosemite.bottle.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl/certs

and run
  /usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local.

Mac OS X already provides this software and installing another version in
parallel can cause all kinds of trouble.

Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries

Generally there are no consequences of this for you. If you build your
own software and it requires this formula, you'll need to add to your
build variables:

    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include

==> Summary
🍺  /usr/local/Cellar/openssl/1.0.2: 459 files, 18M
==> Installing wget
==> Downloading https://homebrew.bintray.com/bottles/wget-1.16.1.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring wget-1.16.1.yosemite.bottle.tar.gz
🍺  /usr/local/Cellar/wget/1.16.1: 9 files, 940K

4. Update Homebrew:
$ brew update
Already up-to-date.

5. Homebrew helps:
$ brew --help
Example usage:
  brew [info | home | options ] [FORMULA...]
  brew install FORMULA...
  brew uninstall FORMULA...
  brew search [foo]
  brew list [FORMULA...]
  brew update
  brew upgrade [FORMULA...]
  brew pin/unpin [FORMULA...]

Troubleshooting:
  brew doctor
  brew install -vd FORMULA
  brew [--env | config]

Brewing:
  brew create [URL [--no-fetch]]
  brew edit [FORMULA...]
  open https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Formula-Cookbook.md

Further help:
  man brew
  brew home


References:
http://brew.sh/
https://blog.engineyard.com/2010/homebrew-os-xs-missing-package-manager/ https://github.com/Homebrew/homebrew

Monday, February 23, 2015

QFontMetrics Class

http://doc.qt.io/qt-5/qfontmetrics.html
http://doc.qt.io/qt-5/qfont.html

https://www.google.com.tw/search?q=QFontMetrics&lr=lang_zh-CN%7Clang_zh-TW&es_sm=122&biw=1920&bih=955&tbs=lr:lang_1zh-CN%7Clang_1zh-TW&source=lnms&tbm=isch&sa=X&ei=FiDsVJfRCsacugTskILYDQ&ved=0CAsQ_AUoBA

https://developer.apple.com/library/mac/documentation/TextFonts/Conceptual/CocoaTextArchitecture/Art/glyph_metrics_2x.png

Monday, November 10, 2014

FacebookSDK how to request permissions

General:
https://developers.facebook.com/docs/facebook-login/permissions/v2.2

List of all permissions:
https://developers.facebook.com/docs/facebook-login/permissions/v2.2#reference

How to request permissions:
https://developers.facebook.com/docs/facebook-login/permissions/v2.2#adding [Generic description]
https://developers.facebook.com/docs/android/login-with-facebook/v2.2 [For Android]

Friend list interface in Facebook SDK after API Version v2.0

[GET /v2.2/me HTTP/1.1]
A user represents a person on Facebook. The /{user-id} node returns a single user.
1. Go to https://developers.facebook.com/docs/graph-api/reference/v2.2/user
2. Click "Graph Explorer" -> "Get Access Token" -> "User Data Permissions" -> Select "user_about_me" -> Click "Get Access Token", you will see a access token look like "CAACEdEose ... ccKEs" show in the field, then click Submit.
3. You will see a JSON string which is an array of Friendlist objects, Ex:
{
    "id": "1234123412341234",
    "bio": "I love music!",
    "first_name": "bear",
    "gender": "male",
    "last_name": "lin",
    "link": "https://www.facebook.com/app_scoped_user_id/1234123412341234/",
    "locale": "zh_TW",
    "name": "bear lin",
    "timezone": 8,
    "updated_time": "2013-11-17T09:22:13+0000",
    "verified": true
}
4. The more Access token you select, the more information will return.


[GET /v2.2/me/friendlists HTTP/1.1]
A person's 'friend lists' - these are groupings of friends such as "Acquaintances" or "Close Friends", or any others that may have been created
1. Go to https://developers.facebook.com/docs/graph-api/reference/v2.2/user/friendlists
2. Click "Graph Explorer" -> "Get Access Token" -> "Extended Permissions" -> Select "read_friendlists" -> Click "Get Access Token", you will see a access token look like "CAACEdEose ... ccKEs" show in the field, then click Submit.
3. You will see a JSON string which is an array of Friendlist objects, Ex:
{
    "data": [
        {
            "id": "4777092484211",
            "name": "Artists",
            "list_type": "user_created"
        },
        {
            "id": "4777064723517",
            "name": "Musicians",
            "list_type": "user_created"
        }
    ],
    "paging": {
        "next": "https://graph.facebook.com/v2.2/1234123412341234/friendlists?limit=5000&offset=5000&__after_id=enc_AeyE7DuzMXSU9JFIGYuR1XfRcZT-U6YI205muBRRkOIAIAk_UhLZ3kMtWkS67_mgwuE"
    }
}

[GET /v2.2/{friendlist-id} HTTP/1.1]
A friend list - an object which refers to a grouping of friends created by someone or generated automatically for someone (such as the "Close Friends" or "Acquaintances" lists)
1. Go to https://developers.facebook.com/docs/graph-api/reference/v2.2/friendlist
2. In the "Graph Explorer" you should replace "{friendlist-id}" with a valid Id(ex: 4777092484211, you can get it from /v2.2/me/friendlists).
3. After submit, Ex:
{
    "id": "4777092484211",
    "name": "Artists",
    "list_type": "user_created"
}
NameDescriptionType
idThe friend list IDstring
nameThe name of the friend liststring
list_typeThe type of the friend listenum{close_friends, acquaintances, restricted, user_created, education, work, current_city, family}

[GET /v2.2/me/friends HTTP/1.1]
A person's friends.
"Friend list now only returns friends who also use your app".
Read below articles fist:
http://stackoverflow.com/questions/23417356/facebook-graph-api-v2-0-me-friends-returns-empty-or-only-friends-who-also-u
https://developers.facebook.com/docs/apps/changelog [Read API Version v2.0 changelog]

1. Go to https://developers.facebook.com/docs/graph-api/reference/v2.2/user/friends
2. In the "Graph Explorer":
Permissions
  • A user access token with user_friends permission is required to view the current person's friends.
  • This will only return any friends who have used (via Facebook Login) the app making the request.
  • If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.
3. After submit: Ex:
{
    "data": [
        {
            "name": "Eric",
            "id": "33333333333333"
        },
        {
            "name": "Lee",
            "id": "111111111111"
        }
    ],
    "paging": {
        "next": "https://graph.facebook.com/v2.2/1234123412341234/friends?limit=25&offset=25&__after_id=enc_AexidG6KKymgeEvLC38u6ERUDQud__sm2tYQkoPMs2ba6l8E17X73s-pSYx5y5hnuDdwFpyt23dt_Gi3GWiZ1raR"
    },
    "summary": {
        "total_count": 307
    }
}
4. You can also using Postman:
GET /v2.2/1234123412341234/friends?access_token=CAACEdEose0cBAIBIg6ZA9P9YNQQxLpmzT4VSBj2dYClv7vIM7aeXNoHpRTq27yGPh14szRVC2VVU6727V66BItbgUuco1tHVo6ZAwr2LhLlZCu3KxuHSuW6ZASBWm9T44RWWnHCbvFELTSJkveqArEAVEdPwkjHIyDFiAQJX6na9uESefCVfX0e4fUNvKjAkvK7b7BSKkhkCEKulWhPO HTTP/1.1
Host: graph.facebook.com


After API Version v2.0, "/me/friends" no longer return full friends list, it only returns the user's friends who are also using your app, please read: http://stackoverflow.com/questions/23417356/facebook-graph-api-v2-0-me-friends-returns-empty-or-only-friends-who-also-u
------------------------------------------------------------------------------------------------------------------------------
In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends permission from each user. user_friendsis no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide  for more detailed information, or review the summary below.
If you want to access a list of non-app-using friends, there are two options:
  1. If you want to let your people tag their friends  in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook  and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
  2. If your App is a Game AND your Game supports Facebook Canvas , you can use the /me/invitable_friends endpoint in order to render a custom invite dialog , then pass the tokens returned by this API to the standard Requests Dialog. 
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as 'by design'. 
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS  and Android .
UPDATE: Facebook have published an FAQ on these changes here:https://developers.facebook.com/docs/apps/faq  which explain all the options available to developers in order to invite friends etc.
------------------------------------------------------------------------------------------------------------------------------
References:
https://developers.facebook.com/docs/apps/faq
https://developers.facebook.com/docs/apps/changelog [Read API Version v2.0 changelog]
https://developers.facebook.com/docs/apps/upgrading#upgrading_v2_0_user_ids

[TODO]
https://developers.facebook.com/docs/graph-api/reference/v2.2/user/taggable_friends
https://developers.facebook.com/docs/graph-api/reference/v2.2/user/invitable_friends

Thursday, November 6, 2014

Change Tomcat HeapSize(JVM Heap) in Eclipse

Recently I've deployed same WAR to Tomcat server on two machines A and B. On machine A everything works well, but on machine B there are error messages: "java.lang.OutOfMemoryError: Java heap space"

I try to reduce Java heap size on machine A to see if same symptom can be reproduce. After change InitialHeapSize and MaxHeapSize to 128MB, I finally can reproduce same issue on machine A.

I am using Tomcat 7 + Eclipse on machine A, here are some references about how to change the heap size using Eclipse:
http://www.mkyong.com/eclipse/eclipse-tomcat-java-lang-outofmemoryerror-java-heap-space/
http://crunchify.com/how-to-increase-tomcat-heapsize-jvm-heap-in-eclipse-ede/

Important parameters:
-Xms<size> - Set initial Java heap size
-Xmx<size> - Set maximum Java heap size
-Xss<size> - Set java thread stack size


Add new Tomcat server arguments in Eclipse on Machine A:
[-XX:+PrintFlagsFinal]
    uintx InitialHeapSize                          := 262228096       {product}           [250MB]
    uintx MaxHeapSize                              := 4196401152      {product}           [4002MB]
     intx ThreadStackSize                           = 1024            {pd product}      
(means the original MaxHeapSize is about 4002MB)

[-Xms512m -Xmx1024m -XX:+PrintFlagsFinal]
    uintx InitialHeapSize                          := 536870912       {product}           [512MB]
    uintx MaxHeapSize                              := 1073741824      {product}           [1024MB]
     intx ThreadStackSize                           = 1024            {pd product}      

[-Xms128m -Xmx128m -XX:+PrintFlagsFinal]
    uintx InitialHeapSize                          := 134217728       {product}           [128MB]
    uintx MaxHeapSize                              := 134217728       {product}           [128MB]
     intx ThreadStackSize                           = 1024            {pd product}        

Wednesday, November 5, 2014

Facebook SDK for Android

[Install the Prerequisites]
1. Prepare your Android development environment
    * Get the Android SDK: http://developer.android.com/sdk/index.html
    * Development tools: JDK 6 (JRE alone is not sufficient), Apache Ant 1.8 or later
    * Create AVD: http://developer.android.com/tools/devices/managing-avds.html
    * Adding SDK Packages: http://developer.android.com/sdk/installing/adding-packages.html
    * Building Your First App: http://developer.android.com/training/basics/firstapp/index.html

2. You'll need to have the Android 2.2 (API 8) components installed in order to use the Facebook SDK.

[Download the Facebook SDK and install Facebook APK for AVD]
1. Download them:
    https://developers.facebook.com/resources/facebook-android-sdk-current.zip
    https://developers.facebook.com/resources/Facebook-11.zip

2. Export PATH:
    * set_env_android.sh:
       $ cat set_env_android.sh
       ANDROID_SDK_HOME="/home/linst/ws/android/ws/adt-bundle-linux-x86_64-20140702/sdk";

       export PATH="${PATH}:${ANDROID_SDK_HOME}/platform-tools";
       export PATH="${PATH}:${ANDROID_SDK_HOME}/tools";

    * source it:
       $ source set_env_android.sh
       $ which adb
       /home/linst/ws/android/ws/adt-bundle-linux-x86_64-20140702/sdk/platform-tools/adb
 
3. Install Facebook APK to emulator:
    * Reason:
"The Facebook SDK uses Facebook's native app to provide support for authentication when it's present. On a real device, you can test this by simply installing this app for free from Google Play. However, it's not possible to access Google Play on an emulator. If you want to test the flow there, you can download and extract the APK of the Facebook app. It should be named Facebook-11.apk or similar. To install it onto an Android emulator ... "
    * Start AVD
    * Install:
       $ unzip Facebook-11.zip
       Archive:  Facebook-11.zip
         inflating: Facebook-11.apk      

       $ adb devices
       List of devices attached
       emulator-5554 device

       $ adb install ./Facebook-11.apk
       2533 KB/s (40683138 bytes in 15.680s)
        pkg: /data/local/tmp/Facebook-11.apk
       Success

4. Import the SDK into Eclipse:
    * Unzip the Facebook SDK:
       $ unzip facebook-android-sdk-3.20.0.zip
    * Import the Facebook SDK library and the samples to Eclipse:
"The installation folder contains a directory called facebook, which is the SDK project itself. There is
also a selection of sample projects in the 
samples folder."

"To import the SDK library project and the samples, with the new SDK, go to Eclipse's 'File' > 'Import' menu, and select 'General' / 'Existing Projects into Workspace'"

"Browse to select the root of your SDK folder, facebook-android-sdk-3.16. The SDK should appear in the list as 'FacebookSDK' along with all of the samples."

"You must unselect the 'Copy projects into workspace' option so that each of the sample projects retains a correct reference to the neighboring SDK. However, this means that Eclipse creates a link to the project in the SDK installation, rather than making a copy of it."

    * Clean your projects to remove build errors: Project -> Clean... -> Clean all projects.
    * Some important paths:
       Facebook SDK root path: /home/linst/ws/android/ws/facebook-android-sdk-3.20.0
       Facebook SDK library: /home/linst/ws/android/ws/facebook-android-sdk-3.20.0/facebook
       Basic Samples: /home/linst/ws/android/ws/facebook-android-sdk-3.20.0/samples
       AudienceNetwork Samples: /home/linst/ws/android/ws/facebook-android-sdk-3.20.0/AudienceNetwork

References:
https://developers.facebook.com/docs/android
https://developers.facebook.com/docs/android/getting-started/
https://developers.facebook.com/docs/reference/android/current

Tuesday, September 30, 2014

GUI SVN and Diff client for Linux/Unix


  1. I choose RapidSVN + Meld for Ubuntu:
    $ sudo apt-get install rapidsvn
    $ sudo apt-get install meld
  2. Start rapidsvn and setting it's diff tool:
    $ rapidsvn -> View -> Preferences... -> Programs -> Diff Tool -> Browse:"/usr/bin/meld", Program arguments: "%1 %2" -> OK.
  3. Download SVN trunk:
    Repositary -> Checkout -> ...
  4. Reference:
    http://en.wikipedia.org/wiki/Comparison_of_Subversion_clients
    http://en.wikipedia.org/wiki/RapidSVN
    http://en.wikipedia.org/wiki/Comparison_of_file_comparison_tools
    http://en.wikipedia.org/wiki/Meld_(software)

Monday, September 29, 2014

svn tutorial

Add library dependency for Maven

This article is about how to add library dependency for Maven, using log4j and commons-logging as example.
  1. Create basic project with maven:
     mvn archetype:generate \
     -DarchetypeArtifactId=maven-archetype-quickstart \
     -DinteractiveMode=false \
     -DgroupId=tw.com.codedata \
     -DartifactId=helloworld
    
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building Maven Stub Project (No POM) 1
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>
     [INFO] 
     [INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
     [INFO] 
     [INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom ---
     [INFO] Generating project in Batch mode
     [INFO] ----------------------------------------------------------------------------
     [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
     [INFO] ----------------------------------------------------------------------------
     [INFO] Parameter: groupId, Value: tw.com.codedata
     [INFO] Parameter: packageName, Value: tw.com.codedata
     [INFO] Parameter: package, Value: tw.com.codedata
     [INFO] Parameter: artifactId, Value: helloworld
     [INFO] Parameter: basedir, Value: /home/linst/ws/study/maven
     [INFO] Parameter: version, Value: 1.0-SNAPSHOT
     [INFO] project created from Old (1.x) Archetype in dir: /home/linst/ws/study/maven/helloworld
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 1:46.068s
     [INFO] Finished at: Mon Sep 29 18:06:53 CST 2014
     [INFO] Final Memory: 10M/239M
     [INFO] ------------------------------------------------------------------------
    
    $ tree .
    .
    └── helloworld
        ├── pom.xml
        └── src
            ├── main
            │   └── java
            │       └── tw
            │           └── com
            │               └── codedata
            │                   └── App.java
            └── test
                └── java
                    └── tw
                        └── com
                            └── codedata
                                └── AppTest.java
    
    12 directories, 3 files
    
     
     
       4.0.0
       tw.com.codedata
       helloworld
       jar
       1.0-SNAPSHOT
       helloworld
       http://maven.apache.org
       
         
           junit
           junit
           3.8.1
           test
         
       
     
    
  2. Create file ./helloworld/src/main/resources/log4j.properties:
     $ cd helloworld/src/main/
     $ mkdir resources
     $ vim resources/log4j.properties
    
     # Set root logger level to DEBUG and have appenders A1, A2.
     log4j.rootLogger=DEBUG, A1, A2
      
     # A1 is set to be a ConsoleAppender
     log4j.appender.A1=org.apache.log4j.ConsoleAppender
     log4j.appender.A1.layout=org.apache.log4j.PatternLayout
     log4j.appender.A1.layout.ConversionPattern=[%d{yyyy/MM/dd HH:mm:ss,SSS}][%p][%C-%L] %m%n
      
     # A2 is set to be a DailyRollingFileAppender to path "./log/Log4j.log"
     log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
     log4j.appender.A2.layout=org.apache.log4j.PatternLayout
     log4j.appender.A2.layout.ConversionPattern=[%d{yyyy/MM/dd HH:mm:ss,SSS}][%p][%C-%L] %m%n
     log4j.appender.A2.File=./log/Log4j.log
    
  3. Update ./helloworld/src/main/java/tw/com/codedata/App.java to HelloWorld.java with below content:
     
     package tw.com.codedata;
      
     import org.apache.commons.logging.Log;
     import org.apache.commons.logging.LogFactory;
      
     public class HelloWorld {
      
         static Log logger = LogFactory.getLog(HelloWorld.class);
      
         public static void main(String[] args) {
      logger.info("Hello World");
         }
      
     }
    
  4. Try to build, you will get errors because no required logging libraries:
     $ cd helloworld/
     $ mvn package
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building helloworld 1.0-SNAPSHOT
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] --- maven-resources-plugin:2.3:resources (default-resources) @ helloworld ---
     [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
     [INFO] Copying 1 resource
     [INFO] 
     [INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ helloworld ---
     [INFO] Compiling 1 source file to /home/linst/ws/study/maven/helloworld/target/classes
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD FAILURE
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 0.792s
     [INFO] Finished at: Mon Sep 29 18:27:38 CST 2014
     [INFO] Final Memory: 8M/239M
     [INFO] ------------------------------------------------------------------------
     [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.0.2:compile (default-compile) on project helloworld: Compilation failure: Compilation failure:
     [ERROR] /home/linst/ws/study/maven/helloworld/src/main/java/tw/com/codedata/HelloWorld.java:[3,33] package org.apache.commons.logging does not exist
     [ERROR] 
     [ERROR] /home/linst/ws/study/maven/helloworld/src/main/java/tw/com/codedata/HelloWorld.java:[4,33] package org.apache.commons.logging does not exist
     [ERROR] 
     [ERROR] /home/linst/ws/study/maven/helloworld/src/main/java/tw/com/codedata/HelloWorld.java:[8,11] cannot find symbol
     [ERROR] symbol  : class Log
     [ERROR] location: class tw.com.codedata.HelloWorld
     [ERROR] 
     [ERROR] /home/linst/ws/study/maven/helloworld/src/main/java/tw/com/codedata/HelloWorld.java:[8,24] cannot find symbol
     [ERROR] symbol  : variable LogFactory
     [ERROR] location: class tw.com.codedata.HelloWorld
     [ERROR] -> [Help 1]
     [ERROR] 
     [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
     [ERROR] Re-run Maven using the -X switch to enable full debug logging.
     [ERROR] 
     [ERROR] For more information about the errors and possible solutions, please read the following articles:
     [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
    
  5. Update pom.xml to add two dependency:
        ... 
        
          junit
          junit
          3.8.1
          test
        
        
          commons-logging
          commons-logging
          1.1.1
        
        ... 
    
  6. Build again:
     $ mvn package
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building helloworld 1.0-SNAPSHOT
     [INFO] ------------------------------------------------------------------------
     Downloading: http://nexus-ams.tomtomgroup.com:8081/nexus/content/groups/public/log4j/log4j/1.2.16/log4j-1.2.16.pom
     Downloaded: http://nexus-ams.tomtomgroup.com:8081/nexus/content/groups/public/log4j/log4j/1.2.16/log4j-1.2.16.pom (20 KB at 11.4 KB/sec)
     Downloading: http://nexus-ams.tomtomgroup.com:8081/nexus/content/groups/public/log4j/log4j/1.2.16/log4j-1.2.16.jar
     Downloaded: http://nexus-ams.tomtomgroup.com:8081/nexus/content/groups/public/log4j/log4j/1.2.16/log4j-1.2.16.jar (471 KB at 111.6 KB/sec)
     [INFO] 
     [INFO] --- maven-resources-plugin:2.3:resources (default-resources) @ helloworld ---
     [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
     [INFO] Copying 1 resource
     [INFO] 
     [INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ helloworld ---
     [INFO] Compiling 1 source file to /home/linst/ws/study/maven/helloworld/target/classes
     [INFO] 
     [INFO] --- maven-resources-plugin:2.3:testResources (default-testResources) @ helloworld ---
     [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
     [INFO] skip non existing resourceDirectory /home/linst/ws/study/maven/helloworld/src/test/resources
     [INFO] 
     [INFO] --- maven-compiler-plugin:2.0.2:testCompile (default-testCompile) @ helloworld ---
     [INFO] Compiling 1 source file to /home/linst/ws/study/maven/helloworld/target/test-classes
     [INFO] 
     [INFO] --- maven-surefire-plugin:2.10:test (default-test) @ helloworld ---
     [INFO] Surefire report directory: /home/linst/ws/study/maven/helloworld/target/surefire-reports
    
     -------------------------------------------------------
      T E S T S
     -------------------------------------------------------
     Running tw.com.codedata.AppTest
     Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.009 sec
    
     Results :
    
     Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    
     [INFO] 
     [INFO] --- maven-jar-plugin:2.2:jar (default-jar) @ helloworld ---
     [INFO] Building jar: /home/linst/ws/study/maven/helloworld/target/helloworld-1.0-SNAPSHOT.jar
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 7.618s
     [INFO] Finished at: Mon Sep 29 18:33:32 CST 2014
     [INFO] Final Memory: 13M/239M
     [INFO] ------------------------------------------------------------------------
    
    .
    ├── pom.xml
    ├── src
    │   ├── main
    │   │   ├── java
    │   │   │   └── tw
    │   │   │       └── com
    │   │   │           └── codedata
    │   │   │               ├── App.java~
    │   │   │               └── HelloWorld.java
    │   │   └── resources
    │   │       └── log4j.properties
    │   └── test
    │       └── java
    │           └── tw
    │               └── com
    │                   └── codedata
    │                       └── AppTest.java
    └── target
        ├── classes
        │   ├── log4j.properties
        │   └── tw
        │       └── com
        │           └── codedata
        │               └── HelloWorld.class
        ├── helloworld-1.0-SNAPSHOT.jar
        ├── maven-archiver
        │   └── pom.properties
        ├── surefire
        ├── surefire-reports
        │   ├── TEST-tw.com.codedata.AppTest.xml
        │   └── tw.com.codedata.AppTest.txt
        └── test-classes
            └── tw
                └── com
                    └── codedata
                        └── AppTest.class
    
    24 directories, 12 files
    
  7. Run:
     $ mvn exec:java -Dexec.mainClass="tw.com.codedata.HelloWorld"
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building helloworld 1.0-SNAPSHOT
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] --- exec-maven-plugin:1.3.2:java (default-cli) @ helloworld ---
     [WARNING] Warning: killAfter is now deprecated. Do you need it ? Please comment on MEXEC-6.
     [2014/09/29 18:38:01,362][INFO][tw.com.codedata.HelloWorld-11] Hello World
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 0.814s
     [INFO] Finished at: Mon Sep 29 18:38:01 CST 2014
     [INFO] Final Memory: 8M/239M
     [INFO] ------------------------------------------------------------------------
    
  8. Reference:
    http://www.codedata.com.tw/java/understanding-gradle-2-maven/ [Chinese]

Install Maven Integration for Eclipse


  1. Website:
    https://www.eclipse.org/m2e/
  2. Install to Eclipse:
    Goto:
    https://www.eclipse.org/m2e/download/

    Copy link:
    Latest m2e release (recommended)
    http://download.eclipse.org/technology/m2e/releases

    Eclipse -> Help -> Install New Software -> Add ->
    Name: m2eclipse
    Location: http://download.eclipse.org/technology/m2e/releases
    -> OK -> Select "Maven Integration for Eclipse" -> Next.
  3. Reference:
    http://mkn939.blogspot.tw/2013/03/eclipde-maven-plugin-m2eclipse-step-by.html [Chinese]

Apache Maven first project for "archetypeArtifactId=maven-archetype-webapp"


  1. Create webapp project:
     $ mvn \
     archetype:generate \
     -DarchetypeArtifactId=maven-archetype-webapp \
     -DinteractiveMode=false \
     -DgroupId=com.myMaven.app \
     -DartifactId=HelloJavaWeb
    
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building Maven Stub Project (No POM) 1
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>
     [INFO] 
     [INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
     [INFO] 
     [INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom ---
     [INFO] Generating project in Batch mode
     (Downloading packages...)
     [INFO] ----------------------------------------------------------------------------
     [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0
     [INFO] ----------------------------------------------------------------------------
     [INFO] Parameter: groupId, Value: com.myMaven.app
     [INFO] Parameter: packageName, Value: com.myMaven.app
     [INFO] Parameter: package, Value: com.myMaven.app
     [INFO] Parameter: artifactId, Value: HelloJavaWeb
     [INFO] Parameter: basedir, Value: /home/linst/ws/study/maven
     [INFO] Parameter: version, Value: 1.0-SNAPSHOT
     [INFO] project created from Old (1.x) Archetype in dir: /home/linst/ws/study/maven/HelloJavaWeb
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 1:31.939s
     [INFO] Finished at: Mon Sep 29 15:28:36 CST 2014
     [INFO] Final Memory: 11M/302M
     [INFO] ------------------------------------------------------------------------
    
    .
    └── HelloJavaWeb
        ├── pom.xml
        └── src
            └── main
                ├── resources
                └── webapp
                    ├── index.jsp
                    └── WEB-INF
                        └── web.xml
    
    6 directories, 3 files
    

  2. pom.xml:
     
     
       4.0.0
       com.myMaven.app
       HelloJavaWeb
       war
       1.0-SNAPSHOT
       HelloJavaWeb Maven Webapp
       http://maven.apache.org
       
         
           junit
           junit
           3.8.1
           test
         
       
       
         HelloJavaWeb
       
     
    
  3. Compile and packaging:
     $ cd HelloJavaWeb/
     $ mvn package
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building HelloJavaWeb Maven Webapp 1.0-SNAPSHOT
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] --- maven-resources-plugin:2.3:resources (default-resources) @ HelloJavaWeb ---
     [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
     [INFO] Copying 0 resource
     [INFO] 
     [INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ HelloJavaWeb ---
     [INFO] No sources to compile
     [INFO] 
     [INFO] --- maven-resources-plugin:2.3:testResources (default-testResources) @ HelloJavaWeb ---
     [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
     [INFO] skip non existing resourceDirectory /home/linst/ws/study/maven/HelloJavaWeb/src/test/resources
     [INFO] 
     [INFO] --- maven-compiler-plugin:2.0.2:testCompile (default-testCompile) @ HelloJavaWeb ---
     [INFO] No sources to compile
     [INFO] 
     [INFO] --- maven-surefire-plugin:2.10:test (default-test) @ HelloJavaWeb ---
     (Downloading packages...)
     [INFO] No tests to run.
     [INFO] Surefire report directory: /home/linst/ws/study/maven/HelloJavaWeb/target/surefire-reports
     (Downloading packages...)
    
     -------------------------------------------------------
      T E S T S
     -------------------------------------------------------
    
     Results :
    
     Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
    
     [INFO] 
     [INFO] --- maven-war-plugin:2.1.1:war (default-war) @ HelloJavaWeb ---
     [INFO] Packaging webapp
     [INFO] Assembling webapp [HelloJavaWeb] in [/home/linst/ws/study/maven/HelloJavaWeb/target/HelloJavaWeb]
     [INFO] Processing war project
     [INFO] Copying webapp resources [/home/linst/ws/study/maven/HelloJavaWeb/src/main/webapp]
     [INFO] Webapp assembled in [15 msecs]
     [INFO] Building war: /home/linst/ws/study/maven/HelloJavaWeb/target/HelloJavaWeb.war
     [INFO] WEB-INF/web.xml already added, skipping
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 10.573s
     [INFO] Finished at: Mon Sep 29 15:36:19 CST 2014
     [INFO] Final Memory: 7M/239M
     [INFO] ------------------------------------------------------------------------
    
    .
    ├── pom.xml
    ├── src
    │   └── main
    │       ├── resources
    │       └── webapp
    │           ├── index.jsp
    │           └── WEB-INF
    │               └── web.xml
    └── target
        ├── classes
        ├── HelloJavaWeb
        │   ├── index.jsp
        │   ├── META-INF
        │   └── WEB-INF
        │       ├── classes
        │       └── web.xml
        ├── HelloJavaWeb.war
        ├── maven-archiver
        │   └── pom.properties
        └── surefire
    
    13 directories, 7 files
    
  4. You can see the generated "HelloJavaWeb.war" which can be deploy to Tomcat web server.
  5. Adding jar files, ex: modify pom.xml to add mysql dependency:
     
     
       4.0.0
       com.myMaven.app
       HelloJavaWeb
       war
       1.0-SNAPSHOT
       HelloJavaWeb Maven Webapp
       http://maven.apache.org
       
         
           junit
           junit
           3.8.1
           test
         
         
           mysql
           mysql-connector-java
           5.1.24
         
       
       
         HelloJavaWeb
       
     
    
  6. Compile and packaging:
    $ mvn package
    
    .
    ├── pom.xml
    ├── src
    │   └── main
    │       ├── resources
    │       └── webapp
    │           ├── index.jsp
    │           └── WEB-INF
    │               └── web.xml
    └── target
        ├── classes
        ├── HelloJavaWeb
        │   ├── index.jsp
        │   ├── META-INF
        │   └── WEB-INF
        │       ├── classes
        │       ├── lib
        │       │   └── mysql-connector-java-5.1.24.jar
        │       └── web.xml
        ├── HelloJavaWeb.war
        ├── maven-archiver
        │   └── pom.properties
        └── surefire
    
    14 directories, 8 files
    
  7. You can see the generated "mysql-connector-java-5.1.24.jar" and it will also be packaged in "HelloJavaWeb.war".
  8. References:
    http://mkn939.blogspot.tw/2013/03/maven-hellomaven-maven-step-by-step.html [Chinese]

Sunday, September 28, 2014

Apache Maven first project for "archetypeArtifactId=maven-archetype-quickstart"


  1. Apache Maven:
    "Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information."
  2. Ubuntu install:
     
     $ sudo apt-get install maven
    
  3. Where is it and version:
     
     $ which mvn
     /usr/bin/mvn
    
     $ mvn -v
     Apache Maven 3.0.4
     Maven home: /usr/share/maven
     Java version: 1.6.0_31, vendor: Sun Microsystems Inc.
     Java home: /usr/lib/jvm/java-6-openjdk-amd64/jre
     Default locale: en_US, platform encoding: UTF-8
     OS name: "linux", version: "3.2.0-65-generic", arch: "amd64", family: "unix"
    
  4. Create first project:
     
     $ mvn \
     archetype:generate \
     -DarchetypeArtifactId=maven-archetype-quickstart \
     -DinteractiveMode=false \
     -DgroupId=com.myMaven.app \
     -DartifactId=HelloMaven
    
     [INFO] Scanning for projects...
     (Downloading packages...)
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building Maven Stub Project (No POM) 1
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>
     [INFO] 
     [INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
     [INFO] 
     [INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom ---
     (Downloading packages...)
     [INFO] Generating project in Batch mode
     (Downloading packages...)
     [INFO] ----------------------------------------------------------------------------
     [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
     [INFO] ----------------------------------------------------------------------------
     [INFO] Parameter: groupId, Value: com.myMaven.app
     [INFO] Parameter: packageName, Value: com.myMaven.app
     [INFO] Parameter: package, Value: com.myMaven.app
     [INFO] Parameter: artifactId, Value: HelloMaven
     [INFO] Parameter: basedir, Value: /home/linst/ws/study/maven
     [INFO] Parameter: version, Value: 1.0-SNAPSHOT
     [INFO] project created from Old (1.x) Archetype in dir: /home/linst/ws/study/maven/HelloMaven
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 3:05.835s
     [INFO] Finished at: Mon Sep 29 11:28:32 CST 2014
     [INFO] Final Memory: 9M/239M
     [INFO] ------------------------------------------------------------------------
    
  5. About groupId, artifactId and archetypeArtifactId:
     
     groupId: This element indicates the unique identifier of the organization or group that created the project.
     artifactId: This element indicates the unique base name of the primary artifact being generated by this project.
     archetypeArtifactId: The archetype's artifactId.
    

    http://maven.apache.org/archetype/maven-archetype-plugin/generate-mojo.html#archetypeCatalog
  6. The generated tree and files and pom.xml:
     
     .
     └── HelloMaven
         ├── pom.xml
         └── src
             ├── main
             │   └── java
             │       └── com
             │           └── myMaven
             │               └── app
             │                   └── App.java
             └── test
                 └── java
                     └── com
                         └── myMaven
                             └── app
                                 └── AppTest.java
    
     12 directories, 3 files
    
     
     
       4.0.0
       com.myMaven.app
       HelloMaven
       jar
       1.0-SNAPSHOT
       HelloMaven
       http://maven.apache.org
       
         
           junit
           junit
           3.8.1
           test
         
       
     
    
  7. Compile:
     
     $ cd HelloMaven/
     $ mvn compile
     [INFO] Scanning for projects...
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building HelloMaven 1.0-SNAPSHOT
     [INFO] ------------------------------------------------------------------------
     (Downloading packages...)
     [INFO] 
     [INFO] --- maven-resources-plugin:2.3:resources (default-resources) @ HelloMaven ---
     [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
     [INFO] skip non existing resourceDirectory /home/linst/ws/study/maven/HelloMaven/src/main/resources
     [INFO] 
     [INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ HelloMaven ---
     (Downloading packages...)
     [INFO] Compiling 1 source file to /home/linst/ws/study/maven/HelloMaven/target/classes
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 13.615s
     [INFO] Finished at: Mon Sep 29 15:02:17 CST 2014
     [INFO] Final Memory: 8M/239M
     [INFO] ------------------------------------------------------------------------
    
    .
    ├── pom.xml
    ├── src
    │   ├── main
    │   │   └── java
    │   │       └── com
    │   │           └── myMaven
    │   │               └── app
    │   │                   └── App.java
    │   └── test
    │       └── java
    │           └── com
    │               └── myMaven
    │                   └── app
    │                       └── AppTest.java
    └── target
        └── classes
            └── com
                └── myMaven
                    └── app
                        └── App.class
    
    16 directories, 4 files
    
  8. Run:
     
     $ mvn exec:java -Dexec.mainClass=com.myMaven.app.App
     [INFO] Scanning for projects...
     (Downloading packages...)
     [INFO]                                                                         
     [INFO] ------------------------------------------------------------------------
     [INFO] Building HelloMaven 1.0-SNAPSHOT
     [INFO] ------------------------------------------------------------------------
     [INFO] 
     [INFO] --- exec-maven-plugin:1.3.2:java (default-cli) @ HelloMaven ---
     (Downloading packages...)
     [WARNING] Warning: killAfter is now deprecated. Do you need it ? Please comment on MEXEC-6.
     Hello World!@@!
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESS
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 50.464s
     [INFO] Finished at: Mon Sep 29 15:15:47 CST 2014
     [INFO] Final Memory: 7M/239M
     [INFO] ------------------------------------------------------------------------
    
  9. References:
    http://maven.apache.org/index.html
    http://maven.apache.org/guides/getting-started/index.html
    http://maven.apache.org/pom.html
    http://www.codedata.com.tw/java/understanding-gradle-2-maven/ [Chinese]
    http://mkn939.blogspot.tw/2013/03/maven-hellomaven-maven-step-by-step.html [Chinese]