Showing posts with label software tools. Show all posts
Showing posts with label software tools. Show all posts

Tuesday, 21 May 2013

JExcel vs Apache POI : Reading and Writing Excel Files

JExcel is a relatively simple and robust Java based library for manipulating Excel (.xls) files. While it has relatively less functionality than its bigger and more popular brother, Apache POI, it offers a simple API for Excel manipulation.Some features that made me choose JExcel were its relatively smaller memory foot print, simple API and upto date documentation.
On the other hand, some drawbacks that made me wary of choosing the tool were its lack of support for .xlsx files and the fact that the last release was in October 2009, more than 3 years ago. This discussion has listed a significant number of differences between JExcel and POI and while it may appear that Apache POI would be the obvious winner, it all boils down to your requirements. After all you can travel from point A to B in a car or do the same trip in a truck. In situations where the requirements are not very clear, are extensive  or might require support for .xlsx files in the future, Apache POI might be a better choice but if your requirements are clear, you need a fast and efficient Excel generating tool with minimum fuss, choose JExcel.
  
  
   net.sourceforge.jexcelapi
   jxl
   2.6.12
  

  

Thursday, 25 April 2013

Setting up Solr 4.0 on Tomcat 7.0.28

Generally every user centric application requires a Search capability. With Google easily leading the Search domain, user expectations are generally high when they come to a web-application and perform a search. If giving user's the Google experience is not possible, consider Apache's Solr  which is a popular, open-source Java based search tool that runs Lucene under hood.
While Solr comes packaged with Jetty and has a basic tutorial, that provides pointers on its different features, setting up the tool to run within an existing Apache Tomcat instance can require a bit of effort as there are several files and folders and it is not immediately clear which files control the configuration of the tool. This post will document the various steps involved in setting up Solr to run with Apache Tomcat 7.0.28 on a Windows server.

Step 1 : Download a copy of Solr and unzip it  to apache-solr-4.0.0.

Step 2: Create new directory which will be the home of Solr c:\solr_home and copy the following files and folders into it.  ( You will find  them within  the unzipped apache-solr-4.0.0 folder).
bin
collection1
solr.xml
zoo.cfg

collection1 is an existing example which we will load up into our Tomcat.Within the directory collection1, you'll find two other folders conf & data. Just verify that these are present.

Now we'll connect Solr to Tomcat.

Step 3:  Copy the apache-solr-4.0.0.war (which you will find in apache-solr-4.0.0\dist)  into your Tomcat web-apps directory.

Step 4:  Finally, the last step. Tell Solr where the existing search configuration files for collection1 reside.
To do this add the location of the Solr Home directory to your Tomcat JAVA_OPTS. I am setting this value in the setenv.bat file and the declaration looks like this :

set JAVA_OPTS=%JAVA_OPTS% -Dfile.encoding=UTF-8 -server -Xms1536m -Xmx1536m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m -XX:MaxPermSize=256m -XX:+DisableExplicitGC -Dsolr.solr.home=C:/solr_home

Step 5:  Start Tomcat and browse to your loaded Solr instance at http://localhost:8080/apache-solr-4.0.0/#/ You should see the Solr Admin screen as below :
Solr Admin Console for Collection 1
To check if Solr has been configured and set up correctly, select collection1 in the left hand side bar and select the query option. Enter 'solr' in the textbox labelled 'q' as shown in the screenshot below.

Default Search Interface
On submitting the query, one result is returned by Solr. On clicking on the result link, the record is displayed as an XML.
Search Result for 'Solr'


In the next post, I'll document the steps of integrating Solr with an existing web-application which is running on the same Tomcat instance with a MySQL back-end.

Friday, 29 March 2013

Generating JavaDoc with Eclipse or Maven

Generating JavaDocs is an integral part of every Java project and there are various options of generating the required documentation.

Option 1 :  Using Eclipse and JDK's JavaDoc tool.

This is the simplest option. If you are using Eclipse and have the path to the JDK (not JRE) set in the Eclipse > Windows Preferences > Installed JRE option set correctly (as shown in the screenshot below), Eclipse should be able to find the JavaDoc tool.
Set the path to your installed JDK

