Monday, September 08, 2008

TIP: JAX-WS Knowing Client IP (Requester IP)

To find out the client IP (the invoker) in JAX-WS Webservice one will need to use WebServiceContext

   1: import com.sun.xml.ws.transport.Headers;
   2: import javax.annotation.Resource;
   3: import javax.jws.WebMethod;
   4: import javax.jws.WebService;
   5: import javax.xml.ws.WebServiceContext;
   6: import javax.xml.ws.handler.MessageContext; 
   7:  
   8: @WebService
   9: public class XYZService 
  10: { 
  11:  
  12:     @Resource
  13:     WebServiceContext wsContext; 
  14:  
  15:     /**
  16:      * Web service operation
  17:      */
  18:     @WebMethod(operationName = "doOperation")
  19:     public String doOperation() 
  20:     {
  21:         MessageContext mc = wsContext.getMessageContext();
  22:         HttpServletRequest req = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST);
  23:         String clientIP = req.getRemoteAddr();
  24:         System.out.println("Client IP = " + clientIP); 
  25:         .....
  26:     } 
  27:  
  28: }

Wednesday, September 03, 2008

Tip: Hibernate Annotations - Default Column Values

If you wanted to set the default value using hibernate annotations, you’ve probably had some difficulties, as it was the case for me. Some posts on the web talk about default values to the members of the Java class. That is, if you declare

   1: class AEntity { 
   2:  
   3:     private Integer count = 3; 
   4:  
   5:     @Column(name = "count", nullable = false) 
   6:     public Integer getCount() {
   7:         return count;
   8:     }
   9: }

you should have the default value set in the database.

Well, this does not seem to work (at least not for me). So I tried the usage of “columndefinition”. This ofcourse is database dependent, since Hibernate specifies the usage of “columndefinition” attribute for database specific declarations. The following will work well with MySQL - the database of choice for my current project:

   1: class AEntity { 
   2:  
   3:     private Integer count = 3; 
   4:  
   5:     @Column(name = "count", nullable = false, columnDefinition = "bigint(20) default 0") 
   6:     public Integer getCount() {
   7:         return count;
   8:     }
   9: }

NOTE that this is database dependent, so use it if your project is db dependent.

Another way to do it would be to set the property value in the default constructor of that entity as follows:

   1: class AEntity { 
   2:  
   3:     private Integer count; 
   4:  
   5:     public AEntity(){
   6:         count=3;
   7:     }
   8:  
   9:     @Column(name = "count", nullable = false)
  10:     public Integer getCount() {
  11:         return count;
  12:     }
  13: }

Remember though, whenever you create an instance of this entity, the property will have that default value and will need to be overwritten by calling its respective setter method.

*Source: another blog