Thursday, 5 September 2013

Cool tip of the day: Maven & Eclipse ... importing projects

Today I attempted to import a project that had been written using MAVEN as its build process.
So I confidently when to the eclipse option to import existing maven projects ... all went well until I opened the project & tried to build it. when I saw this error:

Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-resources-plugin:2.4.3:resources (execution: default-resources, phase: process-resources)   pom.xml /test line 6    Maven Project Build Lifecycle Mapping Problem
This was not very welcome and the eclipse autofix options did not fix the issue.
So I turned to Slastdot & found a post (http://stackoverflow.com/questions/7638562/import-maven-project-to-eclipse-and-fix-the-errors) but the top solution to to do a project update did not work.

So to fix it I followed a secondary solution (after deleting the .project file previously created) ...


  1. Open the project folder in a command prompt;
  2. run command mvn eclipse:eclipse
  3. Open the project using eclipse;
  4. Set project properties "configure-->Convert to Maven Project"
My experience is that this works nicely.... ALMOST!

The issue is that eclipse may not correctly pick up the maven dependencies.
This is because the .classpath file does not include values on the paths as  follows "<attribute name="maven.pomderived" value="true"/>".

This for a simple project means that you needs to convert your .classpath file from this:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
  <classpathentry kind="src" path="src/test/java" output="target/test-classes" including="**/*.java"/>
  <classpathentry kind="src" path="src/main/java" including="**/*.java"/>
  <classpathentry kind="output" path="target/classes"/>
  <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
  <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/>
</classpath>

to this:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
  <classpathentry kind="src" path="src/test/java" output="target/test-classes" including="**/*.java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
  <classpathentry kind="src" path="src/main/java" including="**/*.java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
  <classpathentry kind="output" path="target/classes"/>
      <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
      <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
</classpath>

Now this should pick up your MAVEN dependencies.

Other references:

  1. http://stackoverflow.com/questions/2037188/how-to-configure-eclipse-build-path-to-use-maven-dependencies
  2. https://groups.google.com/forum/#!topic/scala-ide-user/M9pMpZGD624

Cool tip of the day: Formatting source code for your blog

Oh finally!
I have pasted code into my blog & it has been a real pain to get it right.
While looking around I found a resource on blogspot http://formatmysourcecode.blogspot.co.uk/ which provides an online utility to format the script into html to include on your blog.
It has two outputs, one with inline CSS and the other with a set of styles used.
The "linked style sheet" option depends on a PRE.source-code style.

An example of this formatting is as follows:

/**
 * The HelloWorldApp class implements an application that
 * simply prints "Hello World!" to standard output.
 */
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

A second resource can be found at http://codeformatter.blogspot.co.uk/ which has similar options  but allows you to define whether you have line numbers on your code. When you don't use embedded styles it creates a style element which defines two classes pre.CICodeFormatter and code.CICodeFormatter.

An example of this output is as follow:

1:  /**  
2:   * The HelloWorldApp class implements an application that  
3:   * simply prints "Hello World!" to standard output.  
4:   */  
5:  class HelloWorldApp {  
6:    public static void main(String[] args) {  
7:      System.out.println("Hello World!"); // Display the string.  
8:    }  
9:  }  

A third which I have yet to check is "How to use PrettyPrint to format source code in Blogger" which is a utility on blogger.com which is where this site is.
But more on this an other day.

Saturday, 31 August 2013

Transitioning from ANT to MAVEN

Well I have been putting together ANT scripts for some time now and I have created some funky scripts.
My main issue with ANT was that I had to do all the hard work over and over again. I did work to include IVY into my projects but it was just hard work and the scripts grew in complexity.
I had heard good things about MAVEN so I thought I might as well get stuck into it.

After some successes I smacked straight into an issue regarding the precompilation of JSPs which seems to be a dead topic as the plugins do not seem to work correctly or only work if you are building a WAR.
I want to precompile some JSPs and put them into a JAR ... but no joy.
So right now I am looking back at the ANT scripts and looking how best to include them in to MAVEN.

The first clue was a post on Slashdot titled "Multiple antrun tasks in maven".

The key is to have a series of ANTRuns stuck into your MAVEN script as follows:
<plugin>

    <artifactId>maven-antrun-plugin</artifactId>
    <executions>

        <execution>
            <id>clean</id>
            <phase>clean</phase>
            <configuration>
                <tasks>
                    <echo message = ">>>>>>>>>>>>>>>>>>>>>>>>>>clean"/>
                </tasks>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>

        <execution>
            <id>compile</id>
            <phase>compile</phase>
            <configuration>
                <tasks>
                    <echo message = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>compile"/>
                </tasks>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>

        <execution>
            <id>package</id>
            <phase>package</phase>
            <configuration>
                <tasks>
                    <echo message = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>package"/>
                </tasks>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>

    </executions>

</plugin>
asas

Friday, 26 July 2013

Debug Java applications remotely with Eclipse

The screens in eclipse
You don't need to debug Java™ applications on just your local desktop.
Remote debugging can be useful for application development, such as developing a program for a low-end machine that cannot host the development platform, or debugging programs on dedicated machines like Web servers, whose services cannot be shut down. Other examples include Java applications running with limited memory or CPU power, such as mobile devices, or developers wanting to separate the application and development environments, etc.

Full article: http://www.ibm.com/developerworks/opensource/library/os-eclipse-javadebug/index.html 

If you don't have it already, download Eclipse V3.4 (Ganymede). In Ganymede, the socket listening connector has been added to the Remote Java Application launch-configuration type. Eclipse's new socket listening connector allows you to start the Java debugger, which listens for a connection on a specific socket. The program being debugged can then be started with command-line options to connect to the debugger. Prior to the Ganymede release, only a socket-attaching connector was provided, and the program being debugged had to be a debug host that was connected by the debugger. It is impractical for mobile devices to be a host due to insufficient memory and CPU power.

The Java Debug Wire Protocol (JDWP) contains many arguments that have been added to invoke the application for the remote Java application. Following are some of the arguments used in this article.
-Xdebug
Enables debugging features.
-Xrunjdwp:<sub-options>
Loads the implementation of JDWP in the target VM. It uses a transport and the JDWP protocol to communicate with a separate debugger application. Specific suboptions are described below.
Starting from Java V5, you can use the -agentlib:jdwp option, instead of -Xdebug and -Xrunjdwp. But if you have to connect to the VM prior to V5, -Xdebug and -Xrunjdwp will be the only choice. Following are brief descriptions of the -Xrunjdwp suboptions.
transport
Generally, socket transport is used. But shared-memory transport can also be used on the Windows platform, if available.
server
If the value is y, the target application listens for a debugger application to attach. Otherwise, it attaches to a debugger application at the specified address.
address
This is the transport address for the connection. If the server is n, attempt to attach to a debugger application at this address. Otherwise, listen for a connection at this port.
suspend
If the value is y, the target VM will be suspended until the debugger application connects. 
This is ideal for setting up remote debugging for eclipse.
The typical settings would be "-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n".

This article lists some nice options for remote debugging a Liferay portal.
http://holisticsecurity.wordpress.com/tag/eclipse/
Enjoy. 

PS.

Friday, 5 July 2013

Cool tool of the day: vLetter

Vletter is a nice way to create handwritten text quickly.

As they say on their site:

We create your own handwriting fontto use on your computer. vLetter captures the natural variations in your handwriting to give your letters, cards and other correspondence a unique, personal touch. Your handwriting font also includes your signature, so you can sign documents and letters with ease. We've been creating personal handwriting fonts since 1988!
Any way its kinda fun ...

Cheers

Friday, 21 June 2013

Setting up Eclipse check list (Part 1)

I find my self due to a major laptop Snafu setting up eclipse from scratch (again) so I thought I would document the stages.

Download Eclipse IDE

You need the IDE for java developers and the latest version can be found here: http://www.eclipse.org/downloads/.
Once it is downloaded upzip it to a target folder.
For this install it will be "C:\development\java\eclipse\indigo". What ever you do don't include any spaces in the path as certain java tools don't like it.
I have also named it with the version so I can install others later.
Set your self up a windows short cut to avoid hunting for it later.

Edit the Eclipse.ini to optimise settings

While eclipse should run straight out of the box (unless you download the 32bit one and are running on a 64 bit system).
Before modifying the eclipse.ini file please back it up. The ini file can be error prone with returns and spaces.

I have an other post which will detail some of the settings you need but they boil down to these:

-vmargs
-Xverify:none
This will tell the VM not to validated all the .class files it is loading.
-vm
<Path to JDK>/jre/bin/server/jvm.dll
Aledgedly Eclipse runs better when linked to a specific dll.
A desirable side effect of this is that if there are any problems with Ports the fire wall will now report "Eclipse" is requesting to access ... sooner than "Java".
Please note the new line after the -vm param.
-vmargs
-Xms128m
-Xmx2048m
Give your self some more memory space. Particularly if you have plenty of memory on your PC.
-vmargs
-Dosgi.requiredJavaVersion = 1.6
Tell Eclipse that it can use the latest version of Java.
-vmargs
-Dosgi.requiredJavaVersion=1.6
-XX:+AggressiveHeap
-XX:+AggressiveOpts
-XX:+UseParallelOldGC
-XX:ParallelGCThreads=2
-XX:ThreadPriorityPolicy=1
This is an alternate option to setting up the size of memory by hand and these options do not work with -Xms and -Xmx.
They work as follows:
  • The -XX:+AggressiveHeap option inspects the machine resources (size of memory and number of processors) and attempts to set various parameters to be optimal for long-running, memory allocation-intensive jobs. It was originally intended for machines with large amounts of memory and a large number of CPUs, but in the J2SE platform, version 1.4.1 and later it has shown itself to be useful even on four processor machines.
  • A feature available with the throughput collector in the J2SE platform, version 1.4.1 and later releases is the use of adaptive sizing (-XX:+UseAdaptiveSizePolicy), which is on by default. Adaptive sizing keeps statistics about garbage collection times, allocation rates, and the free space in the heap after a collection. These statistics are used to make decisions regarding changes to the sizes of the young generation and tenured generation so as to best fit the behavior of the application. Use the command line option -verbose:gc to see the resulting sizes of the heap.
  • UseParallelOldGC
    Use the Parallel Old garbage collector, This flag enables a parallel version of both the young- and old-generation collectors.
    "UseParallelGC" Use the Parallel Scavenge garbage collector which only enables a parallel collector for the young generation and keeps a serial collector for the old generation.  A serial collector is a single-threaded collector, while the parallel collector that we are enabling can use multiple threads to collect garbage.
    -XX:+UseParallelOldGC is preferred for newer Java releases.
  • -XX:+AggressiveOpts Turns on point performance optimizations.
    Note: this option is experimental! The specific optimizations enabled by this option can change from release to release and even build to build. You should reevaluate the effects of this option with prior to deploying a new release of Java.
  • -XX:ParallelGCThreads=2 Number of parallel threads parallel gc will use. If too more ParallelGCThreads are specified than CPU cores where the JVM is running, this can cause bottlenecks.
    I have 4 cores (:P) so I'm going to use two to prevent it grabbing every thing.
  • -XX:ThreadPriorityPolicy=1
    As 0 = Normal and 1 = Aggressive.
    On Linux thread priorities are ignored because the OS does not support static priority but on windows it works.
    This policy should be used with care, as sometimes it can cause performance degradation in the application and/or the entire system. However, with ThreadPriorityPolicy=0, VM will not use the highest possible" native priority,


Eclipse Preferences
  • Windows -> Preferences; General --> [x] Show heap status.The best way to monitor the current memory useage in Eclipse is to enable HEAP monitoring:

  • Windows -> Preferences; General -> Appearance -> Label Decorations
    disabling label decorations you don't need;
  • Windows -> Preferences; General -> Startup and ShutdownGet rid of "Usage data gathering", "Equinox ...", "Mylyn..>", "Market Place client".
  • Windows -> Preferences;  MavenTurn off all un needed options on the first Maven tab (all?)
  • Windows -> Preferences;Mylyn --> TasksTurn of sysncronization;

At this point Eclipse should run like lightning.
The next thing to do is to start adding in your plugins.
This is the topic of the next post.

So for reference my eclipse.ini looks like this:

-vm
C:/development/tools/Java/jdk1.7.0_17/jre/bin/server/jvm.dll
-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XX:+AggressiveHeap
-XX:+AggressiveOpts
-XX:+UseParallelOldGC
-XX:ParallelGCThreads=2
-XX:ThreadPriorityPolicy=1
-Xverify:none




See: http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html



(Next>>)

Friday, 7 June 2013

Oh why didn't I ask these questions at my interview!

There are times when you are in an interview and you are ask "Do you have any questions for us?".
On many occasions I thought I had interesting and insightful questions which would help me get the job (ps this works the other way round too).
However I should have been asking the 12 questions from the Joel test as they are the ones that really matter to developers.
In case you are not sure what they are let me reproduce them here:
The Joel Test
  1. Do you use source control?
  2. Can you make a build in one step?
  3. Do you make daily builds?
  4. Do you have a bug database?
  5. Do you fix bugs before writing new code?
  6. Do you have an up-to-date schedule?
  7. Do you have a spec?
  8. Do programmers have quiet working conditions?
  9. Do you use the best tools money can buy?
  10. Do you have testers?
  11. Do new candidates write code during their interview?
  12. Do you do hallway usability testing?
As you can see they are pretty good ... go to Joel test and read the definitions or just ask how much your company scores.
The company I am currently working for only scores 3/12 on the Joel test and that is because I  am being generous.

There is a new version of the Joel test because it is 10 years old and things move on in that time.
This new version can be found here (http://geekswithblogs.net/btudor/archive/2009/06/16/132842.aspx).

The Joel Test

  1. Do you have a change management system?
    There needs to be a configuration management plan, control of assets beyond “source code”, branching and merging strategy (even if it’s not to branch), release stabilization and deployment plan, security permissions and roles, quality gates for checking and/or merge, etc. Otherwise, “use source control” is just referring to a glorified backup system. 
  2. Can everyone make a build in one step? Individual developers need access to the automated build system. The official nightly build can “build everything”, but developers need to be able to build individual parts, pull together the required assets, and run from a representative staging area – maybe a virtual machine (or two), a network share, or just a folder on disk. 
  3. Do your daily build include automated tests? It’s not enough to just build – we need an indication of build quality. “Break the build” should mean more than “does not compile”, it should also mean “does not pass the tests”. 
  4. Is work item tracking integrated with source control? What artifacts were changed with a given bug fix? What bug or development task is associated with the most recent change-set? Which bugs are associated with a given merge? Check-outs (or commits, depending on the source control system in use), must be associated with bug reports or development tasks. Each check-in should reflect changes for one task (unless they are coupled tasks). You should also be able to query, based on a bug report, which artifacts were changed (or ideally, currently in the process of being changed). In other words, change management must be integrated with bug tracking and project task tracking. 
  5. Do you fix bugs and write new code?A properly run project will have a branching / merging strategy (or tagging/labeling policy) that allows simultaneous bug fixes with new development. A quality organization will be able to correct bugs in previous releases, and ensure those corrections are in the current release. Without copying or duplicating the code base.
  6. Do you track progress and manage change?
    Project tracking must include processes that allow for managing (planning / executing / tracking) change as well as tracking progress and periodic re-planning of the remaining work. 
  7. Do you have a requirements management system? The “spec” will change; that change needs to be managed. Too often I see organizations with an excellent process for development of the “spec” and a horrible process for managing change in the spec. Note: In 2010, if you don’t have a “spec”, you automatically get a ZERO on the new Joel Test and there is no point in continuing on. 
  8. Do programmers have quiet working conditions and teaming rooms? The teaming rooms are more than a room with a white-board. There is a conference phone, computers (more than one), projector, and lots of white boards. Code reviews, code walk-through, mentoring, design, dispute resolution, meeting with customers – can all take place here. 
  9. Do you use the best tools money can buy or the latest open source tools?
    No change needed. This one is timeless but with a minor tweek.
  10. Are your testers involved in requirements management? The test team needs to be involved in the requirements management system as well as the product validation process. Tests are executed against the requirements. The testers should have authority to approve/reject a deployment as well as approve or reject a requirement. Otherwise, they’re just testers. 
  11. Do new candidates review code during their interview? “Writing code” is one thing – understanding code is another. Candidates should be able to answer questions like “is this code thread-safe?”, “is the code well-commented?”, or “Is the implementation appropriate” – and why. Printing fizz-buzz is one thing; being able to appropriately critique a page of code is another. As a bonus, you could always ask them to re-write it and get the best of both.
    Or you could throw a random biut of open source at them and ask them to explain it.
  12. Do you do hallway usability testing? No change there.
On this scale my new job scores 0/12.

Oh Crap!