Generate Java Files from XSD with Maven + JAXB

If you have an XML Schema Definition (xsd) file, you can generate fully annotated Java classes by using the Java Architecture for XML Binding (JAXB) ‘xjc‘ tool.

You can integrate your Maven project with JAXB by using the jaxb2-maven-plugin.

Add the following dependency to your pom.xml:


    <dependencies>
        ...
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.1</version>
        </dependency>
        ...
    </dependencies>

You also need to add the plugin:


        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <id>xjc</id>
                        <goals>
                            <goal>xjc</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <packageName>com.example.myschema</packageName> <!-- The name of your generated source package -->
                </configuration>
            </plugin>
            ...
        </plugins>

Your schema file needs to be saved in src/main/xsd

The code will be generated and saved in target/generated-sources/jaxb

Compile Groovy Files with Maven in your Java Project

I’ve always wanted to use Groovy in my Java projects that are built with Maven. This is very easy when using the Groovy-Eclipse compiler plugin

All you have to do is to configure the maven compiler plugin to use the groovy-eclipse-compiler:


<build>
...
<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
      <compilerId>groovy-eclipse-compiler</compilerId>
    </configuration>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-eclipse-compiler</artifactId>
        <version>2.8.0-01</version>
      </dependency>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-eclipse-batch</artifactId>
        <version>2.1.5-03</version>
      </dependency>
    </dependencies>
  </plugin>
  ...
</plugins>
</build>

You also need to add the groovy dependency (versions must match between groovy-eclipse-batch and groovy-all):


<dependencies>
  ...
  <dependency>
	<groupId>org.codehaus.groovy</groupId>
	<artifactId>groovy-all</artifactId>
	<version>2.1.5</version>
  </dependency>
            
  ...
</dependencies>

Now you can simply add your groovy source files in src/main/java or src/test/java.

If you want to separate the groovy and java files into different folders, you can do that too. Save the groovy files in src/main/groovy and the java files in src/main/java. In order for this to work, you have to have at least ONE java file in src/main/java, otherwise the files in src/main/groovy will be ignored. Alternatively, you can simply add

 <extensions>true</extensions> 

to the groovy-eclipse-compiler plugin:


 <plugin>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-eclipse-compiler</artifactId>
    <version>2.8.0-01</version>
    <extensions>true</extensions>
  </plugin>

Load Native JNI Library with Grails

Let’s say I have an application where I need to use a Native Library: libfoo.so

My code is as follows:

Accessor.java:

public class Accessor {        
    static {
        String path = "/usr/lib/libfoo.so";
        System.load(path);
    }
    ...
}

This works perfectly fine when I deploy my war file in a standalone tomcat server.

The problem is when I try to run the embedded tomcat server when you run:

grails run-app

I get an UnsatisfiedLinkError:

Caused by UnsatisfiedLinkError: com.foo.bar.GFS_MALJNI.new_Accessor__SWIG_0(Ljava/lang/String;I)J
->>   39 |     in com.foo.bar.Accessor 

Interestingly enough, if I change my BuildConfig.groovy file to fork mode, it also works.

BuildConfig.groovy:

grails.project.fork = [
   run: [maxMemory:1024, minMemory:64, debug:false, maxPerm:256]
]

I do not want to run it in fork mode.

Solution

I noticed that two different class loaders are being used.

In the non-forked mode, this class loader was being used:

java.net.URLClassLoader

In the forked mode, this class loader was being used:

groovy.lang.GroovyClassLoader

The native library works correctly in the forked mode, so I needed to come up with a hack to load the library with the GroovyClassLoader in the non-forked mode.

This is how System.load is defined in the JDK Source:

System.java:

public final class System {
    ...
    public static void load(String filename) {
        Runtime.getRuntime().load0(getCallerClass(), filename);
    }
    ...
}

It’s calling load0 with the classloader and filename. The obvious solution is to call load0 with your own classloader, but you can’t call it since it is package-protected.

When you write code in groovy, you have access to packge-protected and private methods/variables.