JavaDoc Tool in Eclipse
That's it. Clicking on the Javadoc option will bring up a wizard that will prompt you for the Destination folder for the generated JavaDocs. Apart from generating the JavaDocs, the tool will also create a stylesheet.css for the JavaDocs that can be edited if required.

Option 2 :  Using Maven and the JavaDoc plugin.

Add the plugin definition to your pom.xml
               
                
                     ...........
                  
                  org.apache.maven.plugins
                  maven-javadoc-plugin
                  2.9
                  
                    C:/javadoc/stylesheet.css
                     public
                  
                  
                
                  


In the snippet above, I have added the plugin definition and configuration to the build section. It can also be repeated in the section. This will allow me to run the Javadoc generation goal during the build cycle. I have also specified a path to a stylesheet file that will define the look and feel of the JavaDoc generated.

To generate the JavaDoc using Maven, use mvn javadoc:javadoc

More details on this option is available here.




Thursday, 28 March 2013

Guava : Using Java Collections the Google Way

Recently Guava came out with release 14.0.1 which include a number of bug fixes and enhancements. As a utility library, Guava provides an impressive list of extensions and tools for using Java collections with an aim towards improving code readability, transparently managing Java collections and introducing useful checks and frequently used utility methods that simplify the generation of quality code.
With respect to Java Collections, Guava provides utility methods for creating Immutable collections, and provides some new Collections. If just looking for implementing various checks on your Java Collections, there are a number of Collection Utilities that allow you to create an equivalent Java Collection while writing code that is cleaner and easier to read.

For example, constructing a generic collection before Java 7 would amount to the following line of code:
  • List list = new ArrayList();

In Guava, this could be simplied to  List list = Lists.newArrayList();
And this approach could be further extended to include the List size and initialise the List as follows:
  • List list = Lists.newArrayList(100); // create a list with a 100 elements.
  • List list = Lists.newArrayList("red","blue","green"); // create and initialise a list with some values
Similarly Guava has many utility methods for dealing with nulls in Collections, managing String and performing operations on the Java Math library that is not available in the JDK. If using the Apache Commons Library, Guava is definitely worth a check out !!

Saturday, 6 October 2012

Ninite - Rebuilding your system

I have been using Ninite for the  last few months to install some essential utilities and have found it to be a useful service to set up browsers, media tools, anti-virus, messaging and document management tools. The selected tools are bundled into a single exe and are installed via the Ninite created installer. Thus, installing and rebuilding a system becomes simpler and faster.

Wednesday, 21 March 2012

JDom : The Java based solution for XML manipulation

JDom is a Java based open-source XML manipulation tool that is easy to install and use. Whereas technologies like JaXB are focussed on the marshalling and unmarshalling of XML using Java beans, JDom is more of a XML manipulation tool that is an alternative to DOM and SAX even though as the FAQ says, it integrates well with both these technologies.The best way to understand how well JDOM fits into your requirements is to read the very detailed FAQ. JDom version 1.1.13 is the latest version which is now available from maven-central.

  org.jdom
  jdom
  1.1.3
  
  
   
    maven-plugins
    maven-cobertura-plugin
   
   
    maven-plugins
    maven-findbugs-plugin
   
  
 
xPath support in JDom via Jaxen makes accessing and manipulating XML document trees a breeze. Thus, if you are looking for a low cost solution for manipulating XML documents from a pre-existing template or querying an XML document for extracting xml attribute values, give JDOM a run.

Wednesday, 28 December 2011

Use ColorBrewer for coloring maps rendered with GeoTools

ColorBrewer is an excellent library for creating dynamic color palettes that can be used to apply colors to a map based on the spread of data values. The ColorBrewer web tool allows you to select a color scheme based on the nature of the data (sequential, diverging, qualitative) and  the number of data classes present in the data. You can opt to select a color scheme that is color blind safe and works well on a photocopier.
Based on your requirements, the web tool will display the name of the color scheme that works best for the entered combination. For example, in the screenshot below, the color scheme chosen by the tool is BuGn.

