Friday, February 12, 2016

Apache Commons ToStringBuilder

It's not always possible to override the toString method, but luckily the Apache guys have a fix for that! In Apache Commons Lang you can find a class named ToStringBuilder.  It can, using reflection, output the value of all attributes in a class, that might not have a useful toString method.
It offers quite a few ways of formatting the output and you can even make your own formatting style.
Below class does not override the toString method, but with ToStringBuilder it's possible to nicely print the values.

 package com.blogspot.jpdevelopment.example.tostring;  
   
 public class ToString {  
   
   private final String attributeOne;  
   private final String attributeAnother;  
   
   public ToString(String attributeOne, String attributeAnother) {  
     this.attributeOne = attributeOne;  
     this.attributeAnother = attributeAnother;  
   }  
 }  
   

Using ToStringBuilder, output will be like in the comments above each System.out line.
 ToString toString = new ToString("attributeOne", "attributeAnother");  
   
 // com.blogspot.jpdevelopment.example.tostring.ToString@31befd9f[attributeOne=attributeOne,attributeAnother=attributeAnother]  
 System.out.println("Default toString: " + ToStringBuilder.reflectionToString(toString));  
   
 // attributeOne,attributeAnother  
 System.out.println("Simple toString: " + ToStringBuilder.reflectionToString(toString, ToStringStyle.SIMPLE_STYLE));  
   
 // com.blogspot.jpdevelopment.example.tostring.ToString@31befd9f[  
 //    attributeOne=attributeOne  
 // attributeAnother=attributeAnother  
 // ]  
 System.out.println("Multi line toString: " + ToStringBuilder.reflectionToString(toString, ToStringStyle.MULTI_LINE_STYLE));  
   
 // ToString[attributeOne=attributeOne,attributeAnother=attributeAnother]  
 System.out.println("Short prefix toString: " + ToStringBuilder.reflectionToString(toString, ToStringStyle.SHORT_PREFIX_STYLE));  
   
 // com.blogspot.jpdevelopment.example.tostring.ToString@31befd9f[attributeOne,attributeAnother]  
 System.out.println("No field names toString: " + ToStringBuilder.reflectionToString(toString, ToStringStyle.NO_FIELD_NAMES_STYLE));  

To make you own style, simple make a class that extends ToStringStyle.
 public class MyToStringStyle extends ToStringStyle {  
   
   public MyToStringStyle() {  
     this.setUseClassName(true);  
     this.setUseIdentityHashCode(false);  
     this.setUseFieldNames(true);  
     this.setContentStart("[start]");  
     this.setFieldSeparator(",");  
     this.setFieldSeparatorAtStart(false);  
     this.setContentEnd("[end]");  
   }  
 }  

The output now looks like this.
 // Custom toString: com.blogspot.jpdevelopment.example.tostring.ToString[start]attributeOne=attributeOne,attributeAnother=attributeAnother[end]  
 System.out.println("Custom toString: " + ToStringBuilder.reflectionToString(toString, new MyToStringStyle()));  

Thursday, February 4, 2016

Mapping a list with no root element using Jersey and Moxy

Consider this piece of JSon code. To map this into a List of Strings is not always as easy it one might think.

 [  
   "ListElement1",  
   "ListElement2",  
   "ListElement3"  
 ]  
If you just do like below:
 ClientConfig clientConfig = new ClientConfig();  
 Client client = ClientBuilder.newClient(clientConfig);  
 WebTarget webTarget = client.target("http://localhost/service");  
 Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);  
    
 Response response = invocationBuilder.get();  
 List<String> owners = response.readEntity(ArrayList.class);  
You will get an error like this:
 org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=class java.util.ArrayList, genericType=class java.util.ArrayList.  
To solve the problem, use a GenericType.
 ClientConfig clientConfig = new ClientConfig();  
 Client client = ClientBuilder.newClient(clientConfig);  
 WebTarget webTarget = client.target("http://localhost/service");  
 Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);  
   
 Response response = invocationBuilder.get();  
 List<String> owners = response.readEntity(new GenericType<List<String>>() { });  
This should do the trick. It will work for Map's as well.

Monday, November 16, 2015

Create entity objects from DB schema using IntelliJ IDEA

 If you have a database schema and needs to create the entity objects matching the schema, Intellij IDEA can help you! All you have to to is follow this simple guide.

 Setup data source

Start by adding a data source to the project, by clicking the "Database" tab in the right hand side of Intellij.
Click the green plus, navigate to "Data Source" and choose "MySQL".
 Enter the data source info for the db you wish to connect to and click OK.

Add framework support

Add framework support by right clicking the project.

Choose framework

Choose "JavaEE Persistence" as framework. Set version to 2.1, provider to Hibernate and click OK. A persistence.xml file will be created, which can be deleted after entity objects has been created.

Assign data source

A new tab should be added in the left hand side of IntelliJ, named "Persistence". Click it and a new Persistence frame opens. Right click the persistance unit (ticketing-core) and choose "Assign Data Sources..."