I can specify my own classloader and load the library, as such:

class Accessor {        
    static {
        String path = "/usr/lib/libfoo.so"
        //System.load(path);
        Runtime.getRuntime().load0(groovy.lang.GroovyClassLoader.class, path)
    }
    ...
}

Now you can load the JNI library from your Grails application during development.

Add Native Library to your Project with Maven

I have a web application where I need to include a native library using Maven.

My library already exists in the Maven Repo, so I added a plugin to my build:

pom.xml:

<project>
...
    <build>
    ...

    <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.8</version>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>com.foo.bar</groupId>
                                    <artifactId>my-library-jni-so</artifactId>
                                    <version>1.0-SNAPSHOT</version>
                                    <type>so</type>
                                    <outputDirectory>target/stage/WEB-INF/classes/lib/native/x86/linux</outputDirectory>
                                    <destFileName>my-library.so</destFileName>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
    </plugins>
    ...
    </build>
...
</project>

Load JNI Library from Classpath

I have a web application where I have to use a shared object (*.so) library using JNI.

Let’s assume my library file is named “my-library.so”

First, I will try to load it from the System path (Linux: $LD_LIBRARY_PATH). As a fallback, I will try to load it from the classpath.

import org.springframework.core.io.ClassPathResource;

public class Whatever {

    static MyNativeClass foo;

    static {
        try {
            log.debug("Loading Library from system path: " + System.getProperty("java.library.path"));

            try {
                System.loadLibrary("my-library");
            } catch (UnsatisfiedLinkError ex) {
                log.debug ("Unable to load my-library from System Path, will try to load it from Classpath");

                System.load(new ClassPathResource("lib/native/x86/linux/my-library.so").getFile().getAbsolutePath());

                log.debug ("Loaded lib/native/x86/linux/my-library.so");
            }

            foo = new MyNativeClass();
        } catch (Exception ex) {
            log.error ("Unable to load the GFS Swig Library", ex);
        }
    }
}

I am utilizing ClassPathResource from the Spring Library.

Install Mac OSX 10.8 Mountain Lion on a USB Flash Drive

Here’s what I had to do to create a Bootable USB Flash Drive with a OSX 10.8 Mountain Lion.

Before starting, you need

  • Spare flash drive with at least 6 GB of space.
  • The OSX 10.8 Mountain Lion Installer from the Mac App Store
  1. Purchase and download Mountain Lion from the Mac App Store. My brand new Macbook Pro was eligible for a free upgrade, so I didn’t have to pay to download it. Once the download is finished, do not run the installer.

    Note:
    If you already upgraded to Mountain Lion, but didn’t get a chance to save it to USB, then you have to re-download it from the App Store.






  2. Locate the Installer in Finder under Applications. Right click on it and click ‘Show Packaged Contents’





  3. Go to Contents -> Shared Support and look for the file named “InstallESD.dmg”

  4. Double click on the "InstallESD.dmg" file to mount it.
  5. Open Applications -> Utilities -> Disk Utility.

  6. Drag the “InstallESD.dmg” image to the Disk Utility sidebar.
  7. Connect a spare USB or FireWire drive that has at least 6GB of capacity, which should show up in Disk Utility.
  8. Select your USB Flash Drive in the Disk Utilty Side Bar and create a new Partition.
    • Click the Partition tab
    • Under Partition Layout, select 1 Partition
    • Click Options and Select GUID Partition Table
    • Under Format, select ‘Mac OS Extended (Journaled)’
    • Under Name, type in ‘OSX Install’
    • Hit Apply, then Partition

  9. Select "Mac OS X Install ESD" in the Disk Utility Side Bar.
    • Click on the ‘Restore’ tab
    • Drag the Partition you just created, OSX Install, to the destination section.
    • Click Restore and Erase.

  10. Once this is done, a new window will pop-up with the contents of the New Flash Drive

That’s it! You’re done!

In order to boot with the USB flash drive, restart your mac and hold on to Option + “C”. This will start the installer and you can install Mountain Lion!

Installing a new Hard Drive on a Macbook Pro

