Monday, 4 February 2013

Hacking on JRuby on Rails




With RVM installed,
STEP 0 Check rvm is installed
prayag@Prayag:~/workspace_rails$ rvm --version

rvm 1.18.2 (stable) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]


STEP 1 Install jruby 1.7.2
prayag@Prayag:~$ rvm install jruby
Searching for binary rubies, this might take some time.
jruby-1.7.2 - #configure
jruby-1.7.2 - #download
######################################################################## 100.0%
jruby-1.7.2 - #validate archive
jruby-1.7.2 - #extract
jruby-1.7.2 - #validate binary
jruby-1.7.2 - #setup
mkdir: cannot create directory `': No such file or directory
mkdir: cannot create directory `': No such file or directory
Saving wrappers to '/home/prayag/.rvm/bin'.
jruby-1.7.2 - #importing default gemsets, this may take time ...


Check in .rvm/bin
prayag@Prayag:~/workspace_rails$ ls -l /home/prayag/.rvm/bin/
total 76
-rwxrwxr-x 1 prayag prayag   578 Jan 25 11:20 bundle
lrwxrwxrwx 1 prayag prayag    42 Jan 25 11:54 default_gem -> /home/prayag/.rvm/wrappers/jruby-1.7.2/gem
lrwxrwxrwx 1 prayag prayag    42 Jan 25 11:54 default_irb -> /home/prayag/.rvm/wrappers/jruby-1.7.2/irb
lrwxrwxrwx 1 prayag prayag    43 Jan 25 11:54 default_rake -> /home/prayag/.rvm/wrappers/jruby-1.7.2/rake
lrwxrwxrwx 1 prayag prayag    43 Jan 25 11:54 default_rdoc -> /home/prayag/.rvm/wrappers/jruby-1.7.2/rdoc
lrwxrwxrwx 1 prayag prayag    41 Jan 25 11:54 default_ri -> /home/prayag/.rvm/wrappers/jruby-1.7.2/ri
lrwxrwxrwx 1 prayag prayag    43 Jan 25 11:54 default_ruby -> /home/prayag/.rvm/wrappers/jruby-1.7.2/ruby
lrwxrwxrwx 1 prayag prayag    45 Jan 25 11:54 default_testrb -> /home/prayag/.rvm/wrappers/jruby-1.7.2/testrb
-rwxrwxr-x 1 prayag prayag   265 Jan 25 11:54 erb
lrwxrwxrwx 1 prayag prayag    42 Jan 25 11:52 erb-jruby-1.7.2 -> /home/prayag/.rvm/wrappers/jruby-1.7.2/erb
lrwxrwxrwx 1 prayag prayag    49 Jan 25 11:52 erb-jruby-1.7.2@global -> /home/prayag/.rvm/wrappers/jruby-1.7.2@global/erb
-rwxrwxr-x 1 prayag prayag   265 Jan 25 11:54 gem
lrwxrwxrwx 1 prayag prayag    42 Jan 25 11:52 gem-jruby-1.7.2 -> /home/prayag/.rvm/wrappers/jruby-1.7.2/gem
lrwxrwxrwx 1 prayag prayag    49 Jan 25 11:52 gem-jruby-1.7.2@global -> /home/prayag/.rvm/wrappers/jruby-1.7.2@global/gem
-rwxrwxr-x 1 prayag prayag   265 Jan 25 11:54 irb
lrwxrwxrwx 1 prayag prayag    42 Jan 25 11:52 irb-jruby-1.7.2 -> /home/prayag/.rvm/wrappers/jruby-1.7.2/irb
lrwxrwxrwx 1 prayag prayag    49 Jan 25 11:52 irb-jruby-1.7.2@global -> /home/prayag/.rvm/wrappers/jruby-1.7.2@global/irb
lrwxrwxrwx 1 prayag prayag    43 Jan 25 11:52 jruby-1.7.2 -> /home/prayag/.rvm/wrappers/jruby-1.7.2/ruby
lrwxrwxrwx 1 prayag prayag    50 Jan 25 11:52 jruby-1.7.2@global -> /home/prayag/.rvm/wrappers/jruby-1.7.2@global/ruby
-rwxrwxr-x 1 prayag prayag   266 Jan 25 11:54 rake
lrwxrwxrwx 1 prayag prayag    43 Jan 25 11:52 rake-jruby-1.7.2 -> /home/prayag/.rvm/wrappers/jruby-1.7.2/rake
lrwxrwxrwx 1 prayag prayag    50 Jan 25 11:52 rake-jruby-1.7.2@global -> /home/prayag/.rvm/wrappers/jruby-1.7.2@global/rake
-rwxrwxr-x 1 prayag prayag   266 Jan 25 11:54 rdoc
lrwxrwxrwx 1 prayag prayag    43 Jan 25 11:52 rdoc-jruby-1.7.2 -> /home/prayag/.rvm/wrappers/jruby-1.7.2/rdoc
lrwxrwxrwx 1 prayag prayag    50 Jan 25 11:52 rdoc-jruby-1.7.2@global -> /home/prayag/.rvm/wrappers/jruby-1.7.2@global/rdoc
-rwxrwxr-x 1 prayag prayag   264 Jan 25 11:54 ri
lrwxrwxrwx 1 prayag prayag    41 Jan 25 11:52 ri-jruby-1.7.2 -> /home/prayag/.rvm/wrappers/jruby-1.7.2/ri
lrwxrwxrwx 1 prayag prayag    48 Jan 25 11:52 ri-jruby-1.7.2@global -> /home/prayag/.rvm/wrappers/jruby-1.7.2@global/ri
-rwxrwxr-x 1 prayag prayag   266 Jan 25 11:54 ruby
-rwxrwxr-x 1 prayag prayag  1272 Jan 25 11:20 rvm
-rwxrwxr-x 1 prayag prayag  1512 Jan 25 11:20 rvm-auto-ruby
-rwxrwxr-x 1 prayag prayag  1803 Jan 25 11:20 rvm-exec
-rwxrwxr-x 1 prayag prayag 10648 Jan 25 11:20 rvm-installer
-rwxrwxr-x 1 prayag prayag  3816 Jan 25 11:20 rvm-prompt
-rwxrwxr-x 1 prayag prayag  2263 Jan 25 11:20 rvm-shell
-rwxrwxr-x 1 prayag prayag   648 Jan 25 11:20 rvm-smile
-rwxrwxr-x 1 prayag prayag  2228 Jan 25 11:20 rvmsudo
-rwxrwxr-x 1 prayag prayag   268 Jan 25 11:54 testrb
lrwxrwxrwx 1 prayag prayag    45 Jan 25 11:52 testrb-jruby-1.7.2 -> /home/prayag/.rvm/wrappers/jruby-1.7.2/testrb
lrwxrwxrwx 1 prayag prayag    52 Jan 25 11:52 testrb-jruby-1.7.2@global -> /home/prayag/.rvm/wrappers/jruby-1.7.2@global/testrb


Check jruby version
prayag@Prayag:~$ jruby --version
jruby 1.7.2 (1.9.3p327) 2013-01-04 302c706 on Java HotSpot(TM) Client VM 1.6.0_23-b05 [linux-i386]


STEP 2 List Local gem
-S parameter tells JRuby to use its version of the installed binary.
prayag@Prayag:~/workspace_rails$ jruby -S gem list --local

*** LOCAL GEMS ***


bouncy-castle-java (1.5.0146.1)

bundler (1.2.3)
jruby-openssl (0.8.2)
rake (10.0.3)
rubygems-bundler (1.1.0)
rvm (1.11.3.6)


gem install rails
prayag@Prayag:~/workspace_rails$ jruby -S gem install rails mongrel jdbc-mysql activerecord-jdbcmysql-adapter
Fetching: railties-3.2.11.gem (100%)
Fetching: rails-3.2.11.gem (100%)
Successfully installed railties-3.2.11
Successfully installed rails-3.2.11
Fetching: gem_plugin-0.2.3.gem (100%)
Fetching: mongrel-1.1.5-java.gem (100%)
Successfully installed gem_plugin-0.2.3
Successfully installed mongrel-1.1.5-java
Fetching: jdbc-mysql-5.1.22.1.gem (100%)
Successfully installed jdbc-mysql-5.1.22.1
Fetching: activerecord-jdbc-adapter-1.2.5.gem (100%)
Fetching: activerecord-jdbcmysql-adapter-1.2.5.gem (100%)
Successfully installed activerecord-jdbc-adapter-1.2.5
Successfully installed activerecord-jdbcmysql-adapter-1.2.5
7 gems installed


STEP 3 create a rails app
prayag@Prayag:~/workspace_rails$ jruby -S rails new justice-for-gyanendra
      create
      create  README.rdoc
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/images/rails.png
      create  app/assets/javascripts/application.js
      create  app/assets/stylesheets/application.css
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/views/layouts/application.html.erb
      create  app/mailers/.gitkeep
      create  app/models/.gitkeep
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  lib/assets
      create  lib/assets/.gitkeep
      create  log
      create  log/.gitkeep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  script
      create  script/rails
      create  test/fixtures
      create  test/fixtures/.gitkeep
      create  test/functional
      create  test/functional/.gitkeep
      create  test/integration
      create  test/integration/.gitkeep
      create  test/unit
      create  test/unit/.gitkeep
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor/assets/javascripts
      create  vendor/assets/javascripts/.gitkeep
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.gitkeep
      create  vendor/plugins
      create  vendor/plugins/.gitkeep
         run  bundle install