Select data source

Assign a data source to the persistence unit and click OK.

Generate mapping

Generate a mapping by right clicking the persistence unit and choose "Generate Persistence Mapping" and then "By Database Schema".

Choose entities

Choose a data source, package and the schemas, click OK and Yes in the pop up. You should now have some some nice entity objects with basic mapping annotations!





Wednesday, May 20, 2015

Various Java trips and tricks

This blog will list some nice tips and tricks that is good to know.

Classpath resource to java.net.URL

To get a java.net.URL from a classpath resource do:
 URL url = getClass().getClassLoader().getResource("some.file");  

Classpath resource to java.io.InputStream

 To get a java.io.InputStream from a classpath resource do:
 InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream();  

Classpath resource to java.io.File

 To get a java.io.File from a classpath resource do:
 File file = new File(this.getClass().getResource("some.file").toURI());  

Iterate through a Map

 for (Map.Entry<String, String> entry : map.entrySet()) {  
   System.out.println(entry.getKey() + "/" + entry.getValue());  
 }  

Find current root directory

 File rootDirectory = new File(System.getProperty("user.dir")); 

Sunday, April 19, 2015

Connecting to MongoDB using Spring Data

In this blog I will show how easy you can connect to a MongoDB using Spring Data. For installation of MongoDB, go to http://docs.mongodb.org/manual/installation/

The dependencies needed besides standard Spring dependencies are spring-data-mongo and mongo-java-driver.
 <dependency>  
     <groupId>org.mongodb</groupId>  
     <artifactId>mongo-java-driver</artifactId>  
     <version>2.12.4</version>  
 </dependency>  
 <dependency>  
     <groupId>org.springframework.data</groupId>  
     <artifactId>spring-data-mongodb</artifactId>  
     <version>1.6.0.RELEASE</version>  
 </dependency>  

First lets create some domain objects. Department is a simple object with only only one attribute representing a department.

 public class Department {  
   
     private final String name;  
   
     public Department(String name) {  
         this.name = name;  
     }  
   
     @Override  
     public String toString() {  
         return "Department [name=" + this.name + "]";  
     }  
 }  
Second domain object is Person, which holds a reference to Department. Is also has an @Id which can be used for retrieval.
 import org.springframework.data.annotation.Id;  
 import java.util.UUID;  
   
 public class Person {  
   
   @Id  
   private final UUID id;  
   private final String name;  
   private final String title;  
   private final Department department;  
   
   public Person(String name, String title, Department department) {  
     this.id = UUID.randomUUID();  
     this.name = name;  
     this.title = title;  
     this.department = department;  
   }  
   
   public UUID getId() {  
     return this.id;  
   }  
   
   @Override  
   public String toString() {  
     return "Person{" +  
         "department=" + department +  
         ", id=" + id +  
         ", name='" + name + '\'' +  
         ", title='" + title + '\'' +  
         '}';  
   }  
 }  

Next we need a configuration that connects to the MongoDB and exposes a MongoTemplate that can be injected into repository beans.
 import org.springframework.data.mongodb.MongoDbFactory;  
 import org.springframework.data.mongodb.core.MongoTemplate;  
 import org.springframework.data.mongodb.core.SimpleMongoDbFactory;    
 import com.mongodb.DB;  
 import com.mongodb.MongoClient;  
   
 @Configuration  
 @ComponentScan("com.blogspot.jpdevelopment.mongodb")  
 public class MongoDbConfig {  
   
     @Bean  
     public MongoClient mongoClient() throws UnknownHostException {  
         return new MongoClient("localhost");  
     }  
   
     @Bean  
     public DB db() throws UnknownHostException {  
         return mongoClient().getDB("test");  
     }  
   
     @Bean  
     public MongoDbFactory mongoDbFactory() throws UnknownHostException {  
         return new SimpleMongoDbFactory(mongoClient(), "test");  
     }  
   
     @Bean  
     public MongoTemplate mongoTemplate() throws UnknownHostException {  
         return new MongoTemplate(mongoDbFactory());  
     }  
 }  
After setting up the configuration, we can create a Repository.The MongoTemplate is injected and opens up to all CRUD actions.
 import org.springframework.data.mongodb.core.MongoTemplate;  
 import org.springframework.data.mongodb.core.query.Criteria;  
 import org.springframework.data.mongodb.core.query.CriteriaDefinition;  
 import org.springframework.data.mongodb.core.query.Query;  
 import org.springframework.stereotype.Repository;  
 import java.util.UUID;  
   
 @Repository  
 public class PersonRepository {  
   
     private static final String PERSON_COLLENCTION = "person";  
   
     @Autowired  
     private MongoTemplate template;  
   
     public Person findOne(UUID id) {  
         CriteriaDefinition criteriaDefinition = Criteria.where("id").is(id);  
         Query query = new Query();  
         query.addCriteria(criteriaDefinition);  
         return this.template.findOne(query, Person.class, PERSON_COLLENCTION);  
     }  
   
     public Person save(Person person) {  
         template.save(person);  
         return person;  
     }  
 }  