I decided to upgrade my new Macbook Pro by installing a new 360 GB Solid State Drive. The whole process is relatively simple and takes up to 10 minutes to install the new hard drive. You will need a small phillips screwdriver and a T6 Torx screwdriver.

In summary, you will need to shut down your laptop, disconnect all the cables, unscrew the back panel, discharge static electricity, unscrew the bar keeping the hdd in place, disconnect the SATA cable, remove the screws on hdd, install the new hdd, and reassemble the laptop!

I bought a 360 GB OCZ Agility 3 2.5” SATA III Solid State Disk (SSD)






You will need some way to install a Mac OS after you install the new Hard Drive. I put Mountain Lion OSX into a bootable USB flash drive. You can find instructions on how to do that here.





Step 1: Flip it over and unscrew the 10 screws in back panel. Keep note of every screw and its position on the back panel. The top 3 screws are longer than the rest and the remaining screws are slightly different.




Step 2: Remove the back panel and set it aside.






Step 3: The hdd will be on the bottom left corner. Locate the black brackett holding the hard drive. Unscrew both screws and remove the bracket.



Step 4: Disconnect the SATA cable from the hard drive.


Step 5: Remove the adhesive tape from the hard drive and set it aside (you will be re-using this).


Step 6: Remove the 4 screws on the hard drive and set it aside (you will be re-using this).

Step 7: Put the adhesive tape and 4 screws on the new hard drive

Step 8: Connect the SATA cable to the new hard drive.

Step 9: Place the bracket back in place and screw it in.

Step 10: Put the Back panel back in place and screw it in.

Step 11: Flip it over and start it up!






Now you have to format the hard drive and install the OS. Instructions for that can be found here.

References:
http://www.everymac.com/systems/apple/macbook_pro/macbook-pro-unibody-faq/macbook-pro-13-15-17-mid-2009-how-to-upgrade-hard-drive-ssd.html

Mac Keyboard Shortcuts for Developers

I have recently bought a mac and coming from a PC background, it’s taken a while to get used to all the new keyboard shortcuts.

Starting with some Basic ones — these are the same as the PC, but replacing ctrl with command:

Copy +C
Paste +V
Cut +X
Select All +A

In most apps, these shortcuts apply:

Save +S
Close Window +W
Quit Program +Q

Common Shortcuts for Developers

Scroll to the beginning of the page +UP/DOWN
Page Up/Down +UP/DOWN
Go to next word +LEFT/RIGHT
Highlight a word
+
+LEFT/RIGHT
Highlight a line
+
+LEFT/RIGHT
Delete (really delete) +Delete

For the full reference, visit http://support.apple.com/kb/HT1343

Fixed slow WIFI issue with new Macbook Pro

I just bought a new Macbook Pro

As I started playing with it, I noticed that all my software updates and downloads were taking a long time to finish.  I am paying for a 12 mbps high-speed internet connection with AT&T Uverse, but a speed test (www.speedtest.net) proved that I was only getting up to 4 mbps.

I did the same test on my iPhone and it yielded 10 mbps.

I did the same test on my PC and it yielded the max speed, 12 mbps.

Long story short, I fixed it by changing the Wifi Channel from 1 to 6.

If you are experiencing the same issue, you have to log into your router and change it as well.

First, you need to find the IP of your router.  Open Network Preferences

Click Advanced and click on the TCP/IP tab

Keep Note of the Router IP.  In my case, it is 192.168.1.254

The next step will vary from router to router.

You will have to log into your router and change the Wifi settings.

Open up a browser and enter in http://<IP of your router>.  In my case, I would enter http://192.168.1.254

In most cases you will have to log in with a username and password.  You should know this, but in case you don’t, try admin/admin, or just admin with no password.  If you are an AT&T customer, the password should be the same as the network code on the label.

 

Scroll down and find the Wireless link.  If you don’t see this, look for an option to configure your wireless settings.

Once you are there, change the wireless channel from ‘Auto’ to something else.  I selected 6 and it worked for me.

 

Good luck!