Fetching gem metadata from https://rubygems.org/.
Error Bundler::HTTPError during request to dependency API
Fetching full source index from https://rubygems.org/
Using rake (10.0.3)
Using i18n (0.6.1)
Using multi_json (1.5.0)
Using activesupport (3.2.11)
Using builder (3.0.4)
Using activemodel (3.2.11)
Using erubis (2.7.0)
Using journey (1.0.4)
Using rack (1.4.4)
Using rack-cache (1.2)
Using rack-test (0.6.2)
Using hike (1.2.1)
Using tilt (1.3.3)
Using sprockets (2.2.2)
Using actionpack (3.2.11)
Installing mime-types (1.20.1)
Using polyglot (0.3.3)
Using treetop (1.4.12)
Using mail (2.4.4)
Using actionmailer (3.2.11)
Using arel (3.0.2)
Using tzinfo (0.3.35)
Using activerecord (3.2.11)
Installing activerecord-jdbc-adapter (1.2.6)
Installing jdbc-sqlite3 (3.7.2.1)
Installing activerecord-jdbcsqlite3-adapter (1.2.6)
Using activeresource (3.2.11)
Using bouncy-castle-java (1.5.0146.1)
Using bundler (1.2.3)
Installing coffee-script-source (1.4.0)
Installing execjs (1.4.0)
Installing coffee-script (2.2.0)
Installing rack-ssl (1.3.3)
Using json (1.7.6)
Using rdoc (3.12)
Using thor (0.17.0)
Using railties (3.2.11)
Installing coffee-rails (3.2.2)
Installing jquery-rails (2.2.0)
Using jruby-openssl (0.8.2)
Using rails (3.2.11)
Installing sass (3.2.5)
Installing sass-rails (3.2.6)
Installing therubyrhino_jar (1.7.4)
Installing therubyrhino (2.0.2)
Installing uglifier (1.3.0)
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.


STEP 4 build a rails app
Rake is a build tool, written in Ruby, using Ruby as a build language.

prayag@Prayag:~/workspace_rails/justice-for-gyanendra$ jruby -S rake -T
rake about              # List versions of all Rails frameworks and the env...
rake assets:clean       # Remove compiled assets
rake assets:precompile  # Compile all the assets named in config.assets.pre...
rake db:create          # Create the database from DATABASE_URL or config/d...
rake db:drop            # Drops the database using DATABASE_URL or the curr...
rake db:fixtures:load   # Load fixtures into the current environment's data...
rake db:migrate         # Migrate the database (options: VERSION=x, VERBOSE...
rake db:migrate:status  # Display status of migrations
rake db:rollback        # Rolls the schema back to the previous version (sp...
rake db:schema:dump     # Create a db/schema.rb file that can be portably u...
rake db:schema:load     # Load a schema.rb file into the database
rake db:seed            # Load the seed data from db/seeds.rb
rake db:setup           # Create the database, load the schema, and initial...
rake db:structure:dump  # Dump the database structure to db/structure.sql. ...
rake db:version         # Retrieves the current schema version number
rake doc:app            # Generate docs for the app -- also available doc:r...
rake log:clear          # Truncates all *.log files in log/ to zero bytes
rake middleware         # Prints out your Rack middleware stack
rake notes              # Enumerate all annotations (use notes:optimize, :f...
rake notes:custom       # Enumerate a custom annotation, specify with ANNOT...
rake rails:template     # Applies the template supplied by LOCATION=(/path/...
rake rails:update       # Update configs and some other initially generated...
rake routes             # Print out all defined routes in match order, with...
rake secret             # Generate a cryptographically secure secret key (t...
rake stats              # Report code statistics (KLOCs, etc) from the appl...
rake test               # Runs test:units, test:functionals, test:integrati...
rake test:recent        # Run tests for {:recent=>"test:prepare"} / Test re...
rake test:single        # Run tests for {:single=>"test:prepare"}
rake test:uncommitted   # Run tests for {:uncommitted=>"test:prepare"} / Te...
rake time:zones:all     # Displays all time zones, also available: time:zon...
rake tmp:clear          # Clear session, cache, and socket files from tmp/ ...
rake tmp:create         # Creates tmp directories for sessions, cache, sock...


Saturday, 2 February 2013

Accessing ftp server from Linux

STEP 1 Connect to server
prayag@Prayag:~$ ftp
ftp> open
(to) 202.166.195.70
Connected to 202.166.195.70.
220-Welcome to Islington Uni File Server
220-Created by Islington IT Team    
220---------------!!!!!!!WARNING!!!!!!! -------------------
220-*******UNAUTHORIZED ACCESS TO THIS SYSTEM IS
220 STRICTLY PROHIBITED*******
Name (202.166.195.70:prayag): s*****t
331 User s*****t, password please
Password:
230 Password Ok, User logged in
Remote system type is UNIX.
Using binary mode to transfer files.

GUI tool for ftp connection where one just need to feed host, username, password and port, may look like the following one.



