Monday, September 17, 2007

Why Agile Projects Fail?

This Article posted in InfoQ discusses about the reasons some projects who adopt Agile Methodology fail.

Most reasons end up concluding: people are the problem. Not the process, not the tools. People.

Is this really true? People who "lead" an Agile Project to failure would lead a RUP Project to failure as well?

In my opinion, the Agilists set their basis on a competence that is harder and harder to find through professionals: Proactivity! And I don't mean that only to the developers or Project Managers. Almost every colleague of mine, no matter where he/she works, complains about lack of proactivity in their team, boss, colleagues etc.

According to the Websters Dictionary:
Proactive: "acting in anticipation of future problems, needs, or changes". Everything you need from your team in one sentence.

Technical skills may be trained. Proactivity may not. It belongs to the human being and his profile. Either you have it, or you don't. Learning how to identify this competence still while interviewing candidates is fundamental for the team development. Learn how to do it, and you will build a great team!

Cheers,
Dani

Agile Development - Free Tool

Hey folks,

Just started trying this tool to manage agile software development.
It is free up to a 5 team members.

The name is Mingle, and you can find it here.

Cheers,
Dani

Friday, August 24, 2007

web.xml specification header 2.3 or 2.4

This is a quick tip. There are two versions of the servlet specification in use now: 2.3 and 2.4.
The header for the web.xml file will be different in both cases.
In version 2.3 it is used a DTD do specify the XML format, and it is as follows:



<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>



In version 2.4 it is used a Schema to specify the XML Format. Here it is the format:


<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">

Sunday, August 12, 2007

Struts in development mode

Struts has a very nice feature which increases development productivity. It is called development mode (or dev mode) and it forces reloading of configuration files and resource bundles, it raises the debugging level etc. As you, smart developer who reads this blog, might have noticed it has an impact on performance, so use it wisely.
It is very easy to tell struts that you want it running in dev mode. You may set a property in struts.properties like this:

devMode=true

It is also possible to set this same property in the struts.xml file:
<constant name="struts.devMode" value="true" />

Struts 2 wired by Spring

Struts 2 is a framework for aiding Java Developers into building their web applications, using Inversion of Control (IoC) and MVC Architecture for a multi-tier architecture.

In this post we will see how to wire your action and service classes in Struts 2 using the spring framework.

To start, if you are using Maven there is a dependency you need to add to your pom file.


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>2.0.6</version>
<scope>compile</scope>
</dependency>


When this is done, it is necessary to add a listener to the WEB-INF/web.xml file. This is a spring listener, used to intercept calls and redirect them to the Application Context.

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>


Now, we will need to create the Application Context file for Spring. It will use the configuration information in this file to inject the necessary beans into each needed class. The file format is like below and it should be called WEB-INF/applicationContext.xml. I added some example beans to explain how Struts will later identify these beans and inject them into the Actions being called by the framework.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">


<bean id="personService" class="my.service.PersonServiceImpl" />

<bean id="personAction" scope="prototype"
class="my.web.action.PersonAction">
<constructor-arg ref="personService" />
</bean>

</beans>


Last, but not least it is necessary to setup the struts.xml file to tell the framework that it should use struts' object factory. The example below will show the entries you need to add to struts.xml file. Setting "struts.objectFactory" to "spring" will force Struts to instantiate the actions using Spring, injecting all the defined dependencies on applicationContext.xml.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.devMode" value="true" />

<package name="person" extends="struts-default">

<action name="list" method="execute" class="personAction">
<result>pages/list.jsp</result>
<result name="input">pages/list.jsp</result>
</action>

....


</package>

</struts>


The "class" attribute for each action alias is set to "personAction", which is the bean id that we defined on applicationContext.xml for the PersonAction class. This is all that is needed to make Struts work with Spring.

Have fun!

Maven Download Sources

When using maven, it normally downloads only the binaries from the dependencies your project has.
It is possible, with simple commands, to also download the source and/or documentation from the dependencies you are interested in.

To download sources:

mvn [goal] -DdownloadSources=true


To download javadocs:
mvn [goal] -DdownloadJavadocs=true

Maven Eclipse

The maven eclipse plugin is provided for those who have a ready .pom file for a maven project and want to start using eclipse as the IDE for the project.

The command is as simple as running:

mvn eclipse:eclipse

This command have a number of parameters, but one of the most interesting ones would be the one which allows to create a WTP (Web Tools Platform) aware eclipse project.

mvn eclipse:eclipse -Dwtpversion=1.0

This command will create an eclipse project with WTP 1.0 support.

Friday, August 3, 2007

Adding Repositories to Maven 2

Maven uses on-line repositories to find the dependencies you set in your pom file. By default, maven uses the repository specified in the

If you want to use other repositories, you are able to do so by adding a ~/.m2/settings.xml file. This file should be provided in the following format:


<settings>
<profiles>
<profile>
<id>standard-extra-repos</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>jboss</id>
<url>http://repository.jboss.com/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>jboss-snapshot</id>
<url>http://snapshots.jboss.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>jboss-plugins</id>
<url>http://repository.jboss.com/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>jboss-snapshot-plugins</id>
<url>http://snapshots.jboss.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</settings>


Some repositories I've collected and you might be interested in using, because some artifacts are available only through some of these repositories and not all of them. It is important to remember that the more repositories you add, the slower will be your build, so use them with wisely.