ColorBrewer 2.0

ColorBrewer comes bundled with GeoTools. To include the correct library,use the following Maven snippet.

     org.geotools
     gt-brewer
     2.7.2

To instantiate the required palette within your Java application,
   String paletteName = "BuGn";
  ColorBrewer brewer = null;
  try {
   brewer = ColorBrewer.instance(ColorBrewer.DIVERGING);
  } catch (IOException e) {
   //Log Error
  }
                // Instantiate the color palette 
                 palette = brewer.getPalette(paletteName);
                // Get the number of colors your need. In this case, 3 colors
                // which are a variant of Green
                 palette.getColors(3);
Now, you have an array of colors which you can apply to your GIS features.

Friday, 25 November 2011

Install JFreeChart 1.0.14 with Maven

After 2.5 years, JFreeChart came out with a new release of the toolkit on Nov 21,2011.Version 1.0.14 promises bug fixes, improvements in the TimeSeries graphing and much more. Over the last few years, JFreeChart has been a popular open source choice for charts and graphs in Java.  The previous version has been download close to 430,000 times and while there are not many examples available describing the usage of the toolkit, installing it and implementing it in a Java application is relatively pain free.
Currently, the Maven repositories have not been updated with this release and you will need to manually install it into your local repository. To do so:

  • Download the latest release from the source-forge download page. Unzip the jar onto your local file system to any directory, say C:\jFreeChart\jfreechart-1.0.14
  • Open a command prompt in the directory where you have your Maven POM located and invoke the following command from the command line:
  • mvn install:install-file -Dfile=C:\jFreeChart\jfreechart-1.0.14\lib\jfreechart-1.0.14.jar -DgroupId=jfree -DartifactId=jfreechart -Dversion=1.0.14 -Dpackaging=jar
This should install jFreeChart into your local Maven repository. Now you can add a dependency to the Maven POM as follows:

     jfree 
     jfreechart
     1.0.14 
     compile 
    

Wednesday, 2 November 2011

log4j - power logging at your fingertips

log4j has been a popular logging framework in Java applications for several years. It is simple to implement, thread safe and light weight. While there are no current major releases planned, it is still a popular download among the Apache Logging Services toolset.
To add log4j to your project using Maven, add the following dependency snippet to your code


  log4j
  log4j
  1.2.16
 
Maven will download and add the log4j jar to your respository. Next, you need to specify a configuration file, which could be either a .properties file or a .xml file.The configuration file is usually named as log4j.properties or log4j.xml and need to be placed within the classpath for the application to find it.
If you are building an application that ships as an executable JAR, place this file within your src/main/resources or your src/test/resources directory depending upon whether you need your logging framework in the production code or not
The log4j manual describes a sample properties file.If you don't have access to a .properties file, you can use the entries shown in the example to create a .properties file for yourself.Now that you have a log4j properties file, you need to make sure that you have a Appender defined within it.
For logging messages to the console, use a ConsoleAppender. For logging to a file, use a FileAppender.
To control what should be logged with the log statement, set up a Layout and initialise it to a particular Pattern. A popular Layout is the PatternLayout that formats the output line with meta data using a pre-defined pattern.

For example, here is a snippet from the manual.

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

The ConversionPattern can be used to specify meta-data about the logged statement, such as the Class from were the log originated, the date and time in different formats, the severity level etc.An exhaustive list is available in the API docs. It is worth noting the several warnings posted in the API docs regarding speed and efficiency before choosing a ConversionPattern character.
Another aspect of log4j logging performance that one needs to be aware of is the cost of creating a log statement that may not be used.To get around the parameter construction code, wrap the logging statements within a check:
if(logger.isDebugEnabled() {
    logger.debug("Log : " +  " String 1 " + "String 2"));
}
If the check is not place, the log statement will create 4 Strings (yes , we could have used a StringBuffer), but a simple check prevents this overhead. Ofcourse, there is now the cost of checking the LEVEL at which the logger is set, but this is a miniscule overhead.
Finally, now that the log4j is setup and has been configured, instantiate it 