STEP 2 Check status
ftp> status
Connected to 202.166.195.70.
No proxy connection.
Connecting using address family: any.
Mode: stream; Type: binary; Form: non-print; Structure: file
Verbose: on; Bell: off; Prompting: on; Globbing: on
Store unique: off; Receive unique: off
Case: off; CR stripping: on
Quote control characters: on
Ntrans: off
Nmap: off
Hash mark printing: off; Use of PORT cmds: on
Tick counter printing: off


STEP 3 show files
ftp> ls 
200 Port command received
150 Opening data connection
drw-rw-rw-   1 user     group           0 Dec 16 03:58 MSC_COMPUTER NETWORKING & IT SECURITY
drw-rw-rw-   1 user     group           0 Dec 27 07:23 MSC_COMPUTING
drw-rw-rw-   1 user     group           0 Nov 05 03:26 MSC_MULTIMEDIA TECHNOLOGIES
drw-rw-rw-   1 user     group           0 Dec 18 04:07 EXTENDED PROGRAMME
drw-rw-rw-   1 user     group           0 Nov 01 03:18 SOFTWARES
drw-rw-rw-   1 user     group           0 Nov 04  2011 TimeTable-LondonMetSepSem
drw-rw-rw-   1 user     group           0 Nov 18 05:23 MBA EXTENDED PROGRAMME
drw-rw-rw-   1 user     group           0 Aug 29 06:16 FIRST_YEAR_INDUSTRIAL_PROJECT
226 Transfer complete


STEP 4 Download a directory
ftp> cd MSC_COMPUTING
ftp> mget  *

Wednesday, 23 January 2013

SVN Daily on Linux

[1] adding files to svn:ignore

prayag@Prayag:~/workspace_java/sbtc$ svn propedit svn:ignore .





[F3] to save
[Ctrl+X] to quit
Set new value for property 'svn:ignore' on '.'

[2] list all ignored patterns

prayag@Prayag:~/workspace_java/sbtc$ svn propget svn:ignore
target
c:
ctbs
catalina.base_IS_UNDEFINED

OR
prayag@Prayag:~/workspace_java/sbtc$ svn pg -R svn:ignore .
. - target
c:
ctbs
catalina.base_IS_UNDEFINED



[3] display the unversioned files
prayag@Prayag:~/workspace_java/sbtc$ svn status | grep -e ^?
OR
prayag@Prayag:~/workspace_java/sbtc$ svn status | grep "^?"


[4] recent log entries

prayag@Prayag:~/workspace_java/sbtc$ svn log -r {2012-12-26}:{2013-01-23}
Authentication realm: <http://10.13.212.254:80> Subversion Repositories
Password for 'pupd':

-----------------------------------------------------------------------
ATTENTION!  Your password for authentication realm:

   <http://10.13.212.24:80> Subversion Repositories

can only be stored to disk unencrypted!  You are advised to configure
your system so that Subversion can store passwords encrypted, if
possible.  See the documentation for details.

You can avoid future appearances of this warning by setting the value
of the 'store-plaintext-passwords' option to either 'yes' or 'no' in
'/home/prayag/.subversion/servers'.
-----------------------------------------------------------------------
Store password unencrypted (yes/no)? no
------------------------------------------------------------------------
r40557 | pupd | 2012-12-26 15:06:54 +0545 (Wed, 26 Dec 2012) | 1 line

UPDATE ETransaction to RemitDetails and UPDATE UI
------------------------------------------------------------------------

OR
prayag@Prayag:~/workspace_java/central-tb-system$ svn log --limit 3


[5] comparing diff between incoming changes

prayag@Prayag:~/workspace_java/sbtc$ svn diff -r BASE:HEAD

Index: src/main/resources/WEB-INF/resourcebundle/message.properties

===================================================================
--- src/main/resources/WEB-INF/resourcebundle/message.properties (working copy)
+++ src/main/resources/WEB-INF/resourcebundle/message.properties (revision 42213)
@@ -5,9 +5,8 @@
 serviceNotSupported=Service {0} is not supported.
 currencyNotSupported=Currency {0} is not supported.
 requestAcknowleged=Request Acknowledged.
+amount.isless=Amount less than minimum limit
+amount.isgreater=Amount more than minimum limit
 invalidServiceInfo=Invalid Service Info ID {0}.
 internalError=Internal Error
 invalidAmount=Amount is missing




Wednesday, 16 January 2013

RAM usage in Linux

1 . using command top
prayag@Prayag:~$ top | grep java
 PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND
 4216 prayag    20   0  429m 139m 8808 S   1.0  7.9   1:04.51 java                                                                                     
 4216 prayag    20   0  429m 139m 8808 S   0.3  7.9   1:04.52 java                                                                                     
 4216 prayag    20   0  429m 139m 8808 S   0.7  7.9   1:04.54 java                                                                                     
 4216 prayag    20   0  429m 139m 8808 S   0.3  7.9   1:04.55 java                                                                                     
 4216 prayag    20   0  429m 139m 8808 S   0.7  7.9   1:04.57 java

 6035 prayag    20   0  406m 107m 7812 S   1.0  6.1   1:02.63 java                                                                                    
 7249 prayag    20   0  857m 223m 7436 S   0.3 12.8   0:28.04 java                                                                                    
 7249 prayag    20   0  857m 223m 7436 S   0.3 12.8   0:28.05 java

#type h for help, q to quit

RES   = RESident Size (how much of your program is in actual, physical RAM.)
VIRT = VIRTual Memory Footprint (how much virtual memory, RAM + Swap, your program has allocated).
In my case, Java eats 429 MB - 857 MB.

2. free --help
prayag@Prayag:~$ free --mega
             total       used       free     shared    buffers     cached
Mem:          1754       1563        190          0          8        301
-/+ buffers/cache:       1253        500
Swap:         2859        867       1992


3. vmstat --help
prayag@Prayag:~$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 1  0 887604 192400   8996 310300   77  111   311   181  211 1096  8  2 82  8


References
Tomcat VIRT memory usage. 2012. http://serverfault.com/a/296721/113713

Why (on Linux) am I seeing so much RAM usage?. 2013.
http://www.chrisjohnston.org/ubuntu/why-on-linux-am-i-seeing-so-much-ram-usage


Monday, 14 January 2013

clojure REST API 101

Compojure by James Reeves(a British developer) is a small routing library for Ring that allows web applications to be composed of small, independent parts. (Compojure Github, 2012)

Ring is a Clojure web applications library inspired by Python's WSGI and Ruby's Rack.

                                                                    Fig. a Rack app

Why Compojure?
The language I work with from day to day is Ruby, so Compojure has a  lot in common with lightweight Ruby frameworks like Sinatra, and less  with existing Java frameworks. It's designed for impatient, lazy  people like myself, so it's quick to install and quick to start  developing in.

- @James Reeves (on Google Group)



After installing lein, the following are the steps to get started with Clojure on Compojure :

STEP 1 install lein-newnew 0.2.6 and compojure/lein-template 0.2.0 

