I do not have enough time to post articles in more than one place, so I will retire (at least temporarily) this blog in favor of my site definenull.
Hope to see you all there!
Cheers,
Dani
Saturday, August 1, 2009
Retirement of the blog
Posted by Daniel @ 9:56 PM 0 comments
Thursday, June 18, 2009
Dude, where are my resources?
I was struggling with a stupid problem this week and it took me some time to realize what was going on, so I will post here the solution so nobody else needs to waste time on this matter again (and for future reference for myself as well ;)).
I wanted to read a .csv (comma separated value) text file that was inside one package in my application. Consider the simplified version of my code in the tree below.
src
|- main
|- java
|- com
|- App.java
|- resources
|- file.csv
The App.java had this (simplified) code:
public class App {
public static void main(String[] args) throws IOException {
URL url = App.class.getResource("com/resources/file.csv");
}
}
The value of the variable
url
was null. And there is one simple (and quite obvious once you find out) reason for this. The resource file was indeed in my src folder, but it was not in my destination folder where the classes were generated. As I am using maven, this would be the target
folder.And why is this obvious? Because the
getResource
method uses the ClassLoader of the calling class to find the resource you are looking for, and the realm of files the ClassLoader knows are in the classpath. As I was executing the code from my IDE, the classpath would be the compiled classes from sources. On top of that, the problem was that the text files not being copied to the destination folder.Thanks to Maven the solution was quite simple. As it is based on convention over configuration, all I did was to move the resources folder to the root of the
src/main
folder like this:
src
|- main
|- java
|- com
|- App.java
|- resources
|- file.csv
The App.java had this (simplified) new version of the code:
public class App {
public static void main(String[] args) throws IOException {
URL url = App.class.getResource("file.csv");
}
}
In summary, just make the resource available somewhere in your classpath: in the
target/classes
folder or in the .jar you are generating.Find this article also on definenull.com.
Posted by Daniel @ 12:13 AM 0 comments
Labels: getResource, getResourceAsStream, Java
Thursday, June 11, 2009
Java in Ubuntu
Well, I am now just trying to use Ubuntu as a development environment. First thing I noticed is that there are more than one jre already installed by default in the system, and here is the evidence:
jars@jars-desktop:~$ locate /rt.jar
/usr/lib/jvm/java-6-openjdk/jre/lib/rt.jar
/usr/lib/jvm/java-6-sun-1.6.0.07/jre/lib/rt.jar
I really wanted to use the Sun JDK for my development instead of OpenJDK, so I installed the Sun Java.
Just type the command below and compare the results:
sudo apt-get install sun-java6-bin sun-java6-jre sun-java6-jdk
jars@jars-desktop:/etc/alternatives$ sudo apt-get install sun-java6-bin sun-java6-jre sun-java6-jdk
Reading package lists... Done
Building dependency tree
Reading state information... Done
sun-java6-bin is already the newest version.
sun-java6-jre is already the newest version.
sun-java6-jre set to manually installed.
Suggested packages:
sun-java6-demo sun-java6-doc sun-java6-source
The following NEW packages will be installed:
sun-java6-jdk
0 upgraded, 1 newly installed, 0 to remove and 14 not upgraded.
Need to get 17.4MB of archives.
After this operation, 55.7MB of additional disk space will be used.
Get:1 http://de.archive.ubuntu.com hardy-updates/multiverse sun-java6-jdk 6-07-3ubuntu2 [17.4MB]
Fetched 17.4MB in 3min23s (85.6kB/s)
Preconfiguring packages ...
Selecting previously deselected package sun-java6-jdk.
(Reading database ... 139447 files and directories currently installed.)
Unpacking sun-java6-jdk (from .../sun-java6-jdk_6-07-3ubuntu2_i386.deb) ...
sun-dlj-v1-1 license has already been accepted
Setting up sun-java6-jdk (6-07-3ubuntu2) ...
But which of the two JVMs that now reside in my system area going to be used? Here it comes the ass-saving (and brand new to me) Ubuntu command:
sudo update-java-alternatives -s java-6-sun
This will define Sun Java-6 as the default JVM in your system. If you prefer to do it step-by-step just type this:
jars@jars-desktop:~$ sudo update-alternatives --config java
There are 2 alternatives which provide `java'.
Selection Alternative
-----------------------------------------------
+ 1 /usr/lib/jvm/java-6-openjdk/jre/bin/java
* 2 /usr/lib/jvm/java-6-sun/jre/bin/java
Press enter to keep the default[*], or type selection number:
The next tricky step is to set the prefered order in which your JVMs shoud be used. To set this up just edit the /etc/jvm
file and include your recently installed JVM as the first one, so your file looks more or less like this:
# This file defines the default system JVM search order. Each
# JVM should list their JAVA_HOME compatible directory in this file.
# The default system JVM is the first one available from top to
# bottom.
/usr/lib/jvm/java-6-sun
/usr/lib/jvm/java-gcj
/usr/lib/jvm/ia32-java-1.5.0-sun
/usr/lib/jvm/java-1.5.0-sun
/usr
Ok, not ready yet, but I am not willing to return to Windows without doing this until the end! :)
So, next step is setup the environment variables and if you want to set it system wide, edit the /etc/profile
file and append the following lines at the end:
export JAVA_HOME=/usr/lib/jvm/java-6-sun
export PATH=$PATH:$JAVA_HOME/bin
You can also set the variables for only one user by editing /home/$user_name$/profile
.
Now test it!!
jars@jars-desktop:/etc/alternatives$ java -version
java version "1.6.0_07"
Java(TM) SE Runtime Environment (build 1.6.0_07-b06)
Java HotSpot(TM) Client VM (build 10.0-b23, mixed mode, sharing)
You find this article also on definenull.com.
Posted by Daniel @ 12:54 AM 1 comments
Wednesday, June 10, 2009
JavaOne 2009 Slides
You can download the slides from JavaOne 2009 conference from here. Just choose the track and find the slides.
You need to be signed at the Sun Developer Network (SDN) to view/download the pdf.
Cheers
Posted by Daniel @ 3:41 PM 0 comments
Labels: Java, javaOne, javaone_2009, javaone2009
Thursday, June 4, 2009
JavaOne 2009: RESTful Transaction Systems
Mark Little (JBoss CTO) and Michael Musgrove (Red Hat Tx)
RESTful Transaction Systems
- Atomic Transactions should have a scoping mechanism that provides "all-or-nothing" semantics, enables shared resources to be protected from concurrent use and have ACID properties (Atomic, Consistent, Isolated, Durable)
- WS-Transactions in the past vas very hard to achieve transactional interaction among WS services; even JTS implementations didn't interoperate but WS provide the opportunity to leverage unparalleled interoparability
- On B2B interaction, one cannot affort to lock resources on behalf of an individual indefinitely and maybe you need to undo a subset of the worh that's been done
- Possible Transaction Models for REST
- Atomic Transaction (XA/XTA) - status: specified and implementd
- Forward Compensation Base (WS-BP)- status: specified
- Implementation for REST transaction for JBoss uses an uniform interface with HTTP and the usual methods (GET, PUT and POST) return the usual HTML code and some XML in the body
- Example URLs:
GET <s>://<auth>/transaction-coordinator/active
POST <s>://<auth>/transaction-coordinator/begin
- Demo is using the transaction-coordinator (with a Proxy in Tomcat) and some Web Services in Python, JBoss TM and RESTeasy
Posted by Daniel @ 3:25 PM 0 comments
Labels: Java, javaOne, javaone_2009, javaone2009, JBoss
JavaOne 2009: Enterprise Application Integration Patterns
Andreas Egloff (Sun) and Bruce Snyder (SpringSource)
Enterprise Integration Patterns in Practice
"A Design Pattern is a formal way to document a solution to a design problem ina particular field of expertise" - from Wikipedia
- The presentation is based on the "enterprise integration patterns" book
- Stencils for Visual Studio in EAI Patterns web site
- Flexibility x Productivity: too little explicit support out-of-the-box but explicit support out-of-the-box is too rigid (does not fit your case or you are forced to go around) - the solution would be to extend those use cases
- Frameworks: Apache Camel and Project Fuji (from OpenESB v3)
- Camel supports routing of messages in a simple manner like, for instance,
from("A").to("B")
and much more complex stuff like taking decisions in the route and where to route the message to; it also suppors a pipeline routing much likefrom("file://myfile.txt").choice().when().method("MyBean","matches").to("Q").end().pipeline("B","C","D")
- Some Camel components: Atom, Bean, SEDA, SFTP, HTTP, FTP, Mock, XQuery, XSLT and much more (70+)
- Project Fuji is the basis for OpenESB v3 and is a service platform to realize SOA based on Convention - Configuration - Code in that order; Light weight and OSGi based and not centred on JMS but on Services
- The Project Fuji has a Web UI that allows the user to visually declare and configure services and program the connections and routing of services; it also offers a DSL (Integration Flow Language)
- Bruce and Andreas went on some slides with examples of the patterns from EAI book and showed how those are implemented in Camel calls using Fuji interface to build them - it seems easy, but as they said in the beginning of the presentation, using out-of-the-box solutions might be too rigid; on the good side, you can write code using DSL and even pure Java, so it really might be an interesting solution for integration
- After the slides, a quick live demo using Eclipse with some tools for Spring and Maven with archetypes for Apache Camel
Posted by Daniel @ 2:21 PM 0 comments
Labels: Java, javaOne, javaone_2009, javaone2009
Wednesday, June 3, 2009
JavaOne 2009: Coding REST and SOAP together
Martin Grebac and Jakub Podlesak from Sun Microsystems on Coding REST and SOAP together
- Using METRO = JAXB + JAX-WS + WSIT and Jersey
- No deployment descriptors needed (use annotations) but still available if required; part of Java EE 5 and 6
- Why REST? Simplicity, Takes advantage of the existing caches and proxies, Serendipity, Scalability (HTTP load balancers)
- Common JAX-WS/RS concepts should be supported
- Heavy using of annotations: @Path, @WebService, @GET, @Produces, @WebMethod, @XmlRootElement, @XmlAttribute etc.
- Take care: do not fall into RPC over HTTP (REST-RPC hybrid), use compatible security (Securing SOA does not automatically secure the REST), annotation hell
- Think about the consumers of your services and ask yourself if you really need SOAP and REST; consider using REST only in some parts of your application
- Use @WebMethod annotations to enable control over exposed SOAP methods
Posted by Daniel @ 8:58 PM 0 comments
Labels: Java, javaOne, javaone_2009, javaone2009
JavaOne 2009: Effective Java
Joshua Bloch in "Effective Java: still effective after all these years"
First Edition of the famous book Effective Java was in 2001 and is now on its second edition from 2008 and it has new chapters on generics, enums, annotations, varargs, concurrency and Serialization
- About Generics
- Unlike arrays, generics types are invariant: List <String> is not a subtype of List <Object>; Wildcard provide additional API flexibility
- PECS - Producer extends, Consumer super (Mnemonic for Wildcard usage)
- How to write a container with an arbitrary number of type parameters: typesafe heterogenous container pattern - parameterize selector instead of container; present selector to container to get data; data is strongly typed at compile time; allows for unlimited type parameters
- Enum Types
- double temp = thermometer.getTemp(true)
- double temp = thermometer.getTemp(Temperature.FAHRENHEIT)
- double temp = thermometer.getTemp(FAHRENHEIT)
- which of the above would you prefer? :)
- Synchronized collections are largely obsolete; use ConcurrentHashMap and friends and Never sinchronize on a concurrent Collection
- The Serialization Proxy Pattern - don't serialize instances of your class; instead, serialize instances of a small, struct-like class that concisely represents it, then reconstitue instances of your class at read time using a constructor that uses only its public methods - Sun uses this pattern on its EnumSet there is a private static final SerializationProxy
The presentation is based on lots and lots examples of code, so it's kind of hard to resume them here! ;) In essence, it is probably a good idea to buy the new edition of the book! ;)
Posted by Daniel @ 6:30 PM 0 comments
Labels: Java, javaOne, javaone2009
JavaOne 2009: Enterprise Build and Test in the Cloud
Carlos Sanchez from G2iX on Enterprise Build and Test in the Cloud
- Tools:
- Build: Apache Maven (build and more, start/stop AS, automatic deployment, execution of tests - note: most people in the room use maven and not ant)
- Test Cases: TestNG (they don't use JUnit) - unit/integration tests, parameterized tests, parallel testing - note: not many people in the room uses TestNG
- Integration tests: Selenium - UI and integration testing, tests run in the browser, tests can be recorded, firefox plugin
- Continuus Integration: Apache Continuum - tight integration with Maven, dependency handling, trigger builds on defined conditions - note: not many people in the room use continuum
- Cloud Computing: Amazon Web Services - storage, queue service, manpower, computation
- Joke of the day: The #1 Programmer Excuse for legitimately slacking off: "my code's compiling" - credits XKCD
- Different setup for selenium grid: using a selenium hub brings no complexity to the developers or to the already written tests; setting up differente remote controls for differente environments (IE on Windows, Firefox on Linux, Safari on Mac) only depends on having the Selenium hub
- TestNG will allow to run the same tests in the different environments that were setup by Selenium Grid
- Test Servers cost money: using the cloud allows to use on-demand servers, pay-per-hour, unlimited number of machines and start in a couple of minutes - no OS X offered by amazon
- Create Amazon Machine Images for each different environment you need to test your application - The machines are killed after the tests are run and you only pay for the time you use those machines
- Use Maven EC2 plugin to start amazon AMIs, stop at the end of test and pass user data
Found a different (but up to date) version of this presentation from Carlos Sanches at slideshare.
Posted by Daniel @ 3:52 PM 0 comments
Labels: Java, javaOne, javaone2009
JavaOne 2009: Lessons Learned in ESB
Andreas Egloff and Frank Kleviet: ESB Lessons Learned
Both speakers work now at Sun in the OpenESB project and come from a big vendor that sold EE products.
- ESB as a product comes with risks like, for instance, architecture concerns (good or bad for SOA?), more middleware, over-reliance on one provider
- Light weight non functional requirements: enterprise scale integration, change happens (decouple configuration), long term commitments (today's hot stuff is tomorrow's legacy)
- Accomodate large teams: enterprises like to scale by adding people and this makes things harder: easy-to-learn is critical, provide tooling (automated testing & integration) and keep the solution simple
- Tooling is great, but don't let it get in the way!
- In their words: "Consultants tend to think that copying and pasting code make them more productive. And this is not true.!: Prefer convetion and configuration over coding! Support Patterns as first class citizens!
- Frameworks are poweful to reduce code duplication, but sometimes constrain flexibility: Interceptors are a powerful way to add flexibility
- Developers spend a lot of time waiting. It is necessary to shorten the change-build-deploy-test cycle, by reducing build time, deploy time with smapper deployables or in-place editing; increase testability and debuggability with built-in tests and support automation
- Modulartiy improves startuptime and performance by only loading what's necessary when it's needed. Modularity can help control complexity.
- Reduce the artifacts per solution or make managing large numbers of artifats possible.
- Connectivity Configuration: configuration belongs to run-time and not design or development time; deployables are used in different environments
- Message-based services more robust in face of change so avoid rebuilding the world for small business logic changes: use scripting languages, externalize business logic (e.g. CBR), consider evolution, versions in handling messages, externalize cross-cutting concerns (e.g. Aspects)
- Patch Management! OSBi allows to declare a dependency on a specific version of a component, and this way it is not necessary to test the whole enterprise application because you need to upgrade one library
- JMS if often a bottleneck - component-component message-passing can also be done without JMS; in-memory message exchange allows performance improvement. Just use JMS if it is really necessary
- JMS has a proprietary wire protocol, requires yet more infrastructure; HTTP provides proven scalability and interoperability;
- Avoid depending on one vendor only so stick with open standards, open-source: portability of skills of developers
Posted by Daniel @ 2:42 PM 0 comments
Labels: Java, javaOne, javaone_2009, javaone2009
JavaOne 2009: "Bug-free" code on Java 7?
Preventing Bugs with pluggable type checking by Michael Ernst
- New Feature in Java 7
- The motivation of the presentation is to help people to design a type system to solve a specific problem
- Java 7 has a new annotation syntax: e.g. List <@NonNull String> strings; or myGraph = (@Immutable Graph) tmpGraph;
- Type Qualifiers improves documentation, find bugs in programs, guarantee the absence of errors and reduces the need for assertions and run-time checks
- Checkers are designed as compiler plug-ins (i.e. annotation processors) and use familiar messages; many checkers are being implementd in Java 7
- Michael said: "If you want to find some bugs in your code, Findbugs is ok. If you are a developer who cares, you'll want to find ALL your bugs, and this is the tool for that"
- It is possible to create your own type checking annotations, and he showed us how to write a quick one to avoid SQL injection in our code that access the database
- Michael showed some statistics comparing FindBugs and the new Java 7 type checking; type checking found 8 bugs (20000 LOC) and findBugs none; on the other hand, type chacking demanded 35 annotations to be written throughout the code
- It is said that annotations like these would clutter your code, but in my opinion it is a good trade-off for having a "bug-free" code
- Another interesting option that Type Checking offers, is that one can start doing the annotation of the code on a per-module or per-class basis, i.e. start with the most important parts of the code
Posted by Daniel @ 1:03 PM 0 comments
Labels: Java, javaOne, javaone_2009, javaone2009
Tuesday, June 2, 2009
JavaOne 2009: Clojures for the JVM by Rich Hickey
- Fundamentals: it is a dynamic language and a new LISP, Functional, Supporting Concurrency, Compiles to JVM bytecode, not OO
- Why not OO? Because OO encourages mutable state and Mutable stateful objects are the new "spaghetti code". His words, not mine! :)
- Supports a REPL (read-eval-print-loop)
- Load/change code in running program
- On Data Types it has, for example, Arbitrary Precision Integers, Ratios (no precision loss?), doubles, BigDecimals...
- On Composite Data Structures it has, for example, Lists, Vectors, Maps, Sets and everything nests
- Data structures are the code, not text-based syntax and everything is an expression
- All data structures are immutable; performance problems are avoided by two rules: new versions are not full copies and make use of a structural sharing of data (this last one is kind of hard to put in a few words here)
- Abstraction-based library built on concrete classes for structures with a Java Interface
- Clojure supports prallel computation, mostly because it focuses on concurrency, which is made easy by using immutable data; no locks needed
- The only thing that mutate are references themselves, in a controlled way
- Clojure uses MVCC - Multiversion Concurrency Control through the command dosync which is the transactional control done by databases
- Clojure integration with Java is natural beacause the data types are the same as Java; it has debugging support and all the Java bytecode infrastructure works with Closure
Why is it that everytime I see a brand new language or programming paradigm it reminds me of everything I learned 15 years ago at College? My words, not his! :)
Posted by Daniel @ 5:41 PM 0 comments
Labels: Clojure, Java, javaOne, javaone_2009, javaone2009
JavaOne 2009: EJB 3.1Overview
EJB 3.1 Technology Overview by Kenneth Saks
He spoke about the EJB 3.1 Spec which should be ready by end of the year.
- Session Bean with Local Business Interface; "No-interface" view client - it calls directly the business method from the EJB and it is not generated by the API
- Java EE Platform packaging will change to a simplified version; same behavior withoud need for ejb-jar
- EJB 3.1 "lite" API; a small subset of EJB 3.1 API required by JavaEE pPlatform 6 Web Profile, which is made possible by the simplified .war packaging mentioned earlier (local session beans, transactions, declarative security and interceptors)
- Portable global JNDI Names for Remote and Local session beans; portable naming syntax with unique names defined globally, within application and per module
- EJB Component Testing tries to solve the problem that it is hard to test Local session beans and client-side EJB component; it is possible to run the EJB in an embeddable container in regular JSE
- New features: Singletons (new Session Bean component type, Container and Bean Managed Concurrency), Startup/shutdown callbacks, Caledar-based timers (created progammatically or automatically), Asynchronous session bean invocations (available for Stateful, Stateless and Singleton beans), JAX-RS Integration
Glassfish v3 has the implementation for all these new features.
Posted by Daniel @ 3:53 PM 0 comments
Labels: Java, javaOne, javaone_2009, javaone2009
JavaOne 2009 General Session
The Opening General Session for Java One 2009 has just begun. We had presentations from Verizon, Intel, Sun itself with JavaFx. The first two were a little bit commercial, but the JavaFX quick presentation and introduction was interesting in the way that it showed what this technology is able to do!!
Posted by Daniel @ 1:28 PM 0 comments
Labels: javaOne, javaone_2009, javaone2009
Saturday, May 16, 2009
Lower Case, Upper Case and Capitalize in Ruby
Ruby has some very straightforward methods to change the case of your strings.
Here are some of them:
"HoMer".downcase # returns homer
"lisa".upcase # returns LISA
"margie".capitalize # returns Margie
"BaRt".swapcase #returns bArT
Just a quick one! :)
Find this article also on definenull.com.
Posted by Daniel @ 2:15 AM 0 comments
Labels: capitalize, downcase, lower case, rails, ruby, rubyonrails, swapcase, upper case, uppercase
Search an Array in Ruby
If you want to search for a value in an array in Ruby you could do something like this:
array = ['Bart','Lisa','Maggie']
array.include?('Homer') # returns false
array.include?('Lisa') # returns true
Another possibility is to do this:
array = ['Bart','Lisa','Maggie']
array.index 'Homer' # returns nil
array.index 'Lisa' # returns 1
Both methods should work for searching an array.
For more information check the Ruby API for the Array Class.
Cheers,
Dani
Find this article also on definenull.com.
Posted by Daniel @ 1:59 AM 2 comments
Labels: array, find, include, index, rails, ruby, rubyonrails, search
Wednesday, April 29, 2009
Which binary file am I running in Cygwin?
If you want to find out which of the binary versions of some file you are running under Cygwin you can try two commands: "which" and "type".type -a ruby
Should return something similar to:
16:55:17 ~$ type -a ruby
ruby is /usr/bin/ruby
ruby is /bin/ruby
ruby is /usr/bin/ruby
So would this:
which ruby
Cheers!
Find this article also on definenull.com.
Posted by Daniel @ 12:14 AM 0 comments
Labels: Cygwin
Saturday, April 18, 2009
Ruby on Rails Model Auto Completer
When developing web applications nowadays, caring about user interaction is mandatory. Using Ajax technology to allow your system to show information without reloading the whole page is one of the features every web user is getting used to.
One good example on this kind of interaction are those text boxes with auto completion. While the user types some name the system will automatically search for matches to those names in the database, offering sugestions on possible existing values.However, if such a text edit box is part of a form you also need to populate some hidden fields with the returned ids for the text you found on the database.
Ruby offers a text edit option that will perform auto completion by searching in the database, but it does not populate another field.
The model_auto_completer plugin is perfect for this job! If you have, for example the following models, you can type (and lookup) the name of a contact directly in the Transaction form:
class Contact < ActiveRecord::Base
end
class Transaction < ActiveRecord::Base
belongs_to :contact
end
script/plugin install http://model-ac.rubyforge.org/svn/trunk/vendor/plugins/model_auto_completer
After doing this go ahead and install the default auto_complete plugin from rails:
script/plugin install auto_complete
Then, in your view file, add the call to the method that will render the text_edit for the contact name and the one for the contact_id (which is hidden) will also be automatically added:
<%= belongs_to_auto_completer :transaction, :contact, :name %>
The method in the Transaction controller which gets called by the ajax method must be named accodingly:def auto_complete_belongs_to_for_transaction_contact_name
@contacts = Contact.find(
:all,
:conditions => ['LOWER(name) LIKE ?', "%#{params[:contact][:name]}%"],
:limit => 10
)
render :inline => '<%= model_auto_completer_result(@contacts, :name) %>'
end
One problem you might run into is to get an error messsage regarding the forgery protection. Something like this:
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
c:/ruby/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/request_forgery_protection.rb:79:in `verify_authenticity_token'
This message is telling you that the POST command you are sending is not being understood by the gorgery protection mechanism. To overcome this problem, just add the command below to your Transactions Controller: protect_from_forgery :except => [:auto_complete_belongs_to_for_transaction_contact_name]
Well, this is pretty much everything you need to make this plugin work. Have fun!!
You find this article also on definenull.com.
Posted by Daniel @ 2:30 AM 0 comments
Labels: auto complete, model, model_auto_completer, rails, ror, ruby, ruby on rails
Thursday, April 9, 2009
Using forms in Ruby on Rails
I found this great guide on how to use forms in Ruby on Rails.
It is quite complete and it comes with a lot of examples on how to create HTML form entries using Ruby on Rails.
Posted by Daniel @ 4:00 AM 0 comments
Labels: rails, ror, ruby, ruby on rails, rubyonrails
Google App Engine with Java
Google now offers the possibility to use Java for its App Engine!
Posted by Daniel @ 2:43 AM 0 comments
Thursday, April 2, 2009
Running tests in the command line on Ruby on Rails
I normally run the test suite for my Ruby on Rails projects using the Netbeans test interface.
Unfortunately this interface is only useful to run the whole suite. It does not offer (as it does for Java) the possibility to run a single test class or a single test from a test class.
When I need to this I just go to the command line and type:ruby test/functional/accounts_controller_test.rb
But what if I need to run one single test from this test class?
No problem, it is actually very easy. Just type:ruby test/functional/accounts_controller_test.rb --name test_should_create_account
That's it!
You can also find this article on definenull.com.
Posted by Daniel @ 11:41 PM 0 comments
Labels: ror, ruby, ruby on rails, rubyonrails, test, testing
Tuesday, March 31, 2009
Ruby on Rails Order By Using Associated Model
It is very easy to use an 'order by' clause in a model in Ruby on Rails. Supposing you have a Category model it's as simple as doing this:
@categories = Category.find(:all, :order => 'title')
But what if I need to order by the title of the subcategories after ordering by the categories title?
Using the category_id does not work, because it is almost sure that the categories will not be added in alphabetical order, so the command below does not work for me:
@subcategories = Subcategory.find(:all, :order => 'category_id,title')
And neither would work the sentence below, because the resulting SQL query will fail:
@subcategories = Subcategory.find(:all, :order => 'category.title, title')
This last command will fail because rails does not recognize the Category model inside the subcategories model. So all you have to do is tell Rails that you want to include another model in the query, and this is done using the :include option from the find method:
@categories = Category.find(:all,:include => :subcategories, :order => 'categories.title, subcategories .title')
It is easy after you find out how! ;)
This article can also be found on definenull.com.
Posted by Daniel @ 11:27 PM 1 comments
Labels: model, order by, rails, ror, ruby, ruby on rails, SQL
Friday, March 13, 2009
Sun Java One 2009 - topics released
Sun has released the topics for the Java One 2009 Conference, with four high-level areas: Mobility, Rich Media Applications and Interactive Content, Services and Core Content.
It will happen in San Francisco in June, 2nd-5th.
Posted by Daniel @ 4:30 PM 0 comments
Labels: Conference, Java, javaOne, sun
Saturday, March 7, 2009
Cygwin personal setup
Some time ago I wrote a post on how to setup the looks of your Cygwin bash shell using rxvt. Well, I normally add a few more settings to my environment just to make it more useful.
I add the following lines to my ~/.bash_profile with some aliases to make it easier with directory surfing.
alias ls='ls --color=auto'
alias ll='ls -lsa'
alias l='ls -la'
It is also useful to set some preferences for vi, and this is done in the ~/.vimrc file:
set textwidth=70 background=dark
set is hls ic scs aw ruler ls=2
syntax on
I also like to create symbolic links at my home dir to allow me to have quick access to some of the original and most used folders in Windows, like:
ln -s /cygdrive/c/Documents\ and\ Settings/dambrosio/Desktop/ windesk
ln -s /cygdrive/c/Documents\ and\ Settings/dambrosio/Meus\ documentos/ mydocs
Some other useful symbolic links might be the ones pointing to your drives, because it is faster to type
cd ~/c
than cd /cygdrive/c
Quick and clean! ;)
Find this article also on definenull.com.
Posted by Daniel @ 5:45 PM 0 comments
Tuesday, March 3, 2009
Change Default Date Format in Ruby on Rails
Just a quick and simple hint!
If you need to set the default formatting of dates throughout your whole application in Ruby on Rails, just add the following line to your "<your application>/config/environment.rb"
my_date_formats = { :default => '%d/%m/%Y' }
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(my_date_formats)
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(my_date_formats)
Note 1: Rails uses this :default format when attempting to write dates do the database, so be sure that your DBMS is able to use this new format
Note 2: you will need to restart your server so the changes will be effective.Find this article also on Define Null.
Posted by Daniel @ 1:57 AM 0 comments
Labels: date_formats, format, rails, ruby, rubyonrails
Tuesday, February 10, 2009
Format Currency in Ruby on Rails
I was looking for a way to display currency data coming from the database as a long. I found out that Ruby on Rails has a buil-in Module Helper method called
ActionView::Helpers::NumberHelper:number_to_currency which allows one to format a number according to some options:
- :precision - Sets the level of precision (defaults to 2).
- :unit - Sets the denomination of the currency (defaults to "$").
- :separator - Sets the separator between the units (defaults to ".").
- :delimiter - Sets the thousands delimiter (defaults to ",").
- :format - Sets the format of the output string (defaults to "%u%n").
Using this method, we could write something like this:
<%=h number_to_currency @transaction.value, :unit => 'R$', :separator => ",", :delimiter => "." %>
This would work fine, but in this solution we are breaking the DRY (Don't Repeat Yourself) rule, because I would need to set the same parameters in every place I was displaying currency values.
A better solution would be to have a helper method which I could use in every piece of code where I need a currency. So I came up with the solution below, which consists in writing my own helper method in app/helpers/application_helper.rb: module ApplicationHelper
number_to_currency(number,:delimiter => ".", :unit => "R$ ",:separator => ",")
end
end
Now, in my templates I should write something like this:
<%=h real_currency @transaction.value %>
Ain't that easier?
Find this article also on Define Null.
Posted by Daniel @ 1:59 AM 2 comments
Labels: currency, format, rails, ruby, rubyonrails
Tuesday, January 20, 2009
Top 25 most dangerous programming errors
A colleague at work just sent me this interesting list of the most dangerous programming errors.
I think it a very thorough list considering the type of error the average programmer does and normally does not have the time (or interest, or knowledge, or whatever... :)) to care on a daily basis.
The comments on what each error is and how to avoid are quite useful!
Enjoy it!
Posted by Daniel @ 2:32 AM 0 comments
Thursday, January 15, 2009
Scrum - info and links for starters
Being a Certified Scrum Master and working with Scrum for over a year, people quite often come to me asking for directions about information on Scrum.
I created this post to keep this information handy for me next time I am asked for this and to share it with the community.
Is "the home of the Certified ScrumMasters organization, offering training, gatherings, information, and materials regarding Scrum, including frequent articles". Amongst their resources you can find this brief overview of Scrum and
- Videos
- Books
Have fun!
Posted by Daniel @ 11:07 AM 0 comments
Labels: Agile, Agile Scrum, Scrum, Software Development
Tuesday, January 13, 2009
Take Care of your passwords
Now that even Barack Obama had his twitter password hacked by some kids using a brute force attack using a simple dictionary, makes a lot of sense to spread the word: take good care of your passwords.
There is an interesting site called passwordmeter.com with some functions that check how strong is a password. Try using it before adopting a new password.
The site whatsmypass just published a list with the worst 500 passwords ever. Do you use any of those? :)
Here are the top 10:
- 123456
- password
- 12345678
- 1234
- pussy
- 12345
- dragon
- qwerty
- 696969
- mustang
By the way, this list was compiled in a book by Mark Burnett called "Top 500 Worst Passwords Of All Time".
Posted by Daniel @ 1:22 AM 0 comments
Saturday, January 10, 2009
Change Netbeans 6.5 IDE language
I downloaded and installed today the Netbeans 6.5 and for my surprise its IDE was in Portuguese. I prefer using the IDE in English, so I tried to change it using the way I remembered from previous versions, i.e. at the Tools menu. As it happens, it is not possible to change the language of the IDE through the interface, because it is based on the locale of your machine.
After some experimenting and searching I found out that it is necessary to pass the locale to the IDE and force it to use something different from your system. So, go to the shortcut which starts your IDE (yep, using Windows here) and pass "--locale en:US" in the command line.
It should look like something like this:
"C:\Program Files\NetBeans 6.5\bin\netbeans.exe" --locale en:US
Posted by Daniel @ 6:59 PM 2 comments