Archive

Posts Tagged ‘java’

Maven snippet – add generated sources to the build

July 21, 2014 Leave a comment

Here’s a maven snippet I found myself looking for many times – adding generated sources to the build.
This tells Maven to include the generated classes as part of the compilation, which ensures any non generated code that depends on them compiles fine, and their corresponding .class files be included in the .jar/.war file.

  ...
  <build>
    <plugins>
      ...
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>add-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>${project.build.directory}/generated</source>
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    ...
    </plugins>
  </build>
  ...

In this case (line #153) – we assume that the sources are generated to target/generated.

Some useful reading material regarding this subject:

Advertisements

Testing a large variance of inputs using Parameterized JUnit tests

April 17, 2013 4 comments

Often in utility methods (e.g. your usual StringUtils) you find yourself writing the same test over and over again with different inputs.
You can do something like this:

public class TestSomeUtils
{
      @Test
      public void test_function1_input_1()
      {
            test_function1("some-output",  7, 2.6);
      }

      @Test
      public void test_function1_input_2()
      {
            test_function1("another-output",  9, -1.56);
      }

      @Test
      public void test_function1_input_3()
      {
            test_function1("no-output",  0, 768.2341);
      }

      private void test_function1(String expectedOutput, int inputA, double inputB)
      {
            String actualOutput = SomeUtils.function1(inputA, inputB);
            assertEquals(expectedOutput, actualOutput);
      }
}

However – JUnit has a much better way of doing it – org.junit.runners.Parameterized

@RunWith(Parameterized.class)
public class TestSomeUtils
{
      private String expectedOutput;
      private int inputA;
      private double inputB;

      @Parameters
      public static Collection<Object[]> prepareData()
      {
            Collection<Object[]> args = new ArrayList<Object[]>();

            args.add(new Object[]{"some-output",  7, 2.6});
            args.add(new Object[]{"another-output",  9, -1.56});
            args.add(new Object[]{"no-output",  0, 768.2341});

            return args;        
      }

      public TestSomeUtils(String expectedOutput, int inputA, double inputB)
      {
            this.expectedOutput = expectedOutput;
            this.inputA = inputA;
            this.inputB = inputB;
      }

      @Test
      public void testSomething()
      {
            String actualOutput = SomeUtils.function1(inputA, inputB);
            assertEquals(expectedOutput, actualOutput);
      }
}

Explenation:

@RunWith(Parameterized.class) tells the JUnit framework use a non-default test runner, in which case it is the Parameterized runner.
This runner will execute all the tests on all the given inputs. So if you have 3 test methods and nine sets of inputs – you actually get 27 distinct tests.

How does it do it?

  1. It calls the prepareData method since it is annotated with @Parameters.
  2. For each Object[] in the Collection it will instantiate the test class using the Object[] as constructor arguments (Using Reflection).
  3. It will execute all the test methods in the test class

Simple, isn’t it?

I use it mostly for simple utility methods that I want to cover from end to end, but I have also used it to execute other tests as well.

Jar scanning utility – find a class within all jars (Unix/Linux)

March 28, 2013 Leave a comment

Every so often I need to figure out which jar(s) contain a certain class so I can figure out why an application acts the way it does – either since a class is missing in some environment or since the wrong class was loaded into the classpath.

When that happens, I use the following script. I saw it once in a company I worked at, and then again in another company.
I modified it slightly, but the credits do not go to me, they go to the anonymous person who wrote the initial code.

The script is available for download on GitHub.

Or you can simply copy it from here:

#!/bin/tcsh -f

if ( $#argv < 2 ) then
        printf "Scans all the JARs in the specified directory for classes matching the specified string\n"
        printf "Usage: $0 <dir> <class-name-pattern>\n"
        printf "Example: $0 . Exception\n"
        printf 'Example: '$0' $JAVA_HOME/lib "com\/sun\/.*action"\n'
        exit 1
endif

set DIR = "$1"
set CLASS = "$2"

foreach J ( `find $DIR -name "*.jar"` )
        printf "."
        set res=`jar tvf $J | grep "$CLASS" | sed 's/$/;/'`
        set outputsize = `echo $res|wc -c`
        if ( $outputsize > 1 )  then
                printf "\nMatch found in [$J]\n"
                printf  "$res\n" | tr ';' '\n'
        endif
end

printf "\n"
Categories: Java, Shell Scripting, Tools, UNIX Tags: , , , ,

Maven-Eclipse-Spring Integration

December 27, 2012 2 comments

In every new project I write I use maven and Eclipse. On most of these projects I use Spring as well – and I’m probably not the only one around doing it.

The problem I always run in to is how to configure everything to work properly – so once I finally got a properly working configuration, I had to write it down:

Simple Configuration – Maven + Eclipse
This configuration in your pom.xml will generate your .project and .classpath files (and a few more).

<plugin>
	<artifactId>maven-eclipse-plugin</artifactId>
	<version>2.9</version>
</plugin>

Slightly Advanced Configuration – Maven + Eclipse
This configuration will also automatically download sources and javadocs of any dependency you add into your project – very useful when working with open source software.

<plugin>
	<artifactId>maven-eclipse-plugin</artifactId>
	<version>2.9</version>
	<configuration>
		<downloadSources>true</downloadSources>
		<downloadJavadocs>true</downloadJavadocs>
	</configuration>
</plugin>

Spring Specific Configuration – Add Support in Eclipse
The additionalProjectnatures and additionalBuildcommands sections add the springnature and springbuilder to the project and allow you to get Spring specific highlights and notifications on your project (e.g. Icons on each class indicating if it is a Spring bean)

<plugin>
	<artifactId>maven-eclipse-plugin</artifactId>
	<version>2.9</version>
	<configuration>
		<additionalProjectnatures>
			<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
		</additionalProjectnatures>
		<additionalBuildcommands>
			<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
		</additionalBuildcommands>
		<downloadSources>true</downloadSources>
		<downloadJavadocs>true</downloadJavadocs>
	</configuration>
</plugin>

The Maven-Eclipse Plugin has a few more configurations and abilities, you can read more about it on http://maven.apache.org/plugins/maven-eclipse-plugin/

JADClipse is up and running!

November 12, 2012 6 comments

After a long time waiting, JADClipse is back on the market and fully functional with Eclipse 4.x.

Its home page can be found at: http://marketplace.eclipse.org/node/472922#.UKC1UodJ7D4

For some reason installing it from the Market place failed on my PC (Juno SR1) – but directly setting the update site to be http://feeling.sourceforge.net/update worked fine.

The new version comes with two built-in decompilers: “JD-Core” and “jad“.

One of the hidden upsides is that you no longer need to download “jad.exe” separately – the plug-in comes ready to work.

The only problem I observed so far is that the Output original line numbers as comments and the Align code for debugging options are not doing what they used to do. Perhaps this will be fixed in the future.

JADClipse – Debug Settings

Categories: Eclipse, Java, Tools Tags: , , , ,

Easy pasting of strings into Java code using Eclipse

April 8, 2012 Leave a comment

Ever tried to copy a PATH to your java code and end up needing to go into it and replacing all ‘\’ with ‘\\’ ?

Well – a coworker showed me a cool feature in Eclipse that automatically escapes text when pasting it , just go to:
Window –> Preferences –> Java –> Editor –> Typing and check the ‘Escape text when pasting into a string literal’ option. (See below image)
Now whenever you paste text into a string literal (anything that starts with “ and ends with a “) – Eclipse will automatically escape it for you.

This also works for ‘\n’ and any other escape character.

Example of what it does:
Lets say you want to print this text –

Hello everyone!
 this is a "sample" of pasting a '"' and a '\' in a string

In the code it will look like:

String text = "Hello everyone!\n" + "this is a \"sample\" of pasting a '\"' and a '\\'  in a string"

Note: This was written for Eclipse Indigo (3.7), future/past versions may differ.

Categories: Eclipse, Tools Tags: , , ,
%d bloggers like this: