Whenever you write an “if” condition, you are liable to test both scenarios.
Monday, March 5, 2012
Tuesday, February 14, 2012
Inheritance Support in JAXB
In this scenario, We have two XML documents with different root elements and same child-elements as below
XML(Person)
<?xml version="1.0" encoding="utf-8"?> <Person> <id>1</id> <name>Andy</name> </Person>
XML (Student)<?xml version="1.0" encoding="utf-8"?>
<Student> <id>1</id> <name>Andy</name> </Student>
Student XML could even have additional elements to Person XML. I will leave this as an exercise here.
We could have two independent POJO annotated with xml binding.
Java (Person)
@XmlRootElement(name = "Person") public class Person { @XmlElement(name = "id") private Integer id; @XmlElement(name = "name") private String name; //........ }
Java (Student)
@XmlRootElement(name = "Student") public class Student { @XmlElement(name = "id") private Integer id; @XmlElement(name = "name") private String name; //.... }
We want Student class to extend Person as below:
Java (Student extending Person)
@XmlRootElement(name = "Person") public class Student extends Person { }
The issue here is only at the run time, we will notice that values are not bond to id and name fields.
The trick here is we need to have super class annotated with @XmlTransient. However Person class is still required in XML binding for other usages. So we need to add a dummy class for binding Person XML..
Java (Person Class annotated with @XmlTransient)
@XmlTransient public class Person{ @XmlElement(name = "id") private Integer id; @XmlElement(name = "name") private String name; //.... }
Java (Dummy Class for Person XML extending Person Class)
@XmlRootElement(name = "Person") public class PersonXml extends Person{ //... }
Java (Student extending Person)
@XmlRootElement(name = "Student")
public class Student extends Person{ //Additional Fields //... }
With this approach, we can have JAXB bind the values in both Person and Student class while maintaining Person-Student inheritance structure.
In other place of the code (for instance Service class), Person class can be used in the place of PersonXML as below:
@XmlRootElement(name = "Student")
Person p = unmarshall(personXml);//Here, instance of p is in fact PersonXML
Int i = p.id();
Person s1 = unmarshall(studnetXml);//instance of student
Student s2 = unmarshall(studentXml);//instance of student
Tuesday, October 18, 2011
java.lang.ClassFormatError: Truncated class file=javax.servlet.ServletException
Problem
Having above exception after deploying WAR file.
Solution
Delete [Tomcat]\work\Catalina\localhost.
Cause
Tomcat’s got crazy with JSP compilation.
Wednesday, August 17, 2011
Spring Bean as Servlet Filter
Wish
Want to use a Spring bean as JSP Filter.
Solution
Use DelagatingFilterProxy from Spring libarry.
Details
- Implements the Spring bean from javax.servlet.Filter as usual Filter
public class HeaderValidationFilter implements Filter{
……
}
- Create Spring bean (with Spring XML) as usual
<bean id="filterHeader” class=”com.proprogrammers.HeaderValidationFilter”>
……
</bean>
- In “web.xml” add JSP filter as below:
- Notice that <filter-name> is the same as bean id above.
<filter>
<filter-name>filterHeader</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter><filter-mapping>
<filter-name>filterHeader</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping><servlet>
<servlet-name>Spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Caveat
Filter bean (at step-2) cannot be defined in Spring Servlet XML file; Spring-servlet.xml in the sample. It must be in other Spring XML file.
Read More
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/security-filter-chain.html
Credits
Collin Yates
http://forum.springsource.org/showthread.php?20230-Howto-The-joy-that-is-DelegatingFilterProxy
Monday, August 1, 2011
[Java] How to Make Asynchronous Method
I have a long-running method which I want to run asynchronously. I transform the method into asynchronous method by running it on separate thread.
Original Code:
public void mainMethod() throws InterruptedException{
System.out.println("Main Method start");
longRunningMethod("testing", new Object());
otherMethod();
}
public Integer longRunningMethod(String param1,Object parm2) throws InterruptedException{
System.out.println("Long running method");
Thread.sleep(5000);
//long process
return 1;
}
public void otherMethod(){
System.out.println("Other Method");
}
New Code:
public void mainMethod() throws InterruptedException{
System.out.println("Main Method start");
//longRunningMethod("testing", new Object());
asyncServiceMethod("testing",new Object());
otherMethod();
}
public Integer longRunningMethod(String param1,Object parm2) throws InterruptedException{
System.out.println("Long running method");
Thread.sleep(5000);
//long process
return 1;
}
public void otherMethod(){
System.out.println("Other Method");
}
public void asyncServiceMethod(final String parm1,final Object obj){
Runnable task = new Runnable() {@Override
public void run() {
try {
longRunningMethod(parm1,obj);
} catch (Exception ex) {
//handle error which cannot be thrown back
}
}
};
new Thread(task, "ServiceThread").start();
}
There are few things to consider wrapping a method into asynchronous call.
- Passing Parameters must be final
- Exception from the long-running process cannot be thrown back to mainMethod (main thread). It has to be handled at separate thread (ServiceThread in the sample)
- Returning value cannot be retrieved (Integer value in this sample) from the main Method. (If one wants to retrieve, FutureTask should be used.)
Other to read
Monday, May 9, 2011
MS SQL – Strip Time, Day, Month from DateTime
select getdate() as CurrentDateTime;
select DATEADD(d,DATEDIFF(d,0,getdate()),0) as CurrentDate;
select DATEADD(wk,DATEDIFF(wk,0,getdate()),0) as CurrentStartDayOftheWeek;
select DATEADD(mm,DATEDIFF(mm,0,getdate()),0) as CurrentStartDayOftheMonth;
select DATEADD(yy,DATEDIFF(yy,0,getdate()),0) as CurrentStartDayOftheYear;
Result
CurrentDateTime
-----------------------
2011-05-10 11:18:54.857
CurrentDate
-----------------------
2011-05-10 00:00:00.000
CurrentStartDayOftheWeek
------------------------
2011-05-09 00:00:00.000
CurrentStartDayOftheMonth
-------------------------
2011-05-01 00:00:00.000
CurrentStartDayOftheYear
------------------------
2011-01-01 00:00:00.000
Tuesday, May 3, 2011
Java byte Array into int Array
public int[] toIntArray(byte[] barr) {
//Pad the size to multiple of 4
int size = (barr.length / 4) + ((barr.length % 4 == 0) ? 0 : 1);ByteBuffer bb = ByteBuffer.allocate(size *4);
bb.put(barr);//Java uses Big Endian. Network program uses Little Endian.
bb.order(ByteOrder.LITTLE_ENDIAN);
int[] result = new int[size];
bb.rewind();
while (bb.remaining() > 0) {
result[bb.position()/4] =bb.getInt();
}return result;
}
Disappointed for not seeing shifting? Wanna complain about performance?
This is definitely not the most efficient method to convert byte array into int array yet it can be done with simple logic and a bit of knowledge in NIO.
Unless the program is to be used on 1K memory device, using ByteBuffer is acceptable I reckon.
(I tried to convert to IntBuffer but in vain. If anyone could point out, that’d be great.)
Peter has mentioned how to use with IntBuffer in comment section as follow:
public int[] toIntArray(byte[] barr) {
//Pad the size to multiple of 4
int size = (barr.length / 4) + ((barr.length % 4 == 0) ? 0 : 1);ByteBuffer bb = ByteBuffer.allocate(size *4);
bb.put(barr);//Java uses Big Endian. Network program uses Little Endian.
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.rewind();
IntBuffer ib = bb.asIntBuffer();
int [] result = new int [size];
ib.get(result);return result;
}
Tuesday, March 1, 2011
BigDecimal equals method
BigDecimal class from java.lang.Math package is useful for scale manipulation. Be careful though when you want to compare two BigDecimal objects with equals() method since it tests not just the equality of value but also the scale as mentioned in the document as below:
…..this method considers two BigDecimals equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
For the following code
BigDecimal a = new BigDecimal("2.0");
BigDecimal b = new BigDecimal("2.00");
if (a.equals(b)){
System.out.println("Equals");
}else{
System.out.println("Not Equals");
}
it will return "Not Equals” as the scales of the objects are different.
To compare values of the above two objects, compareTo method can be used as it implements Comparable interface like wrappers.
if (a.compareTo(b)==0)
{
System.out.println("They have same value");
}
Tuesday, November 23, 2010
Chrome Proxy Setting
If you change proxy setting in Chrome using Options->Under the Hood –> [Change Proxy Setting], it will use IE proxy setting and it will change proxy setting for all other browsers.
To avoid this, execute chrome.exe using the command line argument below:
--proxy-server=PROXYSERVER:PORT
Thursday, November 4, 2010
[Spring] log4J
WEB-INF\web.xml
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>….
WEB-INF\log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- An appender which writes to file -->
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="file" value="../logs/MyApp.log" />
<param name="datePattern" value="'.'yyyy-MM" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c{6} - %m%n"/>
</layout>
</appender><root>
<priority value ="info" />
<appender-ref ref="FILE" />
</root>
</log4j:configuration>
Sunday, October 31, 2010
Enable Ping (Windows 2008)
According to WiKiPedia
Ping is a computer network administration utility used to test the reachability of a host on an Internet Protocol (IP) network and to measure the round-trip time for messages sent from the originating host to a destination computer.
The name comes from active sonar terminology.
Ping is used to test the hostname/IP address for DNS resolution.
Ping uses ICMP protocol while telnet uses TCP protocol on specific port.
Since Windows 2008, it is disabled by default. To enable it, Networking – Echo Request(ICMPv4In), from command prompt, enter following:
netsh firewall set icmpsetting 8
Monday, October 25, 2010
[MSSQL] Reseed Identity
dbcc checkident( 'TABLENAME', RESEED, 200000000)
Details in: http://blogs.techrepublic.com.com/datacenter/?p=406 (Susan Harkins, 2008)
Monday, September 20, 2010
[Spring] Initialization Callbacks
If you want the Spring container to perform initialization work on your bean after all the properties are set, you may implement InitializationBean and implements afterPropertiesSet() method.
But just as Spring documentation outlines, that approach will couple the code to Spring. You should use init-metod instead and call any public method from your bean. You could event pass parameters using constructor-arg.
http://static.springsource.org/spring/docs/2.0.x/reference/beans.html#beans-factory-lifecycle
Thursday, September 2, 2010
Tomcat 5.5 with Java 1.6
If your Tomcat is running with Java 1.5 by default and want to upgrade to Java 1.6, double click TOMCAT\bin\tomcat5w.exe
- Change Java Virtual Machine by selecting ..\Java\jdk1.6.0_xx\jre\bin\server\jvm.dll.
- There is one more trick to make it work. Copy ..\Java\jdk1.6.0_xx\bin\msvcr71.dll into the same folder as jvm.dll.
Thanks to kellyohair http://forums.java.net/jive/message.jspa?messageID=155421 for step-2
Wednesday, July 14, 2010
Enable connection pooling in Spring Datasource
I use Apache Commons DBCP for the above purpose
<bean id="poolDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="poolPreparedStatements" value="true"/>
<property name="maxActive" value="10"/>
<property name="maxIdle" value="10"/>
</bean>
Friday, July 9, 2010
Caused by: org.xml.sax.SAXException: unable to find FieldDescriptor for 'elementName' in ClassDescriptor of ParentElement
<country xmlns="http://pro-programmers.com/schema">
<city>London</city>
</country>
For the above XML document mapping was designed as
<mapping xmlns="http://castor.exolab.org">
<class name="com.proprogrammers.pojo.Country">
<map-to xml="country" />
<field name="city" type="string">
<bind-xml name="city" node="element"/>
</field>
</class>
</mapping>
Solution: I declared namespace in binding xml element as below:
See more here.
Tuesday, June 22, 2010
Log File
Application Log files should
- roll over daily or by size
- Manual/Scheduled process should be involved to archive log files after a period (for instance every month). It is necessary to set log file archiving procedure.
- analysable
- for number hits/requests (even if the application is not web app, it should log how many times a module is called). We keep such log in a separate log file – say “access.log”.
- performance profiling - We use perf4j and log the performance in “performance.log” which can be enabled as needed.
- Database requests - Not every developer can tell how many DB access application submit in a certain time or for a request. This is very helpful in optimising performance.
- follow industrial standard
- such as Apache log format so that it can be analysed with tools available (e.g; Web Log Expert)
- Even if the log file is not for web application, it may be formatted in Apache log format to be analysed with tool.
- Log file may be formatted in CSV sometimes.
- be Visible for Errors
- We keep any application error in a separate log file, “error.log” which improves visibility and we have a monitor program to raise alarm if any given exception is thrown.
- include start-up states
- log file should have application restart time,
- which modules are running and which are not
- which configurations are used
- Operation/Production team who starts the system should be able to view the log clearly and should be fully aware of how application is started and how it will behave after start-up.
- be configurable
- from INFO to DEBUG without restarting the system
- be Compact
- There were times when application server froze since there was no space left in the HDD. Developers log whatever the want and as a result log file is bloated with unnecessary statements. Apart from consuming storage space, bloated log file reduce the visibility.
- Code review should involve checking log statement.
- Conceal sensitive data
- Data like password or credit card number should never be in the log file.
- viewed by Log file monitoring tool
- We use BareTail to monitor log file which is very good especially with large size file and searching log statement in regex
- (This post will be updated as I can think of any standard for log file in our team…)
Thursday, May 6, 2010
Remove Transfer-Encoding:chunked from HTTP Response Header
Note From Wikipedia
Chunked Transfer Encoding is a mechanism that allows HTTP messages to be split in several parts. This can be applied to both HTTP requests (from client to server) and HTTP responses (from server to client).
HTTP Chunked Transfer Encoding allows a server to maintain a HTTP persistent connection for dynamically generated content.
Problem
If HTTP Response has “Transfer-Encoding” header, it causes client to wait for closing the connection.
Cause
If there is no “Content-Length” is defined in HTTP response header, it will be chunked transmission. HTTP Response must have either “Transfer-Encoding” or “Content-Length” attribute.
Solution
Define “Content-Length” attribute if it can be done.
Thursday, April 8, 2010
HibernateSystemException: could not set a field value by reflection setter
The above error is caught when NULL value in a database column is attempted to set to a setter in an Entity bean whose attribute mapped to that column type is of primitive type.
Never ever use primitive for attribute type in Entity Bean.
Since Java 5, with a feature called “Autoboxing”, we can seamlessly treat wrapper as primitive type as below
Integer deptId;
deptId = 5;
//deptId = new Integer(5);
int a;
a = deptId;
//a = deptId.intValue();
Compiler will handle it.
