Showing posts with label Software Development. Show all posts
Showing posts with label Software Development. Show all posts

Wednesday, April 02, 2014

OSX Development Environment Setup

I just upgraded a 2010 13” Macbook Pro with a 240GB Intel SSD 530. Started with a clean install of OSX 10.9 which I immediately updated to 10.9.2
Here are the apps I installed:
Platforms
Editors/IDE
GUI for common tools
Browsers
Utilities
  • Homebrew: package manager for OSX
  • TrimEnabler: enables SSD trim for non Apple drives
  • iTerm2: a better terminal
  • Alfred: quick search and productivity tool
  • Unarchiver: adds support for 7z and other archive file types
  • ClamXav: free opensource Antivirus
  • Synergy: cross-platform opensource Keyboard and Pointer sharing
  • Virtualbox: For virtualization needs
  • Dropbox: For cloud storage
  • Skype: free video chat and messaging client
  • Transmission: opensouce torrent client
  • VLC: Video Player
  • Cyberduck: Network File Transfer client
Almost all the applications above can be installed using brew-cask except for Homebrew, Xcode and GGTS
brew install phinze/cask/brew-cask
brew cask install java
brew cask install mamp
brew cask install sublime-text
brew cask install netbeans
brew cask install brackets
brew cask install lighttable
brew cask install sourcetree
brew cask install sequel-pro
brew cask install google-chrome
brew cask install firefox
brew cask install opera
brew cask install trim-enabler
brew cask install iterm2
brew cask install alfred
brew cask alfred link
brew cask install the-unarchiver
brew cask install clamxav
brew cask install synergy
brew cask install virtualbox
brew cask install dropbox
brew cask install skype
brew cask install transmission
brew cask install vlc
brew cask install cyberduck

Friday, April 13, 2012

Problem with grails, maven and spring security

Environment:
Ubuntu 12.04 3.2.0-20-generic-pae kernel
java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.1) (6b24-1.11.1-3ubuntu3)
OpenJDK Server VM (build 20.0-b12, mixed mode)

I installed STS 2.9.1 RELEASE which includes apache-maven-3.0.3

I placed the apache-maven-3.0.3 in my PATH environment variable

I created a project with:
mvn archetype:generate \
-DarchetypeGroupId=org.grails \
-DarchetypeArtifactId=grails-maven-archetype \
-DarchetypeVersion=1.3.7 \
-Dversion=1.0.0alpha \
-DgroupId=com.henyo.foobar -DartifactId=foobar

mvn proceeded to download the internet and then created the project folder with the pom file
I modified the pom file to set the source and target to 1.6 as described in the grails manual

I then did:
mvn initialize
which created the grails directory structure

I tried:
mvn grails:run-app
which resulted in the app successfully running

I then tried running just the unit tests with:
mvn grails:exec -Dcommand=test-app -Dargs="--unit"
which resulted in successful build

I then installed the spring security core plugin with:
mvn grails:install-plugin -DpluginName=spring-securit-core

I then tried using the s2-quickstart script:
mvn grails:exec -Dcommand=s2-quickstart -Dargs="com.henyo.foobar.model User Role"
which resulted in a build FAILURE:
[ERROR] Failed to execute goal org.grails:grails-maven-plugin:1.3.7:exec (default-cli) on project foobar: Unable to start Grails: java.lang.reflect.InvocationTargetException: org/springframework/security/core/Authentication: org.springframework.security.core.Authentication -> [Help 1]

It seems that the grails maven integration still needs a lot of work. I suspect this is a dependency resolution issue.

Uploaded a sample project that has this issue: http://dl.dropbox.com/u/5541070/foobar.tar.gz

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Books for Software Development


My updated reading list

Learning Programming
-------------
How to think like a computer scientist: Python Edition
Thinking in C beta 3
The Passionate Programmer


