Fork me on Github s

Posts Tagged java

Spring Roo Database Reverse Engineer with Oracle

So you are trying to reverse engineer an Oracle database with roo?

Unfortunately, due to licensing restrictions with the Oracle JDBC Drivers, this is a little difficult. There are a few blog posts and forum threads that address the problem but I figured I would post what worked for me here.

First, you need to download the appropriate Oracle Drivers from Oracle. The required login, stringent password requirements, nosy registration form, and general system instability made this a pretty painful step for me. I’d also like to say that companies that have password requirements that don’t allow symbols (or any other non-standard requirement) have a special place in my heart. Having to recover my password every time I go to your site virtually guarantees I will only go there when I absolutely have to (not often). Anyways, once you have it downloaded you need to install is with maven:

mvn install:install-file -Dfile=~/Downloads/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -DgeneratePom=true

Here comes the fun part. You need to create an osgi wrapper for the driver to install it in roo. Otherwise, roo cannot see the driver. Create a new folder and put the contents of the oracle roo addon pom gist I created. Now build it with maven. You may want to change some of the artifact ids and dependencies for your particular situation.

mvn package

No open a roo shell and execute the following command:

osgi install --url file:///Users/me/my-osgi-project/target/the-jar-it-built.jar

Now run (in roo):

jpa setup --provider HIBERNATE --database ORACLE 
dependency remove --groupId com.oracle --artifactId ojdbc14 --version 10.2.0.2
dependency add --groupId com.oracle --artifactId ojdbc6 --version 11.2.0.3
database properties set --key database.driverClassName --value oracle.jdbc.OracleDriver
database properties set --key database.url --value jdbc:oracle:thin:@%YOUR_CONNECTION_INFO%
database properties set --key database.username --value %YOUR_USERNAME%
database properties set --key database.password --value %YOUR_PASSWORD%
database reverse engineer --schema %YOUR_SCHEMA% --package ~.domain

If you have any package loading exceptions when running the reverse engineer command you can uninstall the osgi bundle, set the package to optional in the osgi pom in the IncludedPackages tag (javax.some.package.*;resolution:=optional) rebuild, then reinstall in roo.

Tags: , , ,

6 Comments

Connecting to Magento Web Services with Java

I was in the unenviable position of needing to connect to Magento, a PHP ecommerce platform, web services using Java.  It was kind of difficult to get the classes generated from the WSDL so I figured I would throw the results up on my github account for any other poor sap in a similar position.

First, pull down the project using git:

git clone git://github.com/webdevwilson/magento-java.git

and build it with maven:

mvn install

Here is a quick example of how to pull an order using the generated classes:

MagentoServiceLocator serviceLocator = new MagentoServiceLocator();
String url = "http://domain.com/index.php/api/v2_soap";
Mage_Api_Model_Server_V2_HandlerPortType port = serviceLocator.getMage_Api_Model_Server_V2_HandlerPort(url);
String sessionId = port.login("username", "key");
SalesOrderEntity salesOrder = port.salesOrderInfo(sessionId, orderId);

I also have some wrapper code in there that makes it a little easier to call the API.

Checkout the project at https://github.com/webdevwilson/magento-java

There is another option. it’s called Magja and it is located at google code.

Tags: , , , ,

No Comments

What are the downsides to using dependency injection?

I recently came across an interesting question on stack overflow with some interesting reponses.  I like this post for three reasons. First, I am a big fan of dependency injection, it forces you to decouple your code, create cohesive interfaces, and should result in testable classes. Second, the author took the approach I usually do when trying to evaluate a technique or technology; suspend personal feelings and try to find some compelling arguments against it. Third, it proved that it is very difficult to come up with a compelling argument against dependency injection.

What are the downsides to using dependency injection?

Tags: , , , , ,

No Comments

Using Java classes in JRuby

I needed to do some reflection today so I fired up interactive JRuby (jirb) to inspect a jar.  Surprisingly, I couldn’t remember exactly how to use Java classes in JRuby.  So I did some searching on the internet and found this to be a common question with many answers.  So I figure I will document it here in case I forget how in the future.

Add it’s folder to the load path, require it, then use it!