prayag@Prayag:~$ lein plugin install lein-newnew 0.2.6
[INFO] Unable to find resource 'lein-newnew:lein-newnew:jar:0.2.6' in repository central (http://repo1.maven.org/maven2)
Downloading: stencil/stencil/0.2.0/stencil-0.2.0.pom from repository central at http://repo1.maven.org/maven2
Unable to locate resource in repository
[INFO] Unable to find resource 'stencil:stencil:pom:0.2.0' in repository central (http://repo1.maven.org/maven2)
Downloading: stencil/stencil/0.2.0/stencil-0.2.0.pom from repository clojars at http://clojars.org/repo/
Transferring 2K from clojars
Downloading: org/clojure/clojure/1.3.0/clojure-1.3.0.pom from repository clojars at http://clojars.org/repo/
Transferring 5K from clojars
Downloading: slingshot/slingshot/0.8.0/slingshot-0.8.0.pom from repository clojars at http://clojars.org/repo/
Transferring 1K from clojars
Downloading: org/clojure/clojure/1.2.1/clojure-1.2.1.pom from repository clojars at http://clojars.org/repo/
Transferring 1K from clojars
Downloading: bultitude/bultitude/0.1.5/bultitude-0.1.5.pom from repository central at http://repo1.maven.org/maven2
Unable to locate resource in repository
[INFO] Unable to find resource 'bultitude:bultitude:pom:0.1.5' in repository central (http://repo1.maven.org/maven2)
Downloading: bultitude/bultitude/0.1.5/bultitude-0.1.5.pom from repository clojars at http://clojars.org/repo/
Transferring 2K from clojars
Downloading: slingshot/slingshot/0.8.0/slingshot-0.8.0.jar from repository clojars at http://clojars.org/repo/
Downloading: bultitude/bultitude/0.1.5/bultitude-0.1.5.jar from repository central at http://repo1.maven.org/maven2
Downloading: stencil/stencil/0.2.0/stencil-0.2.0.jar from repository central at http://repo1.maven.org/maven2
Downloading: org/clojure/clojure/1.3.0/clojure-1.3.0.jar from repository clojars at http://clojars.org/repo/
Transferring 6K from clojars
Unable to locate resource in repository
[INFO] Unable to find resource 'bultitude:bultitude:jar:0.1.5' in repository central (http://repo1.maven.org/maven2)
Downloading: bultitude/bultitude/0.1.5/bultitude-0.1.5.jar from repository clojars at http://clojars.org/repo/
Unable to locate resource in repository
[INFO] Unable to find resource 'stencil:stencil:jar:0.2.0' in repository central (http://repo1.maven.org/maven2)
Downloading: stencil/stencil/0.2.0/stencil-0.2.0.jar from repository clojars at http://clojars.org/repo/
Transferring 3K from clojars
Transferring 16K from clojars
Transferring 3311K from clojars
Copying 3 files to /tmp/lein-6b1bc0ca-676e-4487-810f-c017583b8a43/lib
Including lein-newnew-0.2.6.jar
Including stencil-0.2.0.jar
Including bultitude-0.1.5.jar
Including slingshot-0.8.0.jar
Created lein-newnew-0.2.6.jar


prayag@Prayag:~$ lein plugin install compojure/lein-template 0.2.0
[INFO] Unable to find resource 'compojure:lein-template:jar:0.2.0' in repository central (http://repo1.maven.org/maven2)
Downloading: leinjacker/leinjacker/0.2.0/leinjacker-0.2.0.pom from repository central at http://repo1.maven.org/maven2
Unable to locate resource in repository
[INFO] Unable to find resource 'leinjacker:leinjacker:pom:0.2.0' in repository central (http://repo1.maven.org/maven2)
Downloading: leinjacker/leinjacker/0.2.0/leinjacker-0.2.0.pom from repository clojars at http://clojars.org/repo/
Transferring 3K from clojars
Downloading: trammel/trammel/0.7.0/trammel-0.7.0.pom from repository clojars at http://clojars.org/repo/
Transferring 2K from clojars
[INFO] snapshot thneed:thneed:1.0.0-SNAPSHOT: checking for updates from clojars
[INFO] snapshot thneed:thneed:1.0.0-SNAPSHOT: checking for updates from central
Downloading: thneed/thneed/1.0.0-SNAPSHOT/thneed-1.0.0-20120330.013054-1.pom from repository clojars at http://clojars.org/repo/
Transferring 1K from clojars
Downloading: leinjacker/leinjacker/0.2.0/leinjacker-0.2.0.jar from repository central at http://repo1.maven.org/maven2
Downloading: thneed/thneed/1.0.0-SNAPSHOT/thneed-1.0.0-20120330.013054-1.jar from repository clojars at http://clojars.org/repo/
Downloading: trammel/trammel/0.7.0/trammel-0.7.0.jar from repository clojars at http://clojars.org/repo/
Transferring 6K from clojars
Unable to locate resource in repository
[INFO] Unable to find resource 'leinjacker:leinjacker:jar:0.2.0' in repository central (http://repo1.maven.org/maven2)
Downloading: leinjacker/leinjacker/0.2.0/leinjacker-0.2.0.jar from repository clojars at http://clojars.org/repo/
Transferring 9K from clojars
Transferring 5K from clojars
Copying 3 files to /tmp/lein-77d9ecd7-c721-46ab-8760-5a5c9c2803df/lib
Including lein-template-0.2.0.jar
Including thneed-1.0.0-20120330.013054-1.jar
Including trammel-0.7.0.jar
Including leinjacker-0.2.0.jar
Created compojure-lein-template-0.2.0.jar


STEP 2 create a new project using the "compojure" template

prayag@Prayag:~$ sudo chmod 777 workspace_erujopmoc/
prayag@Prayag:~$ cd workspace_erujopmoc/
prayag@Prayag:~/workspace_erujopmoc$ lein new compojure hotel


STEP 3 Make sure project is created

prayag@Prayag:~/workspace_erujopmoc/hotel$ ls -la
total 44
drwxrwxr-x 7 prayag prayag 4096 Jan 14 18:09 .
drwxrwxrwx 3 root   root   4096 Jan 14 18:01 ..
drwxrwxr-x 2 prayag prayag 4096 Jan 14 18:09 classes
-rw-rw-r-- 1 prayag prayag  109 Jan 14 18:01 .gitignore
-rw-rw-r-- 1 prayag prayag   40 Jan 14 18:09 .lein-deps-sum
drwxrwxr-x 2 prayag prayag 4096 Jan 14 18:07 .lein-plugins
drwxrwxr-x 3 prayag prayag 4096 Jan 14 18:09 lib
-rw-rw-r-- 1 prayag prayag  309 Jan 14 18:01 project.clj
-rw-rw-r-- 1 prayag prayag  256 Jan 14 18:01 README.md
drwxrwxr-x 3 prayag prayag 4096 Jan 14 18:01 src
drwxrwxr-x 3 prayag prayag 4096 Jan 14 18:01 test


3.A) The dependencies are : 

(defproject hotel "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :dependencies [[org.clojure/clojure "1.4.0"]
                 [compojure "1.1.1"]]
  :plugins [[lein-ring "0.7.1"]]
  :ring {:handler hotel.handler/app}
  :dev-dependencies [[ring-mock "0.1.2"]])


3.B) The structure of main is : 

prayag@Prayag:~/workspace_erujopmoc/hotel$ ls -l src/hotel/
total 4
-rw-rw-r-- 1 prayag prayag 252 Jan 14 18:01 handler.clj

The src/hotel/handler.clj reads as follws :

(ns hotel.handler
  (:use compojure.core)
  (:require [compojure.handler :as handler]
            [compojure.route :as route]))

(defroutes app-routes
  (GET "/" [] "Hello World")
  (route/not-found "Not Found"))

(def app
  (handler/site app-routes))

Change (defroutes) to the following

(defroutes app-routes
  (GET "/" [] "Welcome To Rich Hickey Hotel")
  (route/not-found "Not Found"))


STEP 4 start a development server using Leiningen

prayag@Prayag:~/workspace_erujopmoc/hotel$ lein ring server
Downloading: lein-ring/lein-ring/0.7.1/lein-ring-0.7.1.pom from repository central at http://repo1.maven.org/maven2
Unable to locate resource in repository
[INFO] Unable to find resource 'lein-ring:lein-ring:pom:0.7.1' in repository central (http://repo1.maven.org/maven2)
Downloading: lein-ring/lein-ring/0.7.1/lein-ring-0.7.1.pom from repository clojars at http://clojars.org/repo/
Transferring 2K from clojars
Downloading: org/clojure/data.xml/0.0.3/data.xml-0.0.3.pom from repository clojars at http://clojars.org/repo/
Unable to locate resource in repository
[INFO] Unable to find resource 'org.clojure:data.xml:pom:0.0.3' in repository clojars (http://clojars.org/repo/)
Downloading: org/clojure/data.xml/0.0.3/data.xml-0.0.3.pom from repository central at http://repo1.maven.org/maven2
Transferring 1K from central
Downloading: org/clojure/pom.contrib/0.0.25/pom.contrib-0.0.25.pom from repository sonatype-oss-snapshots at https://oss.sonatype.org/content/repositories/snapshots
Unable to locate resource in repository
[INFO] Unable to find resource 'org.clojure:pom.contrib:pom:0.0.25' in repository sonatype-oss-snapshots (https://oss.sonatype.org/content/repositories/snapshots)
Downloading: org/clojure/pom.contrib/0.0.25/pom.contrib-0.0.25.pom from repository clojars at http://clojars.org/repo/
Unable to locate resource in repository
[INFO] Unable to find resource 'org.clojure:pom.contrib:pom:0.0.25' in repository clojars (http://clojars.org/repo/)
Downloading: org/clojure/pom.contrib/0.0.25/pom.contrib-0.0.25.pom from repository central at http://repo1.maven.org/maven2
Transferring 5K from central
Downloading: org/clojure/data.xml/0.0.3/data.xml-0.0.3.jar from repository clojars at http://clojars.org/repo/
Downloading: lein-ring/lein-ring/0.7.1/lein-ring-0.7.1.jar from repository central at http://repo1.maven.org/maven2
Unable to locate resource in repository
[INFO] Unable to find resource 'lein-ring:lein-ring:jar:0.7.1' in repository central (http://repo1.maven.org/maven2)
Downloading: lein-ring/lein-ring/0.7.1/lein-ring-0.7.1.jar from repository clojars at http://clojars.org/repo/
[...]
Copying 1 file to /home/prayag/workspace_erujopmoc/hotel/lib/dev
2013-01-14 18:09:24.142:INFO:oejs.Server:jetty-7.6.1.v20120215
Started server on port 3000
2013-01-14 18:09:24.218:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:3000


STEP 5 Hit http://localhost:3000/ and scream 

 Welcome To Rich Hickey Hotel



More On Compojure
[1] What's the “big idea” behind compojure routes?, http://stackoverflow.com/a/3490479/432903
https://docs.google.com/document/edit?id=1kKxwuPW0bkzxmbOvyMyJxfZNp71aMz4FifcVZclpTQY

[2] Is Clojure just "a Lisp syntax on the JVM"? Or is it more than that?, http://qr.ae/Ifo36

References
[1] Getting Started, https://github.com/weavejester/compojure/wiki/Getting-Started

[2] Installing Compojure from a clean Ubuntu, http://sharetheconversation.blogspot.com/2010/05/installing-compojure.html

[3] Using Leiningen to build Clojure code, http://alexott.net/en/clojure/ClojureLein.html#sec2

[4] Compojure Demystified with an example,
http://techbehindtech.com/2010/08/24/compojure-demystified-with-an-example-part-4/

Wednesday, 9 January 2013

clojure and lein REPL 101

I'm interested in clojure a bit because of its functional approach borrowed from LISP. Its a constant learning obviously. Im writing about basic 101 stuffs here.

 clojure has a build tool leiningen is a that helps bootstrapping.

It installs its dependencies upon the first run on unix, so the first run will take longer.

STEP 1 : download lein and add to path
$ wget https://raw.github.com/technomancy/leiningen/stable/bin/lein > /usr/bin/lein
$ sudo chmod +x /usr/bin/lein

My PATH reads as given below :
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/java/jdk1.6.0_23/bin


STEP 2 : start REPL, a simple Interactive prog env
REPL helps while learning a new programming lang, for example the groovy, scala also have implementation of REPL.

using lein repl

$ lein repl
REPL started; server listening on localhost port 63090
user=> (println *clojure-version*)
{:major 1, :minor 2, :incremental 1, :qualifier }
nil
user=> (+ 1 3)
4

user=> (println "Thread: " (.getName (Thread/currentThread)))
Thread:  nREPL-worker-0
nil

user=> (clojure-version)
"1.2.1"
user=> (inc 1)
2
user=>

I can connect to above REPL from another machine as below
$ lein repl :connect 50924
Connecting to nREPL at 127.0.0.1:50924
REPL-y 0.3.7, nREPL 0.2.12
Clojure 1.8.0

# inc returns a number one greater than num.

STEP 3 clojure collections

clojure.lang.PersistentVector

user=> (class ["order-1", "order-2"])
clojure.lang.PersistentVector

user=> (count ["order-1", "order-2", "order-3"])
3

user=> (reverse ["prayagupd", "ocean", "seattle"])
("seattle" "ocean" "prayagupd")

;; access

user=> (get ["cancer" "diabetes" "anxiety"] 1)
"diabetes"

user=> (assoc ["cancer" "diabetes" "anxiety"] 2 "social anxiety")
["cancer" "diabetes" "social anxiety"]

;; map
user=> (map #(+ % 3) [1, 2, 3]);
(4 5 6)

user=> (mapv #(str "Mental condition - " % "!" ) ["Social anxiety" "dysthymia" "PTSD"])
["Mental condition - Social anxiety!" "Mental condition - dysthymia!" "Mental con

user=> (partition 2 1 [1 2 3 4])
((1 2) (2 3) (3 4))

user=> (interleave [1 2 3] ["Social anxiety" "dysthymia" "PTSD"])
(1 "Social anxiety" 2 "dysthymia" 3 "PTSD")

Seq/ lazy Seq


user=> (map #(str "ordered sku is " %) ["sku-1" "sku-2" "sku-3"]) 
("ordered sku is sku-1" "ordered sku is sku-2" "ordered sku is sku-3")

user=> (class (map #(str "ordered sku is " %) ["sku-1" "sku-2" "sku-3"]))
clojure.lang.LazySeq


user=> (doseq [order ["order-1", "order-2", "order-3"]] 
  #_=> (println (str order " is about to be supplied.")))
order-1 is about to be supplied.
order-2 is about to be supplied.
order-3 is about to be supplied.
nil

hash-set

user=> (hash-set "social anxiety" "PTSD" "dysthymia")
#{"PTSD" "social anxiety" "dysthymia"}

user=> (conj (hash-set "social anxiety" "PTSD" "dysthymia") "depression")
#{"depression" "PTSD" "social anxiety" "dysthymia"}

user=> (disj (hash-set "social anxiety" "PTSD" "dysthymia") "PTSD")
#{"social anxiety" "dysthymia"}

user=> (contains? (hash-set "social anxiety" "PTSD" "dysthymia") "PTSD")
true

hash-map

user=> (def purchaseorder (hash-map :order-number 1234,
  #_=>     :scheduled-date 20171028,
  #_=>     :fulfillment-centre "Iowa Fulfillment Centre ",
  #_=>     :supplier "Native USA",
  #_=>     :order-skus (list "sku1" "sku2" "sku3")))
#'user/purchaseorder

user=> (:order-number purchaseorder)
1234

user=> (some #(= % "sku1") (:order-skus purchaseorder))
true

user=> (type purchaseorder)
clojure.lang.PersistentHashMap

user=> (class purchaseorder)
clojure.lang.PersistentHashMap

fp = Var + fn

user=> (defn receive [item] (println (str item " is received")))
#'user/receive

user=> (defn scan [item] (println (str item " is scanned")))
#'user/scan

user=> (defn update-inventory [item] (println (str "inventory for " item " is updated")))
#'user/update-inventory

user=> (def receiving (comp update-inventory scan receive))
#'user/receiving

user=> (receiving "item1")
item1 is received
 is scanned
inventory for  is updated
nil

References
[1] http://leiningen.org/#install

[2] How to install Clojure on Ubuntu 10.04 from Github repo with no clojure.jar, http://stackoverflow.com/a/5984183/432903

[3] http://clojure.org/getting_started

[4] Using Leiningen to build Clojure code, http://alexott.net/en/clojure/ClojureLein.html#sec2

[5] Striving to Make Things Simple and Fast - Phil Bagwell, http://www.youtube.com/watch?v=K2NYwP90bNs

[6] http://www.se-radio.net/2010/03/episode-158-rich-hickey-on-clojure/