Learning Java
-------------
Head First Java 2nd Ed
How to think like a computer scientist: Java Edition
Objects First with Java
Thinking in Java 4th Ed
Big Java
Agile Java: Crafting Code with Test-Driven Development
Core Java Vol 1 & 2
The Art & Science of Java
The Java Programming Language

Programming Practices
---------------------
The Pragmatic Programmer: From Journeyman to Master
Pragmatic Version control using git
Pragmatic Unit testing in Java with JUnit
Pragmatic Project Automation
Debug It
Ship it
Release it

Learning Basic Web Frontend Development
---------------------------------------
Head First HTML with CSS & XHTML
Head First Javascript
Javascript the Good Parts
Stylin' with CSS: A Designer's Guide (2nd Edition)
Designing with Web Standards by Jeffrey Zeldman and Ethan Marcotte
Web Design for Developers: A Programmer's Guide to Design Tools and Techniques by Brian P. Hogan
Eric Meyer on CSS: Mastering the Language of Web Design by Eric Meyer
JQuery in Action by Bear Bibeault and Yehuda Katz
Handcrafted CSS by Dan Cederholm with Ethan Marcotte

Learning Swing Frontend Development
-----------------------------------
Desktop Java Live
Swing Second Edition
Java Swing

Mastering Software Development
------------------------------
Head First Object-Oriented Analysis and Design
Head First Design Patterns
Code Complete: A practical handbook of Software Construction
Clean Code: A Handbook of Agile Software Craftsmanship
Program Development in Java
The Elements of Java(TM) Style
Effective Java
Practical Java
Design Patterns: Elements of Reusable Object-Oriented Software
Patterns of Enterprise Application Architecture
Domain-Driven Design
Refactoring: Improving the Design of Existing Code
Refactoring to Patterns
SQL Anti-patterns
Modular Java
Growing Object-Oriented Software Guided by Tests
Holub on Patterns:Learning Design Patterns by Looking at Code
Test Driven Development by Kent Beck
XUnit Test Patterns - Refactoring Test Code by Gerard Meszaros
Concurrency Practice in Java
Java Generics and Collections
Java Performance
Java Puzzlers

Methodology and Management
--------------------------
UML Distilled, 2nd Edition
Extreme Programming Explained
The Unified Software Development Process
Rapid Development: Taming Wild Software Schedules
Peopleware: Productive Projects and Teams
The Mythical Man-Month
Software Runaways: Monumental Software Disasters
Software Creativity
Agile Estimating and Planning by Mike Cohn
Agile Software Development, Principles, Patterns, and Practices by Robert (Bob) C. Martin
Agile Retrospectives: Making Good Teams Great by Esther Derby, Diana Larsen, and Ken Schwaber
Succeeding with Agile: Software Development Using Scrum by Mike Cohn
Agile Testing: A Practical Guide for Testers and Agile Teams by Lisa Crispin and Janet Gregory
Extreme Programming Installed by Ron Jeffries, Ann Anderson, and Chet Hendrickson
Behind Closed Doors: Secrets of Great Management by Johanna Rothman, and Esther Derby
Leading Lean Software Development: Results Are Not the Point by Mary and Tom Poppendieck
Lean-Agile Software Development: Achieving Enterprise Agility by Alan Shalloway, Guy Beaver, and James R. Trott
The Art of Agile Development by James Shore and Shane Warden

Mastering Groovy and Grails
---------------------------
Groovy in Action
The Definitive Guide to Grails
Grails in Action
Groovy Recipes
Programming Groovy

Mastering Web Design
--------------------
Web Design for Developers
Head First Web Design
Designing Web Usability

Mastering User Interface Design
-------------------------------
User Interface Design for Programmers
Don't Make me Think
About Face: The Essentials of User Interface Design
Design of Everyday Things
The Non-Designer's Design Book