$: << '/path/to/my/jars/'
require 'myjar'

# so we don't have to reference it absolutely every time (optional)
include Java::com.goodercode

my_object = SomeClass.new

Tags: ,

1 Comment

Intercept method calls in Groovy for automatic type conversion

One of the cooler things you can do with groovy is automatic type conversion.  If you want to convert an object to another type, many times all you have to do is invoke the ‘as’ keyword:

def letters = 'abcdefghijklmnopqrstuvwxyz' as List

But, what if you are wanting to do something a little fancier, like converting a String to a Date?

def christmas = '12-25-2010' as Date

ERROR org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '12-25-2010' with class java.lang.String' to class 'java.util.Date'

No bueno!

I want to be able to do custom type conversions so that my application can do a simple String to Date conversion. Enter the metaMethod. You can intercept method calls in Groovy using the following method:

def intercept(name, params, closure) {
  def original = from.metaClass.getMetaMethod(name, params)
  from.metaClass[name] = { Class clazz ->
    closure()
    original.doMethodInvoke(delegate, clazz)
  }
}

Using this method, and a little syntactic sugar, we create the following ‘Convert’ class:

// Convert.from( String ).to( Date ).using { }
class Convert {

    private from

    private to

    private Convert(clazz) { from = clazz }

    static def from(clazz) {
        new Convert(clazz)
    }

    def to(clazz) {
        to = clazz
        return this
    }

    def using(closure) {
        def originalAsType = from.metaClass.getMetaMethod('asType', [] as Class[])
        from.metaClass.asType = { Class clazz ->
            if( clazz == to ) {
                closure.setProperty('value', delegate)
                closure(delegate)
            } else {
                originalAsType.doMethodInvoke(delegate, clazz)
            }
        }
    }
}

Now, we can make the following statement to add the automatic date conversion:

Convert.from( String ).to( Date ).using { new java.text.SimpleDateFormat('MM-dd-yyyy').parse(value) }

def christmas = '12-25-2010' as Date

Groovy baby!

Tags: ,

No Comments

Absent Code attribute in method that is not native or abstract

I got the following, quite puzzling error today when running a unit test:

java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/servlet/http/Cookie

A google search found this post, which explains that it is caused by having an interface in the classpath, and not an actual implementation.

In this case it’s the java-ee interface. To fix this I added the jetty servlet api implementation to my pom:

    
        jetty
        javax.servlet
        test
    

Piece of cake. I have run in to this before, so I figured I would capture the fix here in case I run in to it again.

Tags: ,

1 Comment

Naming your unit tests

When you create a test for your class, what kind of naming convention do you use for the tests? How thorough are your tests? I have lately switched from the conventional camel case test names to lower case letters with underscores. I have found this increases the readability and causes me to write better tests.

A simple utility class:


public class ArrayUtils {

  public static < T > T[] gimmeASlice(T[] anArray, Integer start, Integer end) {
    // implementation (feeling lazy today)
  }

}

I have seen some people who would write a test like this:


public class ArrayUtilsTest {

  @Test
  public void testGimmeASliceMethod() {
    // do some tests
  }
}

A more thorough and readable test would be:

public class ArrayUtilsTest {

  @Test
  public void gimmeASlice_returns_appropriate_slice() {
    // ...
  }

  @Test
  public void gimmeASlice_throws_NullPointerException_when_passed_null() {
    // ...
  }
  
  @Test
  public void gimmeASlice_returns_end_of_array_when_slice_is_partly_out_of_bounds() {
   // ...
  }

  @Test
  public void gimmeASlice_returns_empty_array_when_slice_is_completely_out_of_bounds() {
    // ...
  }
}

Looking at this test, you have no doubt what the method is supposed to do. And, when one fails, you will know exactly what the issue is.

Tags: , , ,

No Comments

Using runtime generic type reflection to build a smarter DAO

Have you ever wished you could get the runtime type of your generic class? I wonder why they didn’t put this in the language. It is possible, however, with reflection:

Consider a data access object (DAO) (note: I had to use brackets b/c the arrows were messing with wordpress):

public interface Identifiable {
   
   public Long getId();

}

