Category Archives: Java

Java

Code readability with FluentItarable and Java 8

Each and every developer has to think about code readability and review his habits when working with new technologies and solutions. As you probably know on 18 March 2014 Java 8 was released and changed a lot in Java world.

Just to name few main features introduced in Java 8:

  • Lambda Expressions
  • Default methods
  • Method parameter reflection.
  • etc.

Full list of features in available here.

In this article I would like to compare how usage of lambdas influence code readability on very simple examples. read more »

Java

How NOT to write tests and improve coverage

Recently I’ve found nice way of writing tests and improving test coverage.

Check this example:

public enum Fields {
	SEARCH_TYPE,
	SEARCH_CITIES,
	SEARCH_DATES,
    ...
    POINT_OF_SALE;

	public Fields[] getValues() {
		return Fields.values();
	}
}

As you can see this is quite common enum. So how to improve test coverage?

Lets write some test! You can ask how to write tests for enums. Here it goes:

public class FieldsTest extends TestCase
{
    public void test()
    {
        for (Fields type : Fields.values())
        {
            assertEquals(type, type);
        }
    }
}

You can do this if you want to sell your source code to some company and show statistics about test coverage. Something like pig in a poke.

PS. Of course it’s a joke. Never ever do this!

Eclipse Java

Fluent Builder Generator Eclipse Plugin

I was looking recently for a nice way to generate Fluent Builder pattern code in Eclipse. I tried two plugins

  1. Builder Pattern Eclipse Plugin (https://github.com/henningjensen/bpep)
  2. fluent-builders-generator-eclipse-plugin (https://code.google.com/p/fluent-builders-generator-eclipse-plugin/)
but both are not enough for me. I was looking for a plugin with ability to generate Fluent Builder for immutable class with final fields. Unfortunately both mentioned plugins work only with mutable classes.
So I decided to write my own plugin as a fork of BPEP.
Below you can see some example class and builder generated for it by FBGEP – Fluent Builder Generator Eclipse Plugin.
public class Person {
    private final String firstname;
    private final String lastname;
    private final String address;
    private final String zipcode;
    private final String city;

    public Person(String firstname, String lastname, String address,
            String zipcode, String city) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.address = address;
        this.zipcode = zipcode;
        this.city = city;
    }
}

Class with generated fluent builder:

public class Person {
    private final String firstname;
    private final String lastname;
    private final String address;
    private final String zipcode;
    private final String city;

    public Person(String firstname, String lastname, String address,
            String zipcode, String city) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.address = address;
        this.zipcode = zipcode;
        this.city = city;
    }

    public static class PersonBuilder {
        private String firstname;
        private String lastname;
        private String address;
        private String zipcode;
        private String city;

        public PersonBuilder withFirstname(String firstname) {
            this.firstname = firstname;
            return this;
        }

        public PersonBuilder withLastname(String lastname) {
            this.lastname = lastname;
            return this;
        }

        public PersonBuilder withAddress(String address) {
            this.address = address;
            return this;
        }

        public PersonBuilder withZipcode(String zipcode) {
            this.zipcode = zipcode;
            return this;
        }

        public PersonBuilder withCity(String city) {
            this.city = city;
            return this;
        }

        public Person build() {
            return new Person(firstname, lastname, address, zipcode, city);
        }

        public static PersonBuilder person() {
            return new PersonBuilder();
        }
    }
}

GitHub repository:

https://github.com/coffeedriven/fbgep

Eclipse plugin update site:

http://coffeedriven.org/fbgep/update

Java

Adding WTP Facet to project via maven

Sometimes when I add new project to my workspace I want to make it available for quick deploy to application container (in my case Tomcat). To do this I have to add WTP project facets. It can be easily done by using Maven plugins.

Check this example from pom.xml:

<profiles>
	<profile>
		<id>war</id>
		<activation>
			<activeByDefault>true</activeByDefault>
		</activation>
		<properties>
			<packaging-type>war</packaging-type>
		</properties>
		<build>
			<finalName>projectName</finalName>
			<plugins>
				<plugin>
					<artifactId>maven-eclipse-plugin</artifactId>
					<configuration>
						<wtpversion>2.0</wtpversion>
					</configuration>
				</plugin>
				<plugin>
					<artifactId>maven-compiler-plugin</artifactId>
					<configuration>
						<source>1.6</source>
						<target>1.6</target>
					</configuration>
				</plugin>
			</plugins>
			<resources>
				<resource>
					<directory>src/main/resources</directory>
				</resource>
			</resources>
			<testResources>
				<testResource>
					<directory>src/test/resources</directory>
				</testResource>
			</testResources>
		</build>
	</profile>
</profiles>

I added here maven-compiler-plugin because without this you can get following error message:

Dynamic Web Module 2.5 requires Java 1.5 or newer.

Java

Problem with handshake_failure and SSL connection

Recently I was working on integration with PayPal and I wanted to use certificate based authorization of webservices calls. It was working fine in my integration test (which can be run as standalone Java application), but it was not working when run from real application deployed to Tomcat.

I was getting this exception:

Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1943)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1059)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1294)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1321)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1305)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:523)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1087)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleHeadersTrustCaching(HTTPConduit.java:1355)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.onFirstWrite(HTTPConduit.java:1301)
at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:42)
at org.apache.cxf.io.AbstractThresholdOutputStream.write(AbstractThresholdOutputStream.java:69)
at org.apache.cxf.io.CacheAndWriteOutputStream.write(CacheAndWriteOutputStream.java:68)
at com.ctc.wstx.io.UTF8Writer.flush(UTF8Writer.java:100)
at com.ctc.wstx.sw.BufferingXmlWriter.flush(BufferingXmlWriter.java:225)
at com.ctc.wstx.sw.BufferingXmlWriter.close(BufferingXmlWriter.java:198)
at com.ctc.wstx.sw.BaseStreamWriter._finishDocument(BaseStreamWriter.java:1400)
... 135 more

So I added debug JVM option to Tomcat startup:

-Djavax.net.debug=ssl

And then I’ve found following message in logs:

http-80-Processor5, READ: SSLv3 Handshake, length = 4
*** ServerHelloDone
[read] MD5 and SHA1 hashes: len = 4
0000: 0E 00 00 00 ....
http-80-Processor5, SEND SSLv3 ALERT: warning, description = no_certificate
http-80-Processor5, WRITE: SSLv3 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 00 00 02 01 29

As we can see here application could not find certificate in keystore. After searching the web for solution I couldn’t find anything helpful. But then I also found out that when Tomcat is starting it is using trustStore from JVM (in my case located in C:\Program Files\Java\jrockit-jdk1.6.0_37-R28.2.5-4.1.0\jre\lib\security\cacerts).

So in my case solution for this problem was simple. I had problem with properties overrides and my keystore was not loaded correctly. In this case default trustStore was taken into consideration and it didn’t have requested certificate. After fixing configuration exception was gone.