Mastering Hardcore Stuff
------------------------
Code: The Hidden Language of Computer Hardware and Software by Charles Petzold
The C Programming Language
Structure and Interpretation of Computer Programs
Introduction to Algorithms by CLRS (Cormen,Leiserson,Rivest,Stein)
Compilers: Principles, Techniques and Tools
Test Driven Development for Embedded C
The Art of Computer Programming


- Head First Java
- Head First Object Oriented Analysis and Design
- Head First Design Patterns
- Effective Java
- Concurrency Practice in Java
- Java Generics and Collections
- Java Performance
- Java Puzzlers
- Thinking in Java
- Clean Code


You are also welcome to subscribe via email or subscribe via reader to get updates.

Tuesday, April 03, 2012

Trying Ubuntu 12.04LTS Precise Pangolin

I migrated my desktop from Ubuntu 10.04LTS to Ubuntu 12.04LTS.

A few things I needed to add after installation:
  • Chromium as my default browser
  • adobe-flash to be able to play flash games on facebook
  • openjdk-6-jdk for work stuff
  • icedtea-plugin to be able to run charting applet on citisec
  • pidgin for messaging
  • git for more work
  • smartgit for routine pushing and comitting to git repos
  • smartsvn for routine pushing and comitting to git repos
  • STS for work stuff
  • DB Visualizer for work stuff
  • Virtual Box for desktop virtualization
  • Dia for diagramming
  • synergy to share one keyboard between my desktop and laptop
  • dropbox for personal file sharing
  • pencil for mockups
  • smplayer for watching videos
  • vlc for videos that do not work with smplayer
  • git gui for simple git commits
  • myqsl-server for development work
  • mysql workbench for managing mysql database
  • postgresql for development work
  • pgadmin for managing postgres database

Should I be replacing stuff on the list with something else? What other stuff have I forgotten to install?

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Thursday, March 29, 2012

Building a good Software Startup

If I were to build a good software startup today, I'd run with the following ideas.

Hire only good people who get things DONE.
Even if they are more expensive in terms of compensation.
Quality trumps numbers. No doubt about it.


Development Team
  • 1 Lead Developer
  • 1 Senior Developer
  • 2 Junior Developers
  • 2 Business Analyst/QA

Operations Team
  • 1 Lead Systems Admin
  • 1 Senior System Admin
  • 6 Junior System Admins

Give your team a quiet working environment with ergonomic furniture and equipment

Give your team good internet connection
  • the faster they can download their installers, the earlier they can start working on code
  • the faster they can look up the solution on google or stackoverflow, the faster they can proceed to the next problem

Give your team good computer hardware
  • at least dual core processors with virtualization support
  • at least 8GB memory
  • at least 2 hard drives for mirror setup
  • at least 2 screens

Make sure to have enough environments to test, deploy and support the system properly.
  • Development Environment
  • Staging Environment
  • Support Environment
  • Production Environment

Make use of Free or Open Source systems to manage the development process.
Buy a commercial product only if you can't find a solution that fits.


Project/Issue Tracking with Source Code Management Options:
  • Indefero
  • Gitorious
  • Gitlab
  • Redmine+gitolite

Continuous Integration Server Options:
  • Jenkins
  • Team City

Code Quality:
  • Sonar

Setup google apps for for email, calendar and other stuff

As an example, here is how I would set it up on three physical servers:

Server#1 running ProxmoxVE
- Firewall/Proxy Server/Package Cache(apt,yum,mvn) VM
- Redmine+gitolite VM
- Jenkins VM
- Sonar VM
- NFS/Samba Server VM

Server#2 running ProxmoxVE
- Development Environment VM
- Staging Environment VM
- Support Environment VM

Server#3 for storage of backups
- nexentastor or freenas or centos+zfsonlinux

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Monday, March 26, 2012

FizzBuzz in Javascript

Joel and company probably won't hire me since he only gets rockstar developers but here is my attempt at FizzBuzz
<script>
    for(var i=1;i<=100;i++){
        if(i%3 != 0  && i%5 != 0)
            document.write(i);
        if(i%3 == 0)
            document.write('Fizz');            
        if(i%5 == 0)
            document.write('Buzz');                    
        document.write(' ');
    } //end for loop