Repository
http://www.ibiblio.org/
http://download.java.net/maven/2
http://repo1.maven.org/maven2
http://repository.jboss.com/maven2
http://maven.apache.org/
http://mojo.codehaus.org/


Snapshot
http://snapshots.jboss.org/maven2
http://people.apache.org/repo/m2-snapshot-repository
http://snapshots.maven.codehaus.org/maven2
http://snapshots.repository.codehaus.org


If you want to download snapshot version of maven plugins, there is a page which explains how to setup your settings.xml file.

Using HSQLDB database - the basics

HSQLDB is a powerful database engine. It is normally used to provided an embedded database functionality for java applications.

It is as simple as downloading a zip file, extracting it into your system and you have a functioning RDBMS.

After extracting the zip file, you should have the following (resumed) structure in your system:


/hsqldb
/bin (scripts for running the server and utilities)
/demo (scripts and applet examples)
/doc (guess what?)
/lib (all binaries - including hsqldb.jar)
/src (all source code)
index.html (documentation about the distribution)


The hsqldb.jar is everything you need to run the database application. It contains the RDBMS, the driver and some tools (the database manager, the query tool and the command line tool).

Running the tools

To run some of the tools, enter the lib folder and run the following command, which will run the database manager.

java -cp hsqldb.jar org.hsqldb.util.DatabaseManager


The main classes for the tools deployed with the hqsldb.jar are:


  • org.hsqldb.util.DatabaseManager

  • org.hsqldb.util.DatabaseManagerSwing

  • org.hsqldb.util.Transfer

  • org.hsqldb.util.QueryTool

  • org.hsqldb.util.SqlTool



HSQLDB may run in standalone (in-process) or server mode. There are three server modes, based on the protocol used for communications between the client and server and they are HSQLDB Server, Web Server and Servlet. It is also possible to run HSQLDB in a way that the database is not persistent and exists entirely in random access memory.

The default user and password for connecting to the database is "sa" / "sa".

For more information on this powerful tool, read the online manuals or the documentation provided with the distribution zip file in the doc folder.

Sunday, July 15, 2007

Debugging Struts Information

Some time ago I posted an article about debugging information in a JSP page. Struts tags have an interesting tag with almost the same functionality I wrote before.

It is very simple to use. All you need, is add the tag below to your code, provided all the jstl information are correct (in web.xml and/or standard.jar and/or jstl.jar).


<%@ taglib prefix="s" uri="/struts-tags" %>
...
<s:debug/>

Choose Java Version for Maven compile

It is possible to set the version of the jdk one wants to use when compiling code using maven.

This might be mandatory if your code uses generics or annotations. So here is the code you should add to your pom.xml.


<build>
...
 <plugins>
...
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.5</source>
     <target>1.5</target>
    </configuration>
   </plugin>
 </plugins>
...
</build>
...

Friday, June 8, 2007

Build Struts 2 Application Using Maven 2

I really think that using Maven as tool to build Java Projects is simply great, but if there is one thing I hate is searching ibiblio for the dependencies I need for my project. So I will post below the path for the main components one will need to get started with Struts 2 on his project.

By default, Maven will look for the dependencies on its central repository http://repo1.maven.org/maven2. It is possible to configure the repositories where you want maven to look up for files. These two below are some alternative repositories where you can try to find components you need. In the apache repository below is possible to find the SNAPSHOT version of the components.

Just add the code below into your pom file.


<repositories>
  <repository>
    <id>ibiblio</id>
    <name>iBiblio Maven2 Repository</name>
    <url>http://www.ibiblio.org/maven2</url>
  </repository>
  <repository>
    <id>apache-repo</id>
    <name>Apache Repository</name>
    <url>http://people.apache.org/repo/m2-snapshot-repository</url>
  </repository>
</repositories>


Check the official Maven site about how to setup multiple repositories.

Now, we can reach for those components! :)
As advised by the struts team, the minimum set of components one might need is below.

  • struts2-core.jar

  • xwork.jar

  • ognl.jar

  • freemarker.jar

  • commons-logging.jar


Fortunately, to download all of them automagically, all you need to add to your pom files are the lines below:


  <dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>2.0.6</version>
  </dependency>


Wanna do this even faster? Use maven archetypes to create a struts2-aware project! ;)


mvn archetype:create -DgroupId=tutorial \
    -DartifactId=tutorial \
    -DarchetypeGroupId=org.apache.struts \
    -DarchetypeArtifactId=struts2-archetype-starter \
    -DarchetypeVersion=2.0.5-SNAPSHOT \
    -DremoteRepositories=http://people.apache.org/repo/m2-snapshot-repository

Monday, April 23, 2007

Quiclky Create a Maven-aware project

If you are (or want to start) using Maven as a build tool for your project, a quick way to start is to use an archetype to create a pom.xml and the default folder structure. This is the command:


mvn archetype:create

-DarchetypeGroupId=[archetype-groupId]

-DarchetypeArtifactId=[archetype-artifactId]

-DarchetypeVersion=[archetype-version]

-DgroupId=[my.groupid]

-DartifactId=[my-artifactId]

Friday, April 13, 2007

Debugging Information passed to a JSP Page

Well, scriptlets inside a JSP page Suck. Alright, I agree!!
But sometimes it is necessary to check what are the parameters in the request or session scopes reaching your jsp page.

I found this code somewhere on the web sometime ago. One day (yeah, right) I will right a version of it using JSTL tags, but for now I allow myself to add this scriptlet in one of the pages that are included everywhere in my system. As I use Struts Tiles in my system, I do have a bottom.jsp page which is included everywhere.

So I leave the debug attribute in false state until I need to debug on page or another. At this moment, all I have to do is turn on the debug information in my page by setting the attribute to true.

Below is the scriptlet and page includes that should be added to the page where you want the debug information to be displayed.


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page import="java.util.*" %>
<%@ page import="org.apache.struts.*" %>

<%@ page import="org.apache.struts.util.*" %>
<%@ page import="org.apache.struts.action.*" %>

<%
// Print all attributes in the request object
out.println("<p><b>All Attributes in request scope:</b>");
Enumeration paramNames = request.getAttributeNames();
while (paramNames.hasMoreElements()) {
String name = (String) paramNames.nextElement();
Object values = request.getAttribute(name);
out.println("<br> " + name + ":" + values);
}

// Print all attributes in the session object
out.println("<p><b>All Attributes in session scope:</b>");
paramNames = session.getAttributeNames();
while (paramNames.hasMoreElements()) {
String name = (String) paramNames.nextElement();
Object values = session.getAttribute(name);
out.println("<br> " + name + ":" + values);
}

out.println("<p><b>Data in ActionMessages:</b>");

// Get the ActionMessages
Object o = request.getAttribute(Globals.MESSAGE_KEY);
if (o != null) {
ActionMessages ae = (ActionMessages)o;

// Get the locale and message resources bundle
Locale locale =
(Locale)session.getAttribute(Globals.LOCALE_KEY);
MessageResources messages =
(MessageResources)request.getAttribute
(Globals.MESSAGES_KEY);

// Loop thru all the labels in the ActionMessage's
for (Iterator i = ae.properties(); i.hasNext();) {
String property = (String)i.next();
out.println("<br>property " + property + ": ");

// Get all messages for this label
for (Iterator it = ae.get(property); it.hasNext();) {
ActionMessage a = (ActionMessage)it.next();
String key = a.getKey();
Object[] values = a.getValues();
out.println(" [key=" + key +
", message=" +
messages.getMessage(locale,key,values) +
"]");
}
}
}
%>


Tuesday, April 10, 2007

EJB3 QL: Using the COUNT function

If you are using EJB3 Query Language to build your application, you will probably need to use some functions other than the regular SELECT statements and logical WHERE clauses. One of the most simplest of these functions is the COUNT function.
The syntax for the COUNT function is very simple, and it receives only a parameter which is the identifier to be count, as in:

SELECT COUNT(c) FROM Customers AS c WHERE c.address.country = 'BR'


This query will count all the Customers who live in Brazil.

The COUNT function can be used with an identifier, in which case it always counts entities (as the example above demonstrates), or with path expressions but this last one can always be converted into an expression that counts entities only by managing the conditions in the WHERE clause.

Below is an example on how you could write a piece of code that would count the Patients from a medical database, depending on which Clinic they are registered to:


Query query = entityManager.createQuery("SELECT COUNT (p) FROM Patients p WHERE p.clinic.idtClinic = :idtClinic");
query.setParameter("idtClinic", idtClinic);
return (Long)query.getSingleResult();


I will write about other EJB QL functions later! :)

CU!

Sunday, March 11, 2007

SVN Keywords

One useful feature that subversion and many other Versioning Systems offer for developers is the ability to include keywords in text files stored in the repository.

These keywords get replaced when some action is done on them by the server. This book excerpt (reproduced below) documents some keyword supported by subversion.

The keyword to be replaced is identified by an anchor in the text with the keyword name surrounded by two '$keywordName$.

Subversion defines the list of keywords available for substitution. That list contains the following five keywords, some of which have shorter aliases that you can also use:

LastChangedDate

This keyword describes the last time the file was known to have been changed in the repository, and looks something like $LastChangedDate: 2002-07-22 21:42:37 -0700 (Mon, 22 Jul 2002) $. It may be abbreviated as Date.

LastChangedRevision

This keyword describes the last known revision in which this file changed in the repository, and looks something like $LastChangedRevision: 144 $. It may be abbreviated as Revision or Rev.

LastChangedBy

This keyword describes the last known user to change this file in the repository, and looks something like $LastChangedBy: harry $. It may be abbreviated as Author.

HeadURL

This keyword describes the full URL to the latest version of the file in the repository, and looks something like $HeadURL: http://svn.collab.net/repos/trunk/README $. It may be abbreviated as URL.

Id

This keyword is a compressed combination of the other keywords. Its substitution looks something like $Id: calc.c 148 2002-07-28 21:30:43Z sally $, and is interpreted to mean that the file calc.c was last changed in revision 148 on the evening of July 28, 2002 by the user sally.
as in $keywordName$.

Have fun!

UPDATE on march/2009
Normally it would be necessary to set the properties on every single file of your system so the replacement of these props would happen. However, there is an easier way to do this, which is set the auto-props property in your environment.

