Archive

Posts Tagged ‘java’

I had it with Maven

April 6, 2015 3 comments

Initially I was a big Maven fan. It was the best build tool. When coding in C I was using make and after switching to Java, naturally Ant was next.

But Maven was so much better. It had a few things that you cannot do anything but love them. First of all, dependency management. To get rid of downloading the jars, include them in a lib folder, and even the bigger pain of updating them … wow … to get rid of all of these was a breeze.

Maven had also a standard build lifecycle and you can download a project and start a build without knowing anything about it. You could have done this in Ant, but there projects should have followed a convention, which wasn’t always the case. In all honesty, it wasn’t even existing one :), at least a written formal one.

And then Maven came with a standard folder structure. If you pickup a new project it’s clearly easier to understand it and find what you’re looking for.

And … that’s about it. I would like to say that the fact that uses XML was also a good thing. XML is powerful because it can be easily understood by both humans and computers (read programs). But no other tool, except Maven, was interested in understanding its POM. And if for describing and formalizing something, like a workflow, XML is great, using it for imperative tasks – not so. Ant was doing this and going through an Ant build wasn’t the easiest task of all.

Maven was also known for its verbosity. If you go to mvnrepository.com and take any package in there you’ll clearly see the most verbose one:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.4.RELEASE</version>
</dependency>

as compared to Gradle for example

'org.thymeleaf:thymeleaf:2.1.4.RELEASE'

.

And that’s for adding just one dependency. If you have 30 or more in your project, which for a web application is not uncommon, you end up with a looot of code …

And then it comes the customization. It is very good that Maven comes with a standardized lifecycle, but if it’s not enough (and usually it isn’t) it’s very hard to customize it. To do something really useful you’ll need to write a plugin. I know that there is the exec plugin, but it has some serious drawbacks and the most important one is that it cannot do incremental builds. You can simply run a command, but you cannot do it if only some destination files are outdated compared to their corresponding sources.

So, I needed something else. I looked a little bit over some existing build tools and none of them seemed very appealing, but I ended up switching to Gradle. Two reasons: Spring is using it (I’m a big fan of many Spring projects) and I wanted to also get acquainted with Groovy.

While switching a web application project, which took me 3 days, I ended up with a 10kb build file instead of 36Kb and many added features. I was able to build my CSS and JS using Compass/Sass and browserify and more importantly incrementally (but as a whole).

I was also able to better customize my generated Eclipse project, including specify derived folders. As a side note, for improved Gradle support in Eclipse you need to install Gradle IDE from update site http://dist.springsource.com/release/TOOLS/update/e4.4/ and miminum required version is 3.6.3 – see here why. You may need to uncheck Contact all update sites during install to find required software if you get an installation error.

Gradle is probably not the dream build tool, it has a very loose syntax, it combines descriptive properties with imperative task reducing readability, but it’s less verbose and much more flexible than Maven. Probably with some coding standards applied on top, it could become a good choice.

Categories: Software Tags: , ,

Code analysis and review

January 19, 2011 6 comments

In a big team, with many developers involved, code review is essential. But do you have the tools to do it?
Certainly. As I was lately using Eclipse (and I want to do as much as possible in one place) I will further describe some plugins that will help you accomplish that.

Code analysis

I will start with some automated code analysis tool.
I’m using FindBugs and PMD. My goal is to have 100% clear report from FindBugs. On PMD, things are a little bit different, and this plugin is reporting even the slightest problems, even though they aren’t of real concern. But this tool has a useful feature, Find Suspect Cut and Paste to find duplicate code. It does not always do the best job, but increasing the tile size can help.

If you need report metrics about your project a good choice can be Metrics. It calculates a lot of metrics, it can do a dependecy analysis, export the reports into XML.

All these tools can be easily installed in Eclipse from the update sites. Then they will provide contextual menu items to run the analysis on file, folders or the entire project, displaying the results in specific views. They can be integrated in your build process, running as Ant tasks and generating reports in various formats, usually XML.

Code review