</script>
I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Wednesday, November 02, 2011

Monitoring Tomcat6 with VisualVM on Ubuntu

One of our applications running on Tomcat6 was encountering an issue which was drastically affecting the delivery of services to our clients. To diagnose this, we needed to monitor the state of the virtual machine running Tomcat6. This is what I had to do:

Assumptions:
- tomcat6 installed on an ubuntu server instance
- firewall on the server instance is enabled
- server has non public ip address: 10.0.0.1
- client machine installed with java6 which includes visualvm

1) download catalina-jmx-remote.jar and copy it into the tomcat6 lib folder. At the time of this writing, I found it here: http://apache.opensourceresources.org/tomcat/tomcat-6/v6.0.33/bin/extras/

2) modify /etc/defaults/tomcat6, add the following line to JAVA_OPTS

-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=10.0.0.1

3) modify /etc/tomcat6/server.xml, add the following line inside the server block near the other listeners:
<Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener"
rmiRegistryPortPlatform="8086" rmiServerPortPlatform="8086" />

4) enable access to port 8086

ufw allow 8086

5) restart tomcat6
service tomcat6 restart

6) start visualvm on the client machine and add a jmx connection: 10.0.0.1:8086

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Sunday, April 17, 2011

Setting up a Spring Data JPA Project

This post is about setting up a Maven Project based on Spring Data JPA. I spent a few hours today nailing it down. Hopefully it saves someone some time to bring a project up quickly.

- Spring Framework based application
- makes use of Spring Data JPA for easy Repositories
- makes use of JPA 2.0 persistence with EcliplseLink
- JUnit4 and spring-test
- Logging using SL4J to Log4J

For the impatient, I uploaded a sample project on github: spring-data-jpa-trial

You can also download the tar ball or zip file from these links.

I started with a blank Maven Project created with STS 2.5.2.SR1 created using
the New Maven Project wizard checking the Create a simple project(skip archetype selection).

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test</name>
<description>test</description>
</project>

Added some entries to the pom file to setup 1.6
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>

Setup spring-data-jpa dependency
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.0.0.M2</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>http://maven.springframework.org/milestone</url>
</repository>