In folder "C:\Documents and Settings\[your_username]\Application Data\Subversion" you will find a file named config (with no extension). In this file there should be a property "enable-auto-props" commented out. Remove the comment from this line so it looks like this:


### Set enable-auto-props to 'yes' to enable automatic properties
### for 'svn add' and 'svn import', it defaults to 'no'.
### Automatic properties are defined in the section 'auto-props'.
enable-auto-props = yes

Then, on the same file, find the section [auto-props] and add a line at the end. If you want the replacement to happen only in your java files, add this:


*.java = svn:keywords LastChangedDate

Monday, February 26, 2007

Install a jar file into maven's local repository

Sometimes, while using maven to build your projects, it is necessary to add a needed jar file directly into your local repository. This should not be a need if you have a remote repository correctly setup, but it might be useful if it is a too bureaucratic task or any other reason.

It is as simple as this. Having the file to be installed in your local repository in the local folder, issue the command below to install it.

mvn install:install-file -DgroupId=<MVN_GROUPID> -DartifactId=<MVN_ARTIFACTID> -Dversion=<MVN_VERSION> -Dpackaging=jar -Dfile=<JAR_FILE_TO_INSTALL>

Could be useful! ;)

Sunday, February 11, 2007

Find the name of your session bean in JBoss

If you are writing JEE applications, you will most likely write a Session Bean to provide your View Tier with the services it need. This Session Bean is reached by the client application through a service called JNDI.

The problem is that each Application Server uses a different JNDI provider and this makes portability very hard to achieve. I wrote the code below to allow me to access the JNDI service and find my Session Bean. Please note that this would be much better placed in the container configuration file and not in the code, as it is here.

protected static Context getInitialContext( ) throws javax.naming.NamingException {
  Properties p = new Properties( );
  p.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
  p.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
  p.put(Context.PROVIDER_URL, "jnp://localhost:1099");
  return new javax.naming.InitialContext(p);
}

This method will return a java.naming.Context object which can be used for the lookup on the service, like this:


PatientServices patientServices = (PatientServices)jndiContext.lookup("PatientBean/remote");