I love automation, but human intervention is the ultimate factor. In this case – code review. And the tool here is Jupiter. I must say that I love this tool – easy to use and right on target. Unlike other similar tools, it does not require an additional web application or any additional software. It stores everything on files, which can be maintained in your source versioning system, to coordinate and communicate the review between team members.
I will enter here in a few more details.
After installing Jupiter like any other Eclipse plugins and restarting the environment, you will have to setup a review, to keep everything under the same roof. So, click on the project that you want to review, then Properties > Review > New … A wizard will start to configure your review (you can edit these settings at a later time). Here you can setup

  • the review name and description;
  • the files to be reviewed – you can leave blank for all;
  • the reviewers – I would suggest to use the developer’s email addresses;
  • review folder (where Jupiter stores all the review data) – I would suggest to use /review or /.review and to store this into your versioning system, along with the file /.jupiter (where Jupiter stores the metadata about all the reviews). Be careful, if you keep the latter on the versioning system, that one contains who is the author of the review, which should be different on each machine;
  • issue types and severities – the default ones seem pretty good and they’re explained here;
  • the author of this review;
  • the default values for fields like type or severity;
  • filters for the issues for different phases of review: individual – when issues are submitted, team – when issues are discussed and assigned and rework – when issues are addressed

Now you are all set up and good to … REVIEW. Just go to a line in a file in editor, right click and select Add Review Issue … The Review Editor view will open and there you can enter all the details. You can browse the existing issues using the Review Table view and navigate directly to an issue in the file, notice the purple icon on the left side of the editor or the small purple line on the right side. Another useful feature is the ability to customize different filters, even different for each review phase.

If you will store your review files on SVN (or other versioning system), after update/checkout, don’t forget to modify in the configuration that you are the reviewer (and not the one that committed the last version). Just go to Project Properties > Review > Select a review > Edit > Author and select your name from the list. Also after update don’t forget to refresh the project and the review.

I like Jupiter, because it does not require another server or software installation, it keeps everything in some XML files so you can use your favorite versioning system and it is easy to use and straightforward. It is like a local code issue tracker, but you can also synchronize across a team using, let’s say, Subversion. And, it is integrated in Eclipse and you can do everything in one place.

Summary

Tool Eclipse update site
FindBugs http://findbugs.cs.umd.edu/eclipse/
PMD http://pmd.sf.net/eclipse
Metrics http://metrics.sourceforge.net/update
Jupiter http://jupiter-eclipse-plugin.googlecode.com/svn/trunk/site/
Categories: Software Tags:

Tip: Mouse pointer in Java

August 24, 2010 1 comment

Repetition is the mother of all learning!
Even you knew already or it is old news to you, I feel like repeating this tip: how to handle mouse pointer in Java. For doing this in a framework like Swing or SWT you have all these kind of mouse events associated with the components, but what I’m interested in is a more global view. To get (and set!) the mouse coordinates at the entire desktop level.
For getting the mouse coordinates you have the MouseInfo class. For x coordinate just call MouseInfo.getPointerInfo().getLocation().getX(). Similarly, for y is MouseInfo.getPointerInfo().getLocation().getY().
On the other hand for setting the mouse coordinates on screen, you have the Robot class and its mouseMove method.
Now putting all together and write a method that moves the mouse with a certain amount on screen:

void mouseRelMove(int dx, int dy) {
    new Robot().mouseMove(MouseInfo.getPointerInfo().getLocation().getX() + dx, MouseInfo.getPointerInfo().getLocation().getY() + dy);
}

Now you can play with your mouse. But carefully, not to get it (or you!) dizzy :).

Categories: Software Tags:

Override from 5 to 6

May 26, 2010 Leave a comment

One of the way of learning something is through exercise and trial and error process. And in the end you have the solution. Unfortunately, not everyone is documenting and sharing their learning.
This is a small tip that I learned while I had to maintain backward compatibility with Java 5 for an application written in Java 6.
While building the application, the compiler reported this error: “method does not override a method from its superclass”. Even though it seems very strange, the cause is very simple. Override annotation in Java 6 works for both methods in super classes and interfaces, as opposed to Java 5 where it works only for super classes. So actually in Java 6 this also means Implement. Unfortunately, there is no reference about it in JavaDoc.
One more tip: if you’re using Eclipse is not enough to change the JDK. You also have to change the Compiler compliance level. Just go to Project > Properties > Java Compiler and select 1.5 for Compiler compliance level.
.

Categories: Software Tags:

Programatically load Spring configuration from input stream

March 30, 2010 2 comments

Some will argue about the utility of it, but I think Spring IoC is a powerful configuration tool and it makes sense. You can have a shared configuration across a network which can change over time.
In this case you can easily create a bean factory/application context which will serve as your application configuration object.
Without any further introduction, here’s the code:

	// define and open the input stream from which we read the configuration
	InputStream input = ... ;
	// create the bean factory
	DefaultListableBeanFactory beans = new DefaultListableBeanFactory(applicationContext);
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beans);
	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
	reader.loadBeanDefinitions(new InputStreamResource(input));
	beans.preInstantiateSingletons();
	input.close();

DefaultListableBeanFactory can be replaced with GenericApplicationContext or any similar.
There are two lines that are mandatory

	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

for setting the validation mode instead of AUTO to XSD, as this cannot be automatically detected when working with streams and

	beans.preInstantiateSingletons();

without which the beans created using a factory will not be instantiated.
The solution is pretty simple and straightforward, but if you’re not a Spring expert, it might take a while until you’ll discover it yourself.

Categories: Software Tags:

Swing tip: Move by dragging

July 6, 2009 2 comments

A frame can be moved by dragging it from the title bar. But if you have a window without the title bar or you want to move it by dragging from wherever you want, this is the tip for you.
The MouseListener and MouseMotionListener will do the trick. They will be added to the JWindow that we want to move by dragging.

import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.*;

public class DragMove implements MouseListener, MouseMotionListener {

public static DragMove install(Component c) {
DragMove x = new DragMove();
c.addMouseListener(x);
c.addMouseMotionListener(x);
return x;
}

private Point start;

public void mouseClicked(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
start = e.getPoint();
}

public void mouseReleased(MouseEvent e) {
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void mouseDragged(MouseEvent e) {
Point p = e.getLocationOnScreen();
Component c = e.getComponent();
c.setLocation((int)(p.getX() - start.getX()), (int)(p.getY() - start.getY()));
c.repaint();
}

public void mouseMoved(MouseEvent e) {
}
}


Just a few explanations. When the mouse button is pressed, then the starting location relative to the window is stored. Then as the window is dragged, its location is moved on the screen relative to this starting point. And the window is repainted.
Pretty fast and simple enough.

Categories: Software Tags: ,

Visual C in Ant

February 1, 2009 2 comments

Sounds a little bit crazy, but you would probably need this more often than you think. If you develop some JNI applications this probability increases quite a bit.

Nowadays there is a big hype with the Continuous Integration and behind that usually sits a pretty solid build system. So most likely you will have to find a way to create your native libraries automatically and not from the development environment. Not to mention that you would probably want to generate your binaries on multiple environments to ensure compatibility for your JNI application. After all, it is write once, run anywhere.
And isn’t just nice to do everything from one place? One IDE, one build system, etc.

OK, I convinced you. But how do you do it? Ant is simply great when it comes about building Java applications, but what about compiling C code into native libraries? Now is the part where cpptasks jumps to give you a hand. So let’s see how your ANT file will look like for compiling your native library:

<property environment="env"/>
<condition property="iswin">
    <os family="windows"/>
</condition>
<taskdef resource="cpptasks.tasks"/>
...
<mkdir dir="${native.out}"/>
<cc outtype="shared" subsystem="console" outfile="${native.out}/${native.name}" objdir="${native.out}" name="msvc">
    <fileset dir="${native.src}" includes="*.c"/>
    <libset dir="${native.src}" libs="OtherLib"/>
    <sysincludepath location="${jdk.path}/include/"/>
    <sysincludepath location="${jdk.path}/include/win32" if="iswin"/>
</cc></pre

where

  • iswin is an Ant property set only if we are running on windows
  • native.out is the directory where the libraries and object files are generated
  • native.src is the directory containing the C source files
  • native.name is the name of the generated library
  • jdk.path is the JDK installation directory

.

As you can see the C compiler used is Visual C (name attribute of the cc task). And most probably you will need the WinAPI include file, so add the below inside your cc task:

<compiler name="msvc">
    <sysincludepath location="${env.WindowsSdkDir}/include"/>
</compiler></pre

And now comes the messy part. The environment variable WindowsSdkDir must be defined. Without this the compiler won’t even start and you will get an error like this:

Could not launch cl: java.io.IOException: Cannot run program "cl" (in directory "native\out"): CreateProcess error=2, The system cannot find the file specified

.

But fortunately there is a workaround and it is pretty simple, even tough not beautiful. In the Windows SDK distribution there is a .bat file that defines all the necessary environment variables: vsvars32.bat. And its location is defined in an environment variable: VS90COMNTOOLS for Visual Studio 2008 and VS80COMNTOOLS for Visual Studio 8.

So all you have to do is run (in the same CMD session) “%VS90COMNTOOLS%\vsvars32.bat” before running your Ant build (or launching your IDE). And no, there is no (clean) way to set an environment variable from Ant or Java.

Categories: Software Tags: ,

Rotate images according to EXIF info

November 14, 2008 9 comments

Some digital cameras are saving the snapshots as they come from the digital sensor. This is not always the right orientation, as it depends on how you are position the camera. Luckily, the cameras are also saving the orientation information into EXIF attributes.
This article is about how to automatically correct this from your Java program, using jMagick. The entire thing can be break down into pieces: read an EXIF attribute for an image, interpret the value and transform the image.
The EXIF attribute responsible for orientation is called Orientation. According to EXIF specs, the values have the following meaning:

  • 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
  • 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
  • 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
  • 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
  • 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
  • 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
  • 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
  • 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
  • Other = reserved

Graphically, this looks like this: orientation.
The following transformations should be applied to the images according to their EXIF orientation:

Autorotate EXIF images

Autorotate EXIF images


where the possible operations are horizontal or vertical flip and rotate (90 degrees clockwise or counter-clockwise and 180 degrees). The corresponding jMagick methods from MagickImage class are:

  • horizontal flip – flip()
  • vertical flip – flop()
  • rotate 180 degrees – rotate(180)
  • rotate 90 degrees clockwise – rotate(90)
  • rotate 90 degrees counter-clockwise – rotate(-90)

Now let’s translate everything into Java code:

private static final int NONE = 0;
private static final int HORIZONTAL = 1;
private static final int VERTICAL = 2;
private static final int[][] OPERATIONS = new int[][] {
        new int[] {  0, NONE},
        new int[] {  0, HORIZONTAL},
        new int[] {180, NONE},
        new int[] {  0, VERTICAL},
        new int[] { 90, HORIZONTAL},
        new int[] { 90, NONE},
        new int[] {-90, HORIZONTAL},
        new int[] {-90, NONE},
        };

public static MagickImage rotateByExif(MagickImage image) throws MagickException {
    try {
        int index = Integer.parseInt(image.getImageAttribute("EXIF:Orientation")) - 1;
        int degrees = OPERATIONS[index][0];
        if (degrees != 0)
            image = image.rotateImage(degrees);
        switch (OPERATIONS[index][1]) {
            case HORIZONTAL:
                image = image.flopImage();
                break;
            case VERTICAL:
                image = image.flipImage();
        }
    }
    catch (NumberFormatException exc) {}
    catch (NullPointerException exc) {}
    return image;
}

Now you can simply call the rotateByExif method. For more information on how you can use jMagick to load and save images please see the official documentation or see Watermark with jMagick article. Actually you can even integrate this, so that you apply it to the watermarked images.

So actually it is pretty simple to rotate images according to the EXIF info using jMagick: just get the EXIF Orientation attribute with getImageAttribute() method and, according to its value, apply the rotateImage, flipImage and flopImage.

Categories: Web Tags: ,

Detecting process exit in Java

November 3, 2008 12 comments

If you develop a more complex system, the chances of being a heterogeneous are pretty big. So if you develop a system in Java, but you have to integrate all ready build parts with other technology, the most desirable option is some kind of service oriented architecture. But when this is not available you will simply rely on an external process.
To start an external process is quite simple. Just look at the exec methods from Runtime.
What could be more difficult is to know when that process as finished. The Java process and that subprocess will run in parallel. If you want to perform an action when the subprocess has finish its execution, this article may help you in this direction.
It would be very nice if the Process class would implement the Observable design pattern in some way. But it doesn’t and on this we will base our workaround creation.
Process contains a useful method for us, waitFor, that pauses the current thread execution until the given subprocess is finished. So, we will create a thread that will be suspended until the given subprocess is finished. Then we will fire the listeners to notify that the process has finished its execution.
Enough talking, let’s see some code.

/**
 * Detects when a process is finished and invokes the associated listeners.
 */
public class ProcessExitDetector extends Thread {

    /** The process for which we have to detect the end. */
    private Process process;
    /** The associated listeners to be invoked at the end of the process. */
    private List&lt;ProcessListener&gt; listeners = new ArrayList&lt;ProcessListener&gt;();

    /**
     * Starts the detection for the given process
     * @param process the process for which we have to detect when it is finished
     */
    public ProcessExitDetector(Process process) {
        try {
            // test if the process is finished
            process.exitValue();
            throw new IllegalArgumentException("The process is already ended");
        } catch (IllegalThreadStateException exc) {
            this.process = process;
        }
    }

    /** @return the process that it is watched by this detector. */
    public Process getProcess() {
        return process;
    }

    public void run() {
        try {
            // wait for the process to finish
            process.waitFor();
            // invokes the listeners
            for (ProcessListener listener : listeners) {
                listener.processFinished(process);
            }
        } catch (InterruptedException e) {
        }
    }