public interface Dao< T extends Identifiable > {

  public T findById(Long id);

  public void save(T obj);

  public void delete(T obj);

}

Using reflection, we can create a DAO implementation base class, HibernateDao, that will work for any object:


import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;

public class HibernateDao< T extends Identifiable> implements Dao< T > {

  private final Class clazz;

  public HibernateDao(Session session) {
    // the magic
    ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
    return (Class) parameterizedType.getActualTypeArguments()[0];
  }

  public T findById(Long id) {
    return session.get(clazz, id);
  }

  public void save(T obj) {
    session.saveOrUpdate(obj);
  }

  public void delete(T obj) {
    session.delete(obj);
  }
}

Then, all we have to do is extend from the class:

public class BookDaoHibernateImpl extends HibernateDao< Book > {

}

Tags: , ,

1 Comment

Using Cucumber tests with Maven and Java

Want to jump right in? I have zipped up a working project, with examples. You can download it here.

What’s that? You like using Cucumber and want to use it with your Java project but your company ecosystem is not hip to JRuby?  Enter the cukes4duke project, which allows you to run cucumber with most JVM-based languages.  I am focusing on running it with the Maven plugin. This tutorial assumes you have maven installed, and Java knowledge.

Before you start, you must run the following goal. It will install JRuby and the gems to your .m2 repository.

mvn -Dcucumber.installGems=true cuke4duke:cucumber

Then add the following to your pom:

    
        
            codehaus
            http://repository.codehaus.org
        
        
            cukes
            http://cukes.info/maven
        
    

    
        
            cukes
            http://cukes.info/maven
        
    

    
        0.3.2
    

    
        
            cuke4duke
            cuke4duke
            ${cuke4duke.version}
            test
        
        
            org.picocontainer
            picocontainer
            2.8.3
            test
        
        
            junit
            junit
            4.8.1
            test
        
    

    
        
            
                cuke4duke
                cuke4duke-maven-plugin
                ${cuke4duke.version}
                
                    
                        
                  -Dcuke4duke.objectFactory=cuke4duke.internal.jvmclass.PicoFactory
                        
                        ${cucumber.debug}
                    
                    
                        ${basedir}/target/test-classes
                        --tags ~@wip
                    
                    
                        install cuke4duke --version ${cuke4duke.version}
                    
                
                
                    
                        run-features
                        integration-test
                        
                            cucumber
                        
                    
                
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                2.0.2
                
                    1.6
                    1.6
                
            
        
    

Next, create a feature file under the ‘features’ directory (at the root of your project).

features/example.feature:

Feature: Example of a feature file
  As some aspiring cuke4duke user
  I want an example of how it works
  So that I can easily setup my project to use it
  
  # This should pass
  Scenario: A simple passing scenario
    Given the letter 'A'
    When I check the letter
    Then the letter should be 'A'

Then, create a ‘step’ class under src/test/java/cukes:

src/test/java/cukes/CukeSteps.java:

package cukes;

import cuke4duke.annotation.I18n.EN.Given;
import cuke4duke.annotation.I18n.EN.Then;
import cuke4duke.annotation.I18n.EN.When;

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;

public class CukeSteps {

    private char theLetter;

    @Given("^the letter '([A-Za-z])'$")
    public void gimmeALetter(final char theLetter) {
        this.theLetter = theLetter;
    }

    @When("^I check the letter(?:s)?$")
    public void checkThem() {
        // just a stub
    }

    @Then("^the letter should be '([A-Za-z])'$")
    public void checkTheLetter(final char aLetter) {
        assertThat(theLetter, is(aLetter));
    }
}

Now, run that test using:

mvn integration-test

I have zipped up an example project with more example steps. It is located here.

Tags: , ,

37 Comments

Sweet JavaFX App on the Winter Olympics Website

Though it may be old news for people following JavaFX closely, I have just run across the JavaFX application on the Winter Olympics website.  Slick transitions and useful data make this a great example of what JavaFX can do.  I think it’s really cool that you can look at past olympics as well as the current year.

Maybe this will help generate a little buzz around JavaFX.

Check out the application on vancouver2010.com

Tags: ,

2 Comments