And how can you find the name under which your bean has been published on the application server? Well, in JBoss all you need to do is access the jmx-console (default URL is http://localhost:8080/jmx-console/). On the jboss session from this page, find the JNDIView service. Click on it and a new page will display on your browser.
On this new page there will be a java.lang.String list() MBean operation, and clicking on the invoke button the names of all available JNDI names will be shown on a tree-like structure which composes the name under which your Session Bean is registered on the JNDI service.

Maven Profiles

I was struggling with some different configuration files for my development and production environment. As a "weekend-free-time-developer-now-that-I-changed-into-management", my development environment is restricted. So I use the same instance of MySQL for the production database and run some tests on the same server with a different schema and configuration.

Using maven as a build/management tool improved my a lot my performance, but these different environments still gave me some headache. So I decided to leave laziness aside and configure some profiles in my pom files.

Maven profiles allow you to prepare different sets of configuration. There are for different types of profiles, defined in different files and with different purposes:

  1. Per Project: Defined in the POM itself (pom.xml).
  2. Per User: Defined in the Maven-settings (%USER_HOME%/.m2/settings.xml).
  3. Global: Defined in the global maven-settings (%M2_HOME%/conf/settings.xml).
  4. Profile descriptor: a descriptor located in project basedir (profiles.xml)


I decided to use the type number 1, which is a Per-Project configuration type, and unlike number 4 (which has a restricted scope) which is also a Per-Project configuration type it has the ability to change a lot of the project settings because it is in the same pom file as the projects' specifications themselves.

For starters, I wanted to have different jboss' data source xml files for production and development environments. As Maven works with a hierarchy of configuration files I figures the less intrusive way to set the build configuration was to have different folders for each environment. So where I previously had /src/main/resources/WEB-INF now I would have /src/main/resources/development/WEB-INF and /src/main/resources/production/WEB-INF. With the original single path, Maven did not need any special configuration to find my data source xml files (I love "convention over configuration"). With the 2 new folders, I had to add another layer to the hierarchy of Maven's configuration files and this layer would be the profiles.

In my pom.xml, I added a profiles section, obviously enough marked by the tag <profiles>. Here is what I added to my original pom.xml.
  <profiles>
    <profile>
      <id>env-dev</id>
      <build>
        <resources>
          <resource>
            <directory>src/main/resources/development</directory>
          </resource>
        </resources>
      </build>
      <activation>
        <property>
          <name>env-dev</name>
        </property>
      </activation>
    </profile>

    <profile>
      <id>env-prod</id>
      <build>
        <resources>
          <resource>
            <directory>src/main/resources/production</directory>
          </resource>
        </resources>
      </build>
      <activation>
        <property>
          <name>env-prod</name>
        </property>
      </activation>
    </profile>
        
  </profiles>

Now, you can tell maven to build based on different profiles. Where you normally would enter a command like mvn install now you should change to:

mvn install -P env-dev for development environment

OR

mvn install -P env-prod for production environment

After doing this, I was wondering... Which profile will maven choose to execute the build if I do not explicitly tell it?

That is very easy to check! Run the command:
mvn help:active-profiles

It will show you that there are no active profiles, but it will (wrongly IMHO) add BOTH (production and development) folders to your final build, and will not realize that those are actual resource folders.

One simple solution for this issue is to tell maven which profile should be used by default. I modified the profiles tag content to use the production environment as the default one, so this will force me during development to always add the "-P env-dev" while I am testing/developing and this should make me used to always tell maven what I really want. The way to tell maven which one is the default active profile is in bold below.

    <profile>
      <id>env-prod</id>
      <build>
        <resources>
          <resource>
            <directory>src/main/resources/production</directory>
          </resource>
        </resources>
      </build>
      <activation>
        <activeByDefault>true</activeByDefault>
        <property>
          <name>env-prod</name>
        </property>
      </activation>
    </profile>

Now, if you run mvn help:active-profiles again you will see that the env-prod is being used, which is the same as running mvn help:active-profiles -P env-prod.

$ mvn help:active-profiles
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'help'.
[INFO] ----------------------------------------------------------------------------
[INFO] Building Fisio EJB Component
[INFO] task-segment: [help:active-profiles] (aggregator-style)
[INFO] ----------------------------------------------------------------------------
[INFO] [help:active-profiles]
[INFO]
Active Profiles for Project 'com.jc.fisio:fisio-ejb:ejb:0.1-SNAPSHOT':

The following profiles are active:

- env-prod (source: pom)



[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Sun Feb 11 18:13:13 BRST 2007
[INFO] Final Memory: 2M/5M
[INFO] ------------------------------------------------------------------------

Working with profiles is quite interesting, because it allows you to have multiple active profiles at the same time, providing a number of different combinations. It can be used to may purposes, like setting different application servers, web servers, snapshot version etc.

Tuesday, February 6, 2007

Setting Cygwin Bash Shell Looks

As I posted earlier, I like to use Cygwin as a *nix-like shell to use under Windows, because the command tool is IMHO terrible to use.

Cygwin has a lot of *nix functionalities which are not supported under windows default installation which forces you to install a big variety of software from different vendors.

Cygwin has its own port of bash shell, but on the default installation the looks are kind of dull. I use rxvt port for cygwin to start my shell and I used some configuration settings as suggested by this article.

So, with small changes to the suggestions of the author to have a larger buffer and the size of the started window I came with this .Xdefaults file. It shold be placed in your home directory.

! ~/.Xdefaults - X default resource settings
Rxvt*geometry: 120x60
Rxvt*background: #000020
Rxvt*foreground: #ffffbf
!Rxvt*borderColor: Blue
!Rxvt*scrollColor: Blue
!Rxvt*troughColor: Gray
Rxvt*scrollBar: True
Rxvt*scrollBar_right: True
Rxvt*font: Lucida Console-12
Rxvt*saveLines: 10000
Rxvt*loginShell: True
! VIM-like colors
Rxvt*color0: #000000
Rxvt*color1: #FFFFFF
Rxvt*color2: #00A800
Rxvt*color3: #FFFF00
Rxvt*color4: #0000A8
Rxvt*color5: #A800A8
Rxvt*color6: #00A8A8
Rxvt*color7: #D8D8D8
Rxvt*color8: #000000
Rxvt*color9: #FFFFFF
Rxvt*color10: #00A800
Rxvt*color11: #FFFF00
Rxvt*color12: #0000A8
Rxvt*color13: #A800A8
Rxvt*color14: #00A8A8
Rxvt*color15: #D8D8D8
! eof


Later I did another small change on the cygwin.bat file to use vim instead of vi as the default editor. The cygwin.bat file can be found on the installation directory of cygwin. Save the original file with another name and then replace it with the following content.

@echo off
C:
chdir C:\cygwin\bin
set EDITOR=vim
set VISUAL=vim
set CYGWIN=codepage:oem tty binmode title
rxvt -e bash --login -i


Now when you start cygwin, the shell window will look like the one on the right (click on it to see a larger version). Play around with the collor definitions on the .Xdefaults file to have a setup that pleases you. .Xdefaults gives a lot of possibilites and you can see some examples here, here and here.

Sunday, January 28, 2007

Using Apache as a Proxy for Tomcat Applications

I spent the day trying some configurations to make the integration between Apache HTTP Server and Tomcat.

The configuration that worked best for me basically was to setup a VirtualHost in Apache as a proxy with the same name as the application in Tomcat engine. As a resume, below tou will find some of the steps I went through and what I changed in the configuration files (I am using Apache 2.2 and Tomcat 5.5).

In Apache it is necessary to enable the mod_proxy Module and setup a NameVirtualHost. The httpd.conf (found in %APACHE_HOME%/conf) configuration file should be changed as below.

#Uncomment or add the lines below into the general session of your httpd.conf file.
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

# Add the Virtual Host for your application at the end of the file
NameVirtualHost *

<VirtualHost *>
  ServerAdmin serveradmin@domain.com
  DocumentRoot "C:/java/Tomcat5.5/webapps/"
  ServerName myapplication.domain.com
  ServerAlias *.myapplication.domain.com

  ProxyPass /foo-app http://localhost:8080/foo-app
  ProxyPassReverse /foo-app http://localhost:8080/foo-app
</VirtualHost>

After setting this file in your apache server, restart it and proceed to configuring the Tomcat Server, by editing the server.xml file (found in %CATALINA_HOME%/conf). Simply add the lines below at the end of the file, but inside the <server> tag.

<Service name="Tomcat-Apache">
    
    <Engine name="Apache" defaultHost="myapplication.domain.com" debug="0">
    <Host name="myapplication.domain.com" debug="0"
            appBase="c:/java/Tomcat5.5/webapps/foo-app" 
            unpackWARs="true" autoDeploy="true">

        <Context path="/foo-app" docBase="c:/java/Tomcat5.5/webapps/foo-app" debug="1" reloadable="true"/>
    </Host>

    </Engine>

  </Service>  

Now, open your browser and type the URL http://myapplication.domain.com/foo-app and you should be redirected to your application after passing by Apache and Tomcat.

Tomcat RMI Unmarshalling Exception

This is one of those posts that shows how frustrating sometimes the developer job can be! :)

I had a WAR component that was delivered successfully and worked fine in Jetty 6.0 rc2, but the same WAR file would not work under Tomcat 5.5. This application uses some session beans that are available in my JBoss Server. When I tried to execute the lookup() command in my client application running in Tomcat I had an exception thrown:


java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: java.net.MalformedURLException: no protocol:


Then I asked: Why? Why does it work in Jetty like a charm? Reading ahead at the message of the exception I noticed the MalformedURL message included this: "5.5/temp/0-fisio-web-1.0-SNAPSHOT/WEB-INF/classes/" which made me realize that this was just part of the full URL where my Tomcat Server was running. Searching through the net I found this post, which led me to this other post (and there is also this other post on this subject).

For my surprise this is a known bug since JDK 1.2, marked as WON´T FIX by SUN! Is it unbelievable or not??

There is a workaround suggested by Sun that says that one should use

file.toURI().toURL()

instead of

file.toURL()

but many times, this is not in our hands, as is my case because Tomcat is taking care of this for me, so unless me (or some other generous soul) change and test (and do a backward compatibility test which seems to be what is frightening SUN into not changing this behavior) this way of implementing the RMI communication, the best thing to avoid this problem is to install all your applications in a path that does not include white spaces or illegal characters.

Ignoring Files in Subversion

As I told before, I am using windows as a development environment, and one problem I was facing is that my GUI client SmartSVN was showing binary files produced by compilation (*.class, *.jar) and other uninteristing files do be versioned (like *.log).

I read documentation in the SVN Book Chapter 7, all sort of sites throughout the internet and there was only one solution that worked for me!

This Works - In folder "C:\Documents and Settings\[your_username]\Application Data\Subversion" you will find a file named config (with no extension). In this file there should be a section called [miscellany] and in there you will find the key "global-ignores". Uncomment it (remove the "#" char from the beginning) if necessary, add the extensions you would like to be ignored and you are good to go!

This DOES NOT work - Although it is the solution pointed out by the SVN Book and in many sites, changing the windows registry will not work for SmartSVN.

Still could not find a way to set the default global-ignores for the whole server.

Saturday, January 27, 2007

Tomcat Hot Deployment in Windows

The post about hot deploying an application to Tomcat using maven brought me a problem: the struts.jar was always left in the WEB-INF/lib of the exploded directory in the server.

This is a know issue with Tomcat working under Windows and I found an article which I quoted here below with the solution for this problem:

If you try to hot-deploy a WAR file to Tomcat on Windows, you often encounter file locking issues. Windows won’t let Tomcat undeploy the old app because files are locked by the OS. Here is a fix:

Edit %CATALINA_HOME%\conf\context.xml. Find the root <context> and add these two attributes:

<context antijarlocking="true" antiresourcelocking="true">

Now you can copy updated WAR files to your deploy directory and Tomcat will remove the old app and hot-deploy your new app. I’m using this on Tomcat 5.5.11 without any trouble.

There were other people having this kind of problem. Please note that this has nothing to do with using Maven, but with the combination of Tomcat 5.5 + Windows and Hot Deploys! :)