    /** Adds a process listener.
     * @param listener the listener to be added
     */
    public void addProcessListener(ProcessListener listener) {
        listeners.add(listener);
    }

    /** Removes a process listener.
     * @param listener the listener to be removed
     */
    public void removeProcessListener(ProcessListener listener) {
        listeners.remove(listener);
    }
}

The code is very easy to understand. It creates a class as the detector for the process exit. It has a process to watch for passed in as a constructor argument. The entire thread does nothing else than wait for the given process to finish and then invokes the listeners.
The code for the ProcessListener is as easy:

public interface ProcessListener extends EventListener {
    void processFinished(Process process);
}

Now you have a very easy way to detect when a subprocess is finished, and as proof, here is a code sample:

    // ...
    processExitDetector = new ProcessExitDetector(subprocess);
    processExitDetector .addProcessListener(new ProcessListener() {
        public void processFinished(Process process) {
            System.out.println("The subprocess has finished.");
        }
    });
    processExitDetector.start();
    // ...

.
All the code samples were tested with JDK 6 under Windows XP.

Categories: Software Tags:

Watermark with JMagick

October 13, 2008 2 comments

I know you can do watermarking in thousands of ways, but this is if you want to embed it in your Java application. I know that you can also do this with Java2D, but it’s so much easier with ImageMagick. Moreover you have JMagick distributions for most of the major OSes.
First of all, if you haven’t heard about JMagick, this is the Java/JNI implementation for ImageMagick.
Unfortunately the JMagick documentation is very few and it includes only a few examples.
This next example will guide step by step in adding a watermark to an image. The idea is simple: first you create a watermark image from a text and then combine this image with your initial image.
So, let’s create the watermark image. If you want to watermark more than one image, this will be a one time only step.

    // create the watermark image info structure
    ImageInfo markImageInfo = new ImageInfo();
    // set a size for the image high enough to accommodate the text 
    markImageInfo.setSize("1024x1024");
    // create the image
    markImage = new MagickImage();
    markImage.allocateImage(markImageInfo);
    // make the image transparent
    markImage.setMatte(true);
    // set the background image to black
    // actually the color doesn't matter, only the alpha value - 65535
    markImage.setBackgroundColor(new PixelPacket(0, 0, 0, 65535));
    // make the initial black background color transparent
    markImage.transparentImage(new PixelPacket(0, 0, 0, 0), 65535);

Now what we have is an image with a black transparent background. Next we have to paint the text on it. For this we will create the drawing and put it into the image.

    // create the drawing info structure
    ImageInfo drawInfo = new ImageInfo();
    // create the drawing structure
    DrawInfo draw = new DrawInfo(drawInfo);
    draw.setOpacity(0);
    draw.setGeometry("+0+0");
    draw.setGravity(GravityType.CenterGravity);    
    // set the watermark color to gray
    draw.setFill(new PixelPacket(0xaf00, 0xaf00, 0xaf00, 0));
    // set the font size
    draw.setPointsize(48);
    // set the font name or the path to the font file
    draw.setFont("Arial");
    // set the watermark text
    draw.setText("Adrian's blog");
    // make the text smoother
    draw.setTextAntialias(true);

Now we have the text and we have to put it into the watermark image:

    // draw the text on the image
    markImage.annotateImage(draw);
    // remove the transparent borders of the image so that only the text will remain
    markImage = markImage.trimImage();

The initial setup is finished. Now we have to load every image that we want to watermark it, combine it with the watermark image and save it.

    // load the image from the specified filename
    ImageInfo imageInfo = new ImageInfo(filename);
    MagickImage image = new MagickImage(imageInfo);
    // watermark the image
    image.compositeImage(CompositeOperator.HardLightCompositeOp, markImage, 10, 10);
    // save the image
    image.setFileName(watermarkedFilename);
    image.writeImage(imageInfo);

The watermark is put in the upper left corner, 10 pixels away from both borders. This is actually what the third and fourth parameters of the compositeImage method represent.
Instead of CompositeOperator.HardLightCompositeOp you may also use CompositeOperator.SoftLightCompositeOp or CompositeOperator.OverlayCompositeOp.
If you probably watermark the image you may also want to resize it

    image = image.scaleImage(newWidth, newHeight);

or remove the EXIF and IPTC info from it

    image.profileImage("*", null);

So, in just a few easy steps you were able to watermark an image (or more) with your text. The nice part is that using JMagick you can do a lot of other stuff with the same ease.
This solution can be easily embedded into GUI or web applications.

Later edit: I also tried the DissolveOp and the results are very good.

Categories: Software Tags: ,