static final Logger logger = Logger.getLogger(MyClass.class);
and start logging:
logger.info("Starting the APP");
Exceptions can be sent to the log file as an argument to the logger.error method.
catch (Exception exception) {
logger.error("Error in loading application! ", exception);
To conclude, if you need an easy and fast logging framework, log4j will fit your bill.However, if you are in the market for the next generation of logging, then have a look at Logback

Saturday, 29 October 2011

Using 'R' for Statistical Computing

I recently tried out the 'R' toolkit for performing some statistical operations and was impressed with the power and the extensibility of the toolkit in manipulating terra-byte sized data and its ability to produce publication ready graphs. Being open-source, it is available under the GNU GPL and can be downloaded from a CRAN site and set up to run on Windows, UNIX or Mac OS.
The toolkit basically provides a command-line enviroment for manipulating and loading data into memory arrays which can be subject to further statistical analysis. While the majority of the users see 'R' as a statistical package, it can be also be used as a modelling tool for linear / non-linear models.Apart from providing some high level functions for statistical computing, 'R' also has a well-developed suite for looping and conditional execution. It  also allows extensibility so that users can write their own functions.While the user-interface is easy to get used to, if you are coming from a UNIX background, it might take some getting used to for Windows users.

The 'Help' module is a well designed and is easy to use. Documentation on any function can be loaded from the command-line by preceeding the function name with a '?'. Overall, 'R' is a powerful toolkit for statistical computing and an excellent choice for manipulating large data sets.

Tuesday, 18 October 2011

GeoTools - GIS for Java Developers

GeoTools is an excellent Geographical Information System (GIS) toolkit for Java. It is open-source and has regular updates. The last released version at the time of writing is 2.7 released on the 7th of October 2011. The toolkit also serves as an engine for some other GIS based open-source tools such as uDig, GeoMajas and GeoServer.GeoTools also has some good supporting documentation with tutorials for setting up the toolkit in Eclipse / Maven. The tutorials also give some pointers on generic Geospatial concepts, such as Features, Layers and Maps

A Feature in GIS world is any real world entity that can be represented on a Map. Valid examples of such entities are rivers, buildings, roads, etc. In GeoTools, Features are an instance of a FeatureType. Thus, Features can be considered analogous to (Java) Objects and FeatureTypes can be modelled as (Java) Classes. Features have attributes. for example,  a river may have length, depth, water salinity as its attributes similar to the Field concept in Java. Features also define operations which are analogous to Methods in the Java world. Thus, this close analogy between Java concepts and the GIS toolkit implementation  makes it an easy for Java programmers to work with the toolkit.

Data in GIS (& GeoTools) can be represented in two forms, Raster or Vector type. Raster type data refers to digital images that can be transformed to a grid representation. Vector type data use Geometry to represent real-world elements.Geometry can be reduced to three main forms: Point, Line and Ploygon. Geometry also gives a location attribute to the element it refers to.

Thus, in GeoTools, defining a Feature using a Vector datatype requires a Geometry component specification.  A Feature also has a Style component associated with it. The Style component defines the rendering and look and feel of the Feature on the Map. Features are connected to a Map using Layers. A Map can have several Layers. A Layer contains a set of Features and their associated Styles. It is possible to overlay several Layers on a Map and thus have different objects visible in the same view.Usually, this entire information schema is stored within a file, known as a ShapeFile.

To summarise the process of rendering a Map using GeoTools, the following steps need to be followed:

1. Create a Map, using a DefaultMapContext
2. Load the ShapeFile 
3. Extract the FeatureSource from the ShapeFile  [FileDataStoreFinder.getDataStore(shapeFileLocation)]
4. Create a Style using the FeatureSource. GeoTools has some good tutorials on getting this done.
  A Style involves creating FeatureTypeStyles and associating Symbolizers and Rules with the defined FeatureTypeStyles.
5. Add the Style to a Layer of the Map.
6. Add the Map and a Renderer, to a JMapPane which extends JPanel.
7. Display the JMapPane.

GeoTools also has tools available for creating ShapeFiles from CSV files.Thus, GeoTools simplifies the process of creating GIS applications in Java and enables applications to be up and running within a matter of hours.

Friday, 16 September 2011

Generating Entity Relationship diagrams from a database schema

Consider the situation where you have been given a database schema to work with but there is no E-R diagram documentation available and you need to re-design the database schema. The first step would be to try and understand the existing schema by generating an Entity-Relationship (ER) diagram from the existing database schema.To get an E-R diagram where none is provided, use SchemaSpy.

SchemaSpy produces a rich set of diagrams and tables which gives the users and developers a detailed description of the schema tables, constraints, anomalies ( to investigate what might be wrong with the schema) and most importantly, it displays the relationships between the entities as an E-R diagram. The following steps should help you get started with SchemaSpy. 
  • The tool is Java based open source software tool that it has been developed using Java, runs on Windows as well as UNIX and requires the Java Runtime Environment (JRE) so install the JRE if you don't have it,
  • For generating Graphical views of the schema, the tool is dependent upon the Graphviz library, so download and install it before installing Schema Spy. You'll have to make sure that your Windows PATH Enviroment variable points to the bin directory of the Graphviz install. If it doesn't, you can still run SchemaSpy but you'll need to specify an additional parameter along with the start up parameters of SchemaSpy.
  • Download the jdbc driver for the database SchemaSpy will connect to. For example, for PostGresql, you can download the jdbc driver from this page. For MySql, you'll find the driver here and for Oracle, here.
  • Download and install SchemaSpy. Have a read of the start up instructions and see which parameters are mandatory and which are optional.  Open a DOS command prompt and run SchemaSpy using the following command : 
  • java -jar schemaSpy_5.0.0.jar -dp    -t databaseType  -host -db -s  -u  -p   -o
  • You may also need the -gv pathToGraphviz parameter 
Depending upon the size of the database schema, SchemaSpy will take a few minutes to generate the ER diagram which can be viewed by clicking on the index.htm in the 


Saturday, 10 September 2011

Designing Model Driven Architectures using the Eclipse Modelling Framework

The Eclipse Modelling Framework (EMF) is another useful tool within the Eclipse suite that offers an open source framework for the designing model driven applications. In terms of technology, EMF unifies Java, XML and UML. Given a 'model' described in either of the three technologies i.e Java, UML or XML schema, it is possible to generate the other two. To get an idea of what type of applications can be designed using the EMF, check out this list

The major advantage of using EMF is that it connects a model to its Java based implementation and this simplifies the process of designing and implementing a model. EMF generates Java code separating interfaces from their implementation. In addition, it also generates Factory classes for managing objects. EMF also supports standard CRUD operations, specification of cardinality constraints and the enforcement of referential integrity. Database persistence is available via Teneo.

Designing models in EMF is done using the Eclipse Java Development Tools.Third party options such as Topcase's Ecore editor and Ormondo's EclipseUML editors can also get the job done.
While the Ecore model can realised from Java (using Annotations) , XML Schema orUML, persisting the serializable version requires another form : XML Metadata Interchange (XMI).

Lars Vogel's tutorial is a good starting point for learning and implementing an EMF based application. While the learning curve for EMF is not very steep, debugging problems in the generated code can be a little painful. To get started with the development of EMF based applications, download the Eclipse Modelling Tools IDE and create a new EMF project using File -> New -> Project

Saturday, 3 September 2011

Designing Swing / SWT GUIs using WindowsBuilder in Eclipse Indigo

The latest release of Eclipse code named Indigo includes the WindowsBuilder project as an open source project within the Eclipse umbrella of projects. WindowsBuilder which is a significant GUI designing tool in its own right provides a WYSIWYG editor for desgining Swing and SWT interfaces from within Eclipse.

WindowsBuilder comes bundled with the standard download 'Eclipse IDE for Java Developers' but if you choose to download another version of Eclipse and you need to manually add the plugin, , goto Help->Install New Software -> and in the 'worh with' box enter the site : site http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7  and then follow the usual steps for adding the plugin. After successfully installing it, you will be able to view the plug-in in the 'Installation History' and the'Plugins' tab of Eclipse Installation Details.


Now that you have WindowsBuilder installed, creating Swing / SWT based GUIs is just a matter of clicking through a few wizards. To create a screen using the wizard, create a Java project and then select New-> Other->WindowsBuilder and open up the wizard.

Other->WindowsBuilder and open up the wizard. Select the required option. In this case, I selected 'ApplicationWindow' and the wizard generates the ApplicationWindow for me as shown in the screenshot.
At the bottom of the editor view, there will be two options, 'Source' and 'Design'. Click on the Design option. This will open the design page and load up the pallet and give you the WYSIWYG option.You can now see your 'frame' object on the right hand side and the pallet with different Swing and SWT controls that you can use. I added a JPanel and set its layout to 'JGoodiesFormLayout' and then added a couple of labels, textboxes and a 'Send' button.
Add the required controls you need. You can also select any of the controls and add any EventHandlers that you might need by right clicking on the controls.


The wizard will create skeleton code for you which you can customize as required. Once you are done, just run the application.




Finally, if you want a different 'Look and Feel', especially a 'Native Platform' look, the WindowsBuilder has an option in the top menu, that allows you to change the Look and Feel as shown in the screenshot below.


Thus, within a few minutes, you can design a fully functional Java application with a few bells and whistles. This is very useful, if you need a prototype and some sample screenshots to show the user. Instead of wasting time,drawing the screens in a prototyping tool, create the same using the WindowsBuilder plugin and when the client gives you the green light, come back to your prototype, clean up the code and add the required functionality. Finally, there are a couple of good tutorials on YouTube that describe using WindowsBuilder with Eclipse.

Sunday, 28 August 2011

JGraph : An open source diagramming tool

JGraph  has an excellent open source Java based diagram creation tool. The guys who have developed the tool also give access to a free online diagram creation tool which is pretty nifty and useful if you don't have MS Visio installed and need a quick diagram on the fly. Once created, the diagram can be downloaded as in xml, jpg or png formats.

Tuesday, 6 October 2009

Scalable Vector Graphics

Scalable Vector Graphics provide a rich source of functionality that allow applications to manipulate and respond to the user interactions with the image. Creating and modifying SVG images is possible using one of the several open source tools available.

Batik SVG Toolkit is an impressive Java based open source SVG toolkit that provides libraries for the dynamic manipulation of SVG objects from within a Java application. While Batik provides a rich array of functionality, it somewhat lacks a good WYSIWYG editor.

A good WYSIWYG editor for SVG Graphics is provided by Inkscape which is another open source SVG editor with several advanced editing features such as (markers, clones, alpha blending, etc.)

Thursday, 11 October 2007

Configuring Middlgen to generate Hibernate files from MySQL

Following on from my earlier post , I'll now show you how to configure Middlegen and talk to your MySQL database. You will need to have ANT installed in order to run the ANT tasks that I customized to build the hbms and the Java objects.

I performed the Middlegen connection tasks using ANT version 1.7, MySQL version 5.0.24-community-nt and MySQL client version 5.1.11 and Middlegen 2.1

In your build.xml, set the following Middlegen property
<property name="Middlegen.home" value="${lib}/Middlegen"/>

The lib directory has 2 main jars, Middlegen-2.1.jar and Middlegen-hibernate-plugin-2.1.jar.

Both these jars are required to
(1) Run Middlegen and connect to MySQL
(2) Create Hbm mappings from the database and convert the hbm mappings into Java objects.

Firstly create a directory where you are going to store your generated files using the Middlegen-init ANT task.

<target name="Middlegen-init"
description="Initializes everything, creates directories, etc.">
<mkdir dir="${gen.java}" />
</target>


The next task is Middlegen which talks to the database but inorder to do so, it needs to know where the database is located, what driver file to use and what connection properties to use, so make the task know all this by defining the following properties in the build.xml

<property name="database.initialise.script" value="${main.resources}/database/ddl/FULL_DROP_INITIALISE.sql"/>
<property name="database.driver.file" value="${lib}/mysql-connector-java-3.0.14-production-bin.jar"/>
<property name="database.driver.classpath" value="${database.driver.file}"/>
<property name="database.driver" value="org.gjt.mm.mysql.Driver"/>
<property name="database.url" value="jdbc:mysql://localhost/testdatabase"/>
<property name="database.userid" value="root"/>
<property name="database.password" value="root"/>
<property name="database.schema" value="testdatabase"/>
<property name="database.catalog" value=""/>

You'll notice that the properties talk about a 'database.driver' which should be on the 'database.driver.classpath'.
This driver can be found within the mysql-connector-java-3.0.14-production-bin.jar so it should be downloaded and made available to the application.

Now, write the following ANT tasks in your build.xml

<!-- Middlegen related Tasks --->
<!-- =================================================================== -->
<!-- Run Middlegen -->
<!-- =================================================================== -->
<target
name="Middlegen"
description="Run Middlegen"
unless="Middlegen.skip"
depends="Middlegen-init"
>

<taskdef
name="Middlegen"
classname="Middlegen.MiddlegenTask"
classpathref="lib.class.path"
/>

<Middlegen
appname="${name}"
prefsdir="${Middlegen.prefs}"
gui="${gui}"
databaseurl="${database.url}"
initialContextFactory="${java.naming.factory.initial}"
providerURL="${java.naming.provider.url}"
datasourceJNDIName="${datasource.jndi.name}"
driver="${database.driver}"
username="${database.userid}"
password="${database.password}"
schema="${database.schema}"
catalog="${database.catalog}"
includeViews="false"
>

<!-- Sets up the hibernate plug-in for Middlegen -->

<hibernate
destination="${gen.java}"
package="${name}.persistence"
genXDocletTags="true"
javaTypeMapper="Middlegen.plugins.hibernate.HibernateJavaTypeMapper"
/>
</Middlegen>

</target>

<!-- =================================================================== -->
<!-- Run hbm2java -->
<!-- =================================================================== -->
<target name="hbm2java" description="Generate .hbm and then .java from .hbm files.">
<taskdef
name="hbm2java"
classname="net.sf.hibernate.tool.hbm2java.Hbm2JavaTask"
classpathref="lib.class.path"
/>
<hbm2java output="${gen.java}">
<fileset dir="${gen.java}">
<include name="**/*.hbm.xml"/>
</fileset>
</hbm2java>
</target>
<!-- End of Middlegen related Tasks --->

To create the HBM mappings for ALL tables in your 'testdatabase' schema:
Run the 'Middlegen' task which will
(1) create a directory to store the generated files
(2) connect to your MySQL database based on the params supplied and generate the hbm mapping files.

You can customize the hbm files according to your requirements, now run the hbm2java mapper task on these files by invoking the target 'hbm2java'. The java files will be generated and stored in the same directory alongside their respective hbms.

Well, that's all there is to it.

Middlegen is a very useful tool as it takes away the pain of manually creating these files and helps you setup your Hibernate environment within a couple of hours.

For more info on the subject refer to the Middlegen homepage.

Friday, 14 September 2007

MiddleGen and Hibernate: Making life easy in the middle

If you have been working in the Hibernate or in the EJB space, chances are high that you have had to write intermediate files such as hbms, in the case of Hibernate, that bridge the gap between the database tables and the Java objects (read POJOs) that exist within the application and are responsible for transporting data around.

While writing the hbm files manually, is a good idea if you really want to learn about how they are structured and the different types of relationships that they can be define within the data model, it becomes a tedious task if your data architect is not sure of what he or she is doing and/or keeps changing the DDL regularly.

In an AGILE project scenario, where requirements are welcomed at late stages of the build process, having a tool that can generate the hbm files and the related Java files (which are essentially POJOs) can be a boon. This is where MiddleGen comes in.

While MiddleGen is basically (an open source) database driven tool for generating code from the database to the presentation layer (Struts), I found its confluence with Hibernate to be really useful. It took me basically half-an-hour to set up MiddleGen and configure the Ant Tasks that came with the sample set of examples (in the MiddleGen download), to connect to my MYSQL database and generate a set of hbm files and their corresponding Java counterparts. In my next post, I'll explain the sequence of steps that I followed in setting up MiddleGen to talk to my database and generating the hbms and the Java files.

Sunday, 12 August 2007

Subversion : The next generation of version control systems

Subversion has been gaining popularity as a robust and easy-to-manage version system over the last few years but are there specific advantages for a project to use Subversion as a source code control system? This post briefly examines some of the benefits of using Subversion and brings together a collection of resources that can be used to understand, set-up and start using Subversion as a version control system.

What is Subversion?

Subversion is a version control system which maintains different versions of your documents and files, allowing you to get the latest versions or previous versions easily.

Some of the major advantages for using Subversion are:
  1. It is open-source and thus is free.
  2. Setting up Subversion and managing users is a simple affair.
  3. Subversion is rated to handle binary files comparatively better to the widely used Concurrent Versions System. Thus, image files can be handled better.
  4. Subversion can be integrated with Eclipse using a plug-in named Subclipse, which is useful for developers who like working from within an IDE.
  5. An open-source client (TortoiseSVN) makes accessing and using Subversion from Windows systems easy. Tortoise operates as a windows-shell client and is integrated into the windows explorer.
Some strong testimonials and user experiences are given on this page. On a personal note, I have used Subversion in about 5 projects over the last two years have found it to be a very robust and easy to use source control system.

Using Subversion

Subversion is based on a client-server model, which means that a server process actually monitors and manages access to your files.

( Note: you can also run Subversion as a standalone program to store your personal files but if you choose to do so, you will not be able to access your files from other systems. This article is describing a scenario where you would want to access your files from multiple systems.)

To set up a subversion server, follow the steps outlined in this excellent post.

If you have installed the Subversion server successfully (with Apache), then install a client that will be used to access and modify the files managed by Subversion. To keep things simple, we will focus on setting up Tortoise SVN ( a Subversion client) and use it

To set up the subversion client (TortoiseSVN), follow the steps outlined in this post.

Once you have a server and client system setup, you can access Subversion, check out and check in files, as many times as you like.

Subversion / TortoiseSVN resources
  1. Subversion Homepage
  2. TortoiseSVN Homepage
  3. Subclipse download page

Monday, 23 July 2007

Foxmarks: A bookmark synching tool

While playing around with Mozilla's FireFox, I came across Foxmarks, one of the recommended Firefox add-ons. The main advantage of the tool, apart from the fact that it is free, is that it allows the synchronization of Firefox stored book marks on different machines. I find option to be a pretty useful feature in the consultancy world, where we move from one system to another and sometimes have to do so at a pretty quick notice. While exporting bookmarks and importing them is an option, it requires a third party medium to transport the bookmarks from one system to another. Foxmarks allows you to perform this operation using an intermediate server. The server also acts as a backup device for the storage of the bookmarks.

Two major advantages of Foxmarks are that the installation process is very light and that the tool is easy to use. Foxmarks has one main button "Synchronize now" which pretty much does what it says. It synchronizes the bookmarks on the local machine with a master copy, that is stored on the Foxmarks server. The master copy on the server is created when the user synchronizes for the very first time.Of course , you need to create a user id to use the service. After the first synchronization, the user has the option to synch the local copy with the server or vice-versa.

While the tool is pretty handy and efficient, it has a few annoyances. Why, for example do I need to manually install the tool on every computer before synchronizing my bookmarks. I feel that Foxmarks should offer to self-install, if a user logs into the Foxmarks account from a non-Foxmarks installed browser. Further, the tool does not allow the synchronization of selective folders. This feature would be handy and would definitely speed up the syncing process.

In the world of online bookmarking (delicious), I find Foxmarks to be an interesting and useful application for someone who is constantly on the move.