Display HTML tags in HTML pages

If you want to display an HTML tag in a web page (including posts in this blogger), you have to replace the tag markers "<" and ">" by their equivalent ASCII entities "&lt;" (which stands fot "less than") and "&gt;" (which stands for "greater than") respectively.

Check the W3 Schools to learn about other HTML entities.

Just another note: if you want to indent your tags on the page, a simple way to do this is to use the char "&nbsp;" (which stands for "non blocking space"). This char is not compressed by the browser when rendering a page.

Using Maven to deploy application to Apache Tomcat Server

For those who are not familiar with Maven, it is (as stated in the project site) a "software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information."

Based on the concept of "convention over configuration" developers may use Maven to compile, build, test, deploy, generate reports and use a whole bunch of other features to manage their software development project. In another oppportunity I will post an article about Maven, for now I will write about my most immediate need: deploy a war file to a tomcat server.

As I am using maven to manage my project from test to build, all I need is to configure the Cargo plugin. Cargo is able to download, install and start Tomcat, but this is not our focus right now, so I will assume you have Tomcat installed and running with no problems.

Using Maven´s Cargo plugin it is possible to install an application into Tomcat in two ways:

  1. Use the Tomcat Manager application, which is deployed by default with Tomcat 5.x and is nothing more than a web interface to manage your server. It has the ability to install a WAR into the server from a remote location.
  2. Copy the WAR File of your application directly into the File System where Tomcat is expecting applications to be, normally %CATALINE_HOME%/webapps.
As one can find strong and weak points in each of these options, I will tell a little bit about the first one.

Using the Tomcat Manager

Now we will deploy an application to Tomcat while it is still running. This is called Hot Deploying.

You should add some comands to your pom file, and they should look like the excerpt of code below. Actually it should be positioned between the tags:
<build>
<plugins>
...
</plugins>
</build>

<plugin>
<groupid>org.codehaus.cargo</groupid>
<artifactid>cargo-maven2-plugin</artifactid>

<configuration>

<!-- Container configuration -->
<container>
<containerid>tomcat5x</containerid>
<type>remote</type>
</container>

<!-- Configuration to use with the Container -->
<configuration>
<type>runtime</type>
<properties>
<cargo.tomcat.manager.url>http://localhost:8080/manager</cargo.tomcat.manager.url>
<cargo.remote.username>admin</cargo.remote.username>
<cargo.remote.password>admin</cargo.remote.password>
</properties>
</configuration>

<!-- Deployer configuration -->
<deployer>
<type>remote</type>
<deployables>
<deployable>
<groupid>com.company</groupid>
<artifactid>web-component</artifactid>
<type>war</type>
</deployable>
</deployables>
</deployer>

</configuration>

</plugin>
You should need to change only the values in the and tags with the values that describe your component WAR file you wanto to install to Tomcat.

Having this in your pom file, you need to issue the following command:

mvn cargo:deploy
If you already have the application running in tomcat it is necessary that you undeploy it before deploying. So, issue the command below and you should be ok:

mvn cargo:undeploy

You also have the option to execute a command that will do an undeploy before attempting to deploy:

mvn cargo:deployer-redeploy
That should be enough to get the application running in Tomcat, deploying from a remote server.

I would just like to add that the configuration for the tags
and are values that must match the ones in the tomcat-users.xml file with the role "manager". Check this before trying to do the deploy.

SDWest 2007 Conferece

The registration for SDWest 2007 is now open.
Early bird discounts goes until February 23rd.

Change default View Source Editor in Internet Explorer (IE)

I believe it is common sense that Windows Notepad is not among the best text editors in the market, right?

So, if you wanna change the editor that will display the source html from a web page being displayed in internet explorer to another editor you use, here´s how to do it:

1 - Open the registry editor. You should find it under C:\WINDOWS\system32\regedt32.exe or simply type "regedit" in the run command box in Start Menu.

2 - Navigate in the tree to find the following key

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\View Source Editor\Editor Name

3 - The default value for this key is "C:\windows\notepad.exe". Change this text to whatever editor you like, with the full path to it. If you want to use UltraEdit, for example, the new value should be changed to "C:\Arquivos de programas\UltraEdit\UEdit32.exe".

Thursday, January 18, 2007

SVN as a service under Windows

Found this great article on how to run subversion as a service (check my other post on installing subversion (SVN)).

Basically it explains how to use the "sc" (Service Control) which is provided by Windows OS to crete a service to run the svnserve command. This should work on Windows NT, XP, 2000 and 2003 Server.

It should look like something like this:

sc create [name]
binpath= "c:\svn\bin\svnserve.exe --service [svn-args]"
displayname= "Subversion Repository"
depend= Tcpip

If you are not comfortable in doing this, you can always try running svnservice, which is a project from tigris intended to "offer a comfortable way to run svn server (svnserve.exe) as MS Windows service".

Friday, January 12, 2007

The Cygwin sshd as a service under Windows

My other post on called "Running a ssh server on Windows" gave some steps to start a ssh daemon on Windows using Cygwin.

The interesting thing is that when you setup the ssh environment on Cygwin (executing the command ssh-host-config), it also creates a service in windows. This service can be accessed through the Services Management Windows standard administration tool and be setup to start automatically when windows starts.

Neat! :)

Check this article with some interesting observations on setting up the users who will and will not be allowed access to the ssh server.

Running a SSH server on Windows

This post is not essentially about software development but is about something I found very useful: having an ssh connection to the machines where I work.

SSH daemon in available in linux from the start and there are no big matters about it other than security issues.

Running an ssh server on a Windows machine is a little bit trickier. Thanks to the guys at Cygnus we have Cygwin, which is, as stated in their web site "a Linux-like environment for Windows".

This environment comes with a ssh server daemon which can be run as a service in Windows, allowing you to have ssh connections to your machine using any valid ssh client.

First step would obiously be to donwload and install Cygwin on your machine. You can find a quick reference on installing it under Windows.

There is an official document distributed with Cygwin on setting up a secure environment using ssh. You will find it entering the following commands on your cygwin prompt:

cd /usr/share/doc/Cygwin

less openssh.README

This document can also be found online and the tips below are intended to be a quick start guide.

So now that you have Cygwin installed, you should open your cygwin prompt and type:

ssh-host-config

The output should be something like this:

$ ssh-host-config
Overwrite existing /etc/ssh_config file? (yes/no) yes
Generating /etc/ssh_config file
Overwrite existing /etc/sshd_config file? (yes/no) yes
Privilege separation is set to yes by default since OpenSSH 3.3.
However, this requires a non-privileged account called 'sshd'.
For more info on privilege separation read /usr/share/doc/openssh/README.privsep.