Setup persistence dependecies
<!-- Persistence dependencies -->
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${spring.framework.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.2.0</version>
<scope>runtime</scope>
</dependency>
<repository>
<id>EclipseLink Repo</id>
<url>http://download.eclipse.org/rt/eclipselink/maven.repo</url>
</repository>

Setup logging dependencies as discussed in the Spring Framework Reference Docs
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${sl4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${sl4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${sl4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<scope>runtime</scope>
</dependency>

Setup Testing Dependencies
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.framework.version}</version>
<scope>test</scope>
</dependency>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.8</version>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>        
<argLine>-javaagent:spring-instrument-3.0.5.RELEASE.jar</argLine>
</configuration>
</plugin>

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Friday, October 01, 2010

Drawing the Usecase Diagrams

I imagine TaskStream will be used by 2 types of people in an organization, Users and Admins.
The diagrams above was produced using yuml.me using:

[User]-(Sign in)
(Sign in)>(Sign out)
(Sign in)>(Update Settings)
(Sign in)>(Forgot Password)
[User]-(Share a task)
(Share a task)>(Delete task)
(Share a task)>(Update task)
[User]-(View task stream)
[User]-(Comment on a task)
(Comment on a task)>(Delete own comment)

Admins, in addition to what regular users can do, also have a few more use cases:


[Admin]-(Manage Users)
(Manage Users)>(Update a User)
(Manage Users)>(Delete a User)
[Admin]-(Generate Reports)

I think this is enough to cover the basic functionality of TaskStream. It's time to go into detail and flesh out the User Stories.

TaskStream devlog#02: Writing the User Stories
TaskStream: simple task sharing and tracking

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

TaskStream: simple task sharing and tracking


TaskStream is a web application that allows the internal users of an organization to share tasks with one another as well as to comment on each others tasks. It is designed and built to be run on the intranet allowing organizations better control of usage as well as features and customizations. The web application tracks the status of each task as well as the amount of time spent on said task allowing management to make timely and accurate decisions. 


TaskStream will also serve as the showcase application for building a grails application using the correct approach: complete with upfront Use Case Diagrams,User Stories and Domain Models. I will also strive to write the tests first before the implementing code whenever possible. I will be documenting the progress on this blog which could allow me to make an e-book or perhaps a couple of screencasts to sell on line. Perhaps this could also form the basis of a seminar/talk which I could give so as to help pay for the bills. Or I could accept donations for feature requests so that I could continue working on the system. The possibilities seem endless but I am getting ahead of myself.

TaskStream devlog#01: Drawing the Usecase Diagrams
TaskStream devlog#02: Writing the User Stories
TaskStream devlog#03: Mocking up the screens
TaskStream devlog#04: Domain Modeling
TaskStream devlog#05: Creating the Grails Project
TaskStream devlog#06: Dealing with Security

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Wednesday, September 15, 2010

REST XML parsing with Grails 1.3.4

We encountered an issue with Grails 1.3.4 where we found that the XML packet was not parsed and added to the params variable in the controller.

The grails manual has a section which describes how to do REST web services. We followed the instructions but we weren't able to get the automatic data binding to our domain class to work. A fix seems to be on the way but in the mean time, the code below provides a workaround for the issue:

private populateParamsFromXML(xml,map) {              
        def rootName = xml.name()
        //check if params is already populated
        if(map[rootName])
            return
        def xmlMap = [:]
        map[rootName] = xmlMap          
        map = xmlMap
        for (child in xml.children()) {
            // one-to-ones have ids
            if (child.@id.text()) {
                map["${child.name()}.id"] = child.@id.text()
                def childMap = [:]
                def key 
                map[child.name()] = childMap
                populateParamsFromXML(child, childMap)
            }
            else {
                map[child.name()] = child.text()
            }
        }
    }

It should be called in a controller action before the params variable is used to populate a domain class.

populateParamsFromXML(request.XML,params)

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

Wednesday, July 14, 2010

Symfony: Day#1

Symfony is a web application framework for PHP projects. It aims to speed up the creation and maintenance of web applications, and to replace the repetitive coding tasks by power, control and pleasure.
Symfony is entirely free and published under the MIT license.

I'm currently following the online Symfony tutorial which can be found here: Practical Symfony.

This post documents how I got Symfony 1.4 running on an Ubuntu 10.04 Server installation. When I installed the server, I chose the option to install a default LAMP and Email server.

Monday, May 03, 2010

Grails with Notepad++ Text Editor

Yesterday, I had to work on a Grails project on my old laptop which was running a fresh install of Windows XP SP3. The laptop is about 8 years old. It had 512mb memory and a Pentium M 1500Mhz. The experience was not very good.

First thing I had to do was to get Java installed. I went to the official website and downloaded JDK 1.6.0_20. I ran the installer and proceeded with the next step.
Next I downloaded the zip file distribution of Grails version 1.1.1 and extracted it to c:\grails.

Friday, August 07, 2009

Using ID tables with Grails

Background and Use Case: We had to migrate one of our web applications to Grails. The old one used JPA and table-based scheme of generating primary key IDs. I scoured the internet with the help of google and found no one with the same problem. I of course had to do it on my own and after going thru the Grails docs, JPA docs and Hibernate docs, I arrived at the solution:
    static mapping = {
        id generator:'org.hibernate.id.enhanced.TableGenerator',
            params:[table_name:'id_table',value_column_name:'gen_id',segment_column_name:'gen_key',segment_value:'fooID']
    }
If you stick the above code in a domain class named Foo, you will end up with a table named id_table and it will have two columns, gen_key and gen_id. If you try saving an instance of Foo, you will end up with:
gen_keygen_id
fooID 1

If you do something similar to the domain Bar, you will end up with:
gen_keygen_id
fooID 1
barID 1

Did it work for you? You are welcome to post your comments/questions or better yet, link to this post, blog about it and tell all your friends who might find this post useful.

Thursday, July 09, 2009

Easy Use Case Diagrams with YUML

[Site Admin]-(Manage content),
(Manage content)>(Delete content),
(Manage content)>(Modify content),
(Manage content)>(Create content),
[Site Admin]-(Manage pages),
(Manage pages)>(Delete a page),
(Manage pages)>(Modify a page),
(Modify a page)>(Add Content to a page),
(Modify a page)>(Remove Content from a page),
(Manage pages)>(Create a page)

I can't remember how I stumbled upon this site but I'm glad I did. YUML allows you to create class and use case diagrams online using a simple text syntax. This blog post from the author of the site demonstrates how to use jquery to render a fairly complicated class diagram. Below is the code I used to generate the use case diagram above.
<pre class="diagram">
[Site Admin]-(Manage content),
(Manage content)>(Delete content),
(Manage content)>(Modify content),
(Manage content)>(Create content),
[Site Admin]-(Manage pages),
(Manage pages)>(Delete a page),
(Manage pages)>(Modify a page),
(Modify a page)>(Add Content to a page),
(Modify a page)>(Remove Content from a page),
(Manage pages)>(Create a page)
</pre>

<script type="text/javascript" charset="utf-8">
$('document').ready(
    function(){
        text = $('.diagram').html().replace('\t','').replace('\n','').replace(/&gt;/g,'>');
        $('.diagram').html('');
        $('.diagram').append('<img width="320" height="240" src="http://yuml.me/diagram/scruffy/usecase/' + text + '" />');
    }
);
</script>
Did it work for you? You are welcome to post your comments/questions or better yet, link to this post, blog about it and tell all your friends who might find this post useful.

Wednesday, June 24, 2009

Run grails-app on the root context

USECASE: You want to run your shiny grails killer-app using the jetty server on port 80 and using the root context. Running it on port 80 is covered by providing the grails run-app command with the desired port but your app will still run on http://localhost:80/killer-app. To run it on the root context, you can do:
grails -Dserver.port=80 -Duse.root.context.path=true run-app
but first, you have to modify _GrailsRun.groovy and change an existing method to this:
private runInline(scheme, host, httpPort, httpsPort) {
    EmbeddableServerFactory serverFactory = loadServerFactory()    
    def useRootContextPath = System.getProperty("use.root.context.path")
    if(useRootContextPath)
        serverContextPath = '/'
    grailsServer = serverFactory.createInline("${basedir}/web-app", webXmlFile.absolutePath, serverContextPath, classLoader)
    runServer server: grailsServer, host:host, httpPort: httpPort, httpsPort: httpsPort, scheme:scheme
    startPluginScanner()
}
You can find _GrailsRun.groovy in $GRAILS_HOME/scripts

WARNING: THERE ARE SERIOUS PENALTIES FOR ROLLING OUT YOUR APP THIS WAY

The code seems trivial but I'll submit it anyway to the grails dev team for inclusion. Did it work for you? You are welcome to post your comments/questions or better yet, link to this post, blog about it and tell all your friends who might find this post useful.

Monday, May 04, 2009

Fix: Missing tmp directories in .svn

Last last Friday, I took some code home to work at over the weekend. When I came back to work on the following Monday, I couldn't commit the changes to the Subversion repository. Further investigation led me to discover that most of the tmp directories inside the hidden .svn folders were missing. It seems that the archive tool I used ignored empty directories. To fix this, I cooked up a quick script in groovy as shown below:
File currentDir = new File(".")
processDirectory(currentDir)

void processDirectory(File dir){
    println "Processing "+dir.getAbsolutePath()
    //check if .svn dir exists
    String path = dir.getAbsolutePath()
    File svnDir = new File(path+"/.svn")
    if(svnDir.exists()){
        if(svnDir.isDirectory()){
            //check if tmp dir exists
            File tmpDir = new File(svnDir.getAbsolutePath()+"/tmp")
            if(tmpDir.exists()){
                println "tmp folder already exists "+tmpDir.getAbsolutePath()
            }else{
                tmpDir.mkdir()
            }            
        }else{
            println ".svn is NOT a directory"
        }
    }else{
        println "no .svn dir"
    }
    
    dir.listFiles().each{ file ->    
        println "Processing "+file.getAbsolutePath()
        if(file.isDirectory()){
            if(file.name == ".svn")
                return
            println "Processing "+file.getAbsolutePath()
            processDirectory(file)
        }
    }
}
To use this fix, open a text editor and copy paste the code above into an empty file and save it as fixSvn.groovy to the folder of the workspace you want to fix Make sure you have groovy installed then do
groovy fixSvn.groovy
Did it work for you? You are welcome to post your comments/questions or better yet, link to this post, blog about it and tell all your friends who might find this post useful.

Wednesday, April 29, 2009

Mocking Transactions for unit testing a Grails Service

Use Case:
As a good developer
I should be able to unit test services that programmatically use transactions
So that I can minimize defects  and have high unit test coverage
The Example Specs:
A persistent Foo object has a bar field which is of type String. Write a service with a doSomethingTransactional method that accepts a Foo object as a parameter. The method should change the value of bar to 'did something transactional' if the value of bar is NOT 'oops'
The Domain:
package com.henyo.model

class Foo {

    String bar

    static constraints = {
    }
}
The Unit Test:
package com.henyo.service

import grails.test.*
import com.henyo.model.*
import com.henyo.service.*
import com.henyo.*

class FooServiceTests extends BaseUnitTestCase{

    void testShouldCommit(){
        def foo = new Foo(bar:'not oops')
        mockForTransaction(Foo)
        def service = new FooService()
        service.doSomethingTransactional(foo)
    }

    void testShouldRollBack(){
        def foo = new Foo(bar:'oops')
        mockForTransaction(Foo,true)
        def service = new FooService()
        service.doSomethingTransactional(foo)
    }
}
The unit test above takes into account 2 scenarios. One where we expect that the transaction will be committed and the other one will signal a rollback. The mockForTransaction actually returns a TransactionStatus object which can be used to check if the transaction is indeed committed or if it is for roll back. There is no need though to test for this as BaseUnitTestCase handles this for you automatically.
The Service:
package com.henyo.service

import com.henyo.model.*

class FooService {

    boolean transactional = false

    def doSomethingTransactional = { foo ->
        Foo.withTransaction{ status ->
            if(foo.bar == 'oops'){
                status.setRollbackOnly()
            }
        }
    }
    
}
My BaseUnitTestCase:
package com.henyo

import grails.test.GrailsUnitTestCase
import org.springframework.transaction.TransactionStatus

class BaseUnitTestCase extends GrailsUnitTestCase {

    def statusControls

    protected void setUp() {
        super.setUp()
        statusControls = []
    }

    protected void tearDown(){
        statusControls.each{
            it.verify()
        }
        statusControls.clear()
        super.tearDown()
    }

    def mockForTransaction(Class clazz,boolean expectRollback = false){
        registerMetaClass(clazz)
        def statusControl = mockFor(TransactionStatus)
        statusControls << statusControl
        if(expectRollback)
            statusControl.demand.setRollbackOnly(1..1) { println 'setRollbackOnly called'}
        def status = statusControl.createMock()
        clazz.metaClass.'static'.withTransaction = {
            Closure callable ->  callable.call(status)
        }
        return statusControl
    }
}
Did it work for you? You are welcome to post your comments/questions or better yet, link to this post, blog about it and tell all your friends who might find this post useful.

Friday, April 18, 2008

Grokking Appfuse

I'm running CentoOS 5 and here is the output of mvn --version Maven version: 2.0.9 Java version: 1.5.0_14 OS name: "linux" version: "2.6.18-53.1.14.el5" arch: "i386" Family: "unix" To start having fun(or frustrating yourself) with appfuse, you need * jdk 1.5+ * maven 2.0.x * mysql 5+ Check the Installers folder in our file server if you need any of the above files. For reference, here is the output of mvn -version on my CentOS5 box Maven version: 2.0.9 Java version: 1.5.0_14 OS name: "linux" version: "2.6.18-53.1.14.el5" arch: "i386" Family: "unix" Appfuse makes use of Maven to automate most of its stuff. First thing to do is to setup the maven installation to make use of the internal repository. Locate and open(use a text editor) the settings.xml found in the conf directory of your maven installation. It should have a mirrors section, modify it so that it would look something like this: <mirrors> <mirror> <id>internal</id> <mirrorOf>*</mirrorOf> <name>internal</name> <url>http://scm:8080/archiva/repository/internal</url> </mirror> </mirrors> Next, you need to create the project structure. Using the commandline, go to your workspace directory and run: mvn archetype:create \ -DarchetypeGroupId=org.appfuse.archetypes \ -DarchetypeArtifactId=appfuse-modular-struts \ -DremoteRepositories=http://static.appfuse.org/releases \ -DarchetypeVersion=2.0.1 \ -DgroupId=com.henyo.etg \ -DartifactId=eTestGen This will create a modular struts2 project instead of a basic project. Why modular? I dunno, seems way cooler than a basic project? or according to Matt Raible: The basic archetypes are ideal for creating projects that will serve as web applications. The modular archetypes contain "core" and "web" modules and are ideal for creating projects that have a re-usable backend. Using the command line, change into the project directory and run mvn clean appfuse:full-source This will download the source code of appfuse which we need because there is a STUPID error in the way the dependecies are downloaded. Specifically, there are two versions of spring on the classpath(2.0 and 2.5) so depending on the mood of the freaking class loader, the older version may be loaded which is NOT compatible with the applicationContext-service.xml so you will get this when you try running your project: ERROR [main] ContextLoader.initWebApplicationContext(203) | Context initialization failed org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [applicationContext-service.xml]; nested exception is java.lang.NoSuchMethodError: org.springframework.beans.factory.xml.ParserContext.registerBeanComponent(Lorg/springframework/beans/factory/parsing/BeanComponentDefinition;) You need to modify the pom.xml file inside the web folder, locate the struts2-spring-plugin dependency declaration and modify it so that it looks like this: <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${struts.version}</version> <exclusions> <exclusion> <artifactId>spring-context</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-beans</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> then change into the core directory and run mvn clean install then go to the web directory and do mvn jetty:run-war You can now access the application in: http://localhost:8080

Sunday, December 17, 2006

In search of a standards based fullheight 1-column layout -- the problem

I need to re-skin a transactional web site my company has built and I plan to do it with web standards and accessibility in mind. A typical page should look like this: <div id="container"> <div id="content"> <p>Page Content goes here</p> </div> <div id="header"> <h1>Header 1</h1> <ul id="tab_navigation"> <li><a href="#">link1</a></li> <li><a href="#">link2</a></li> </ul> </div> <div id="footer"> <p>Copyright © 2006 <a href="#">Footer</a> </p> </div> </div> Detailed Specifications: The content div should come first followed by the header div which contains the ul that should be rendered as tabs. The footer follows next. It should remain near the bottom of the browser page even if the page has short content while pages with longer content should place the footer near the end of the content. IE and Firefox should both render similar results. So has someone actually done this?