Finally lets take it for a spin. Spring is started and the Repository bean is fetched from the ApplicationContext. 
First a new Person is stored and then again fetched as a new object and printed.
 public class Main {  
   
     public static void main(String[] args) {  
         AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MongoDbConfig.class);  
   
         PersonRepository personRepository = ctx.getBean(PersonRepository.class);  
         Person newPerson = new Person("Jonas", "Developer", new Department("Dev"));  
         personRepository.save(newPerson);  
   
         Person storedPerson = personRepository.findOne(newPerson.getId());  
         System.out.println(storedPerson);  
   
     }  
 }  
The output will look like this:
 Person{department=Department [name=Dev], id=9ae44c1d-a38e-4364-9848-2d7dd6538444, name='Jonas', title='Developer'}  
That was the very basic of connection to MongoDB from Java using Spring Data.

Tuesday, January 13, 2015

Spring CXF endpoint configuration in pure Java

A Spring CXF endpoint configuration in XML looks something like below.

 <import resource="classpath:META-INF/cxf/cxf.xml" />  
 <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />  
 <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  
        
 <bean id="soapServiceImpl" class="SoapServiceImpl"/>  
   
 <jaxws:endpoint id="soapServiceEndpoint"  
      implementor="#soapServiceImpl" address="/soapService">  
 </jaxws:endpoint>  

To do this configuration in pure Java, simply annotate the web service with @Service and make a configuration file like below.
 import org.apache.cxf.Bus;  
 import org.apache.cxf.jaxws.EndpointImpl;  
 import org.springframework.context.annotation.Bean;  
 import org.springframework.context.annotation.Configuration;  
 import org.springframework.context.annotation.ImportResource;  
 import javax.xml.ws.Endpoint;  
   
 @Configuration  
 @ImportResource({  
     "classpath:META-INF/cxf/cxf.xml",  
     "classpath:META-INF/cxf/cxf-extension-soap.xml",  
     "classpath:META-INF/cxf/cxf-servlet.xml" })  
 public class CXFConfig {  
   
   @Bean  
   public Endpoint soapServiceEndpoint(Bus cxfBus, SoapService soapService) {  
     EndpointImpl endpoint = new EndpointImpl(cxfBus, soapService);  
     endpoint.setAddress("/soapService");  
     endpoint.publish();  
     return endpoint;  
   }  
 }  

If component scan of @Service, @Repository and @Component is not already active this can be done be adding:
 <context:component-scan annotation-config="true" base-package="package.to.scan" />  

Wednesday, November 5, 2014

Java data type conversion

Java auto boxing is a nice feature but it can sometimes cause a lot of problems, especially when going from Object to primitive. A NullPointerException can be very hard to spot, because it can be throw in strange places where you normally would not expect it. See this for some auto boxing errors.
This blog will list some nice data type conversion between different data type and from primitive and Object type and vise versa.

Integer/int conversion
See examples here. 

Data type from, to Use Comment
int to Integer int i = 10; 
Integer intObj = Integer.valueOf(i);

int to Long int i = 10;
Long longObj= Long.valueOf(i);

int to long int i = 10;
long l = (long) i;

int to String int i = 10;
String s = Integer.toString(i);

Integer to int Integer intObj = new Integer(10);
int i = intObj.intValue();
NumberFormatException will be thrown if the intObj is a null Integer.
Integer to String Integer intObj = new Integer(10);
String s = intObj.toString();
NumberFormatException will be thrown if the intObj is a null Integer.
Integer to long Integer intObj = new Integer(10);
long l = intObj.longValue();
NumberFormatException will be thrown if the intObj is a null Integer.
Integer to Long Integer intObj = new Integer(10);
Long longObj = Long.valueOf(intObj.longValue());
NumberFormatException will be thrown if the intObj is a null Integer.

Long/long conversion
Careful when converting from Long/long to Integer/int. No exception is thrown if the Long value is bigger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE. It will simple do an int overflow and the output will be unexpected.
See examples here
long to Long long l = 10L;
Long longObj = Long.valueOf(l);

long to Integer long l = 10L;
Integer intObj = Integer.valueOf(Long.valueOf(l).intValue());
No really good way of doing this. Overflow may occur.
long to String long l = 10L;
String s = Long.toString(l);

long to int long l = 10L;
int i = (int) l;
Use simple cast.
Overflow may occur.
Long to long Long longObj = new Long(10L);
long l = longObj.longValue();
NumberFormatException will be thrown if the longObj is a null Long.
Long to String Long longObj = new Long(10L);
String s = longObj.toString();

Long to Integer Long longObj = new Long(10L);
Integer intObj = Integer.valueOf(longObj.intValue());
No really good way of doing this. Overflow may occur.
Long to int Long longObj = new Long(10L);
int i = longObj.intValue();
Overflow may occur.