Should privilege separation be used? (yes/no) yes
Generating /etc/sshd_config file

Host configuration finished. Have fun!

This should be enough to run the server daemon. Run one of the following two commands to start it.

net start sshd
cygrunsrv -S sshd

Check if the server is actually running:

$ ps -ef | grep ssh
SYSTEM 760 3508 ? 00:29:11 /usr/sbin/sshd

Now test if the connection was successfull:

$ ssh localhost
dambrosio@localhost's password:
Last login: Sat Jan 13 00:31:53 2007 from 192.168.1.1
Fanfare!!!
You are successfully logged in to this server!!!

There are a lot of security issues about ssh and remote connections. Read a bit more about the subject, and there is an interesting article which is a good starting point.

This other article will give you some hints on installing cygwin, setting it up as a service on Windows 2003 and some issues about security as well.

Remember:
ssh runs by default at port 22, so remember to open this TCP port on your firewall. You do have one, right? :)

Sunday, January 7, 2007

Installing Subversion, a Version Control System

Having a Version Control System is almost mandatory for every developer because keeping track of the evolution of his code is highly desirable. Such a system allows the developer to have individually registered version of every file in his system, including source code, documentation, diagrams etc.

Subversion (AKA as SVN) is such a system. It is open source and is considered an evolution of CVS with new features and a new internal architecture which allows SVN to have significant changes and improvements when compared to CVS, such as directories versions, truly atomic commits etc.

After this brief introduction, let’s get to work. As I am using Windows as platform for development (flames expected here ;) this article will give you the steps on installing SVN on this platform. If you are using Windows there are 3 ways to get subversion on your system:

1. Get an installer from Collabnet site.
2. Get a zipped file with binaries from tigris.
3. Get the sources from the repository and compile them on your system.

I’ll stick to the first two situations, because you would normally need the third one only if you need the latest features on the system. The stable releases should be enough for most needs.

Using Collabnet’s installer
Collabnet is the company that designed and created subversion. Using this prepared installation file should be the easiest way to get subversion up and running on your windows box. It comes with the SVN server, a SVN command-line client and an apache server almost ready for running svn.
CollabNet provides a readme file with basic instructions on creating a repository, clearing the firewall to let SVN do his work etc. It is a good basic reference. So, simply download the file (version 1.4 as of the time of the writing) and follow instructions.


Using ZipFile Binaries
This installation option is a little bit more difficult than the one above but everyone should do fine. I will not cover apache installation on this article.

Step 1
First of all you should download the latest version of the server available from subversion project downloads page. As of the time of this writing it is version 1.4.2. You may choose to download the sources and compile them yourself or download the binaries created by contributors to the project, which though not maintained by the project team are normally reliable packages. Now scroll the downloads page down to find the binaries for SVN Server for Windows. When you are redirected to the page find the latest release (should be the last one in the list) and get the file which name looks more or less like this svn-win32-X.X.X.zip (the one I got was svn-win32-1.4.2.zip).

Step 2
Unzip the file somewhere on your hard disk where it would make sense to have the subversion binaries. We will call this folder the subversion home directory (%SVN_HOME%). For example, if you unziped the files for SVN version 1.4.2 under C:\Program Files folder, your %SVN_HOME% dir would be: C:\Program Files\svn-win32-1.4.2. On the %SVN_HOME%\bin folder you will find the executable files which you will use to maintain your server and repositories.

svn.exe - Subversion client
svnadmin.exe - Subversion repository administration
svndumpfilter.exe - Subversion dump fle filter
svnlook.exe - Subversion repository browser
svnserve.exe - Subversion Server
svnsync.exe - Subversion repository replicator
svnversion.exe - Subversion revision extractor

Step 3
Let’s create the repository. Add the %SVN_HOME%\bin folder to your path variable in Windows to make the binaries accessible from anywhere in your computer. Now, create a test repository folder somewhere on your system (let’s say c:\temp\svn-test-rep) and we will call it the %SVN_REP%.
Run the svnadmin command to create a repository called repos1. You will do that running the following command:

svnadmin create c:\temp\svn-test-rep\repos1

As a result you should have a folder called "repos1" under %SVN_REP% with the following content:

DIR --- conf
DIR --- dav
DIR --- db
------- format
DIR --- hooks
DIR --- locks
------- README.txt

Step 4
Now we should test the server. This is as simple as running the command below:

svnserve -d -r c:\temp\svn-test-rep

This will get the server up and running. The "-d" tells the server to run as a daemon and "-r" tells the repository name.
Remember to enable svnserve to run on your firewall if you have one (if you don’t, you should get one ;)).

Now open another command prompt (while the server is still running), go to your "temp" folder and checkout the repository you created on step 3. Checking out a repository means getting a local version (copy with a revision number) from every file present on your repository. You can do that by typing:

svn co svn://localhost/repos1

This command will ask the svn server running on localhost to get the latest revision of every file on repository called "repos1". The "co" in the command line stands for "checkout" and "svn://" specifies the protocol used to access the repository. If had apache installed and setup to run svn mods we could use http or https to access the repository.

Well, this pretty much tells you how to install a SVN server and create repositories for your code. Of course now you will get worried about issues like: who can access my files or how do I specify security constraints? This should be subject for another article, as well as svn GUI clients and apache server.