Posts

Showing posts from 2010

Hibernate + Spring + MySql: Cannot convert value '0000-00-00 00:00:00' from column X to TIMESTAMP

Image
When I was trying to load an Hibernate object, I received the following error: nested exception is java.sql.SQLException: Cannot convert value '0000-00-00' from column 4 to TIMESTAMP. at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQL This exception means that the column "X" has an invalid date "0000-00-00 00:00:00" According to http://bugs.mysql.com/bug.php?id=13030 "Datetimes with all-zero components ('0000-00-00 ...') - These values can not represented reliably in Java. Connector/J 3.0.x always converted them to NULL when being read from a ResultSet. When working with MySQL over JDBC and the driver encounters a zero DATE, TIME, or DATETIME value (that is, e.g, ‚0000–00–00‘ for DATE), this exception is thrown. This can be handled by adding the JDBC Parameter: zeroDateTimeBehavior=convertToNull to your JDBC connection. url=jdbc:mysql://localhost/test?connectTimeout=60000&autoReconnect=true&ze

Hibernate: a different object with the same identifier value was already associated with the session

People working with Hibernate might be familiar with the below error. org.springframework.orm.hibernate3.HibernateSystemException: a different object with the same identifier value was already associated with the session: nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session This exception is generated when we try to load an instance object in session which has been already loaded by hibernate. Easier said than done. Hibernate considers two persistent entities identical if the two rows of the table can be said identical. Above error could be generated in many ways and there may be various solutions on net like using session merge etc to get away with the problem. I will discuss here the reason for me getting this problem and the way I resolved it. Below is the code which generated the exception for me. Following is the method which caused the exception @Transactional(propagation=Propagation.

Context initialization failed - java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

I received the following error while running a Spring and Hibernate application Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/ applicationContext.xml ]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder Caused by: java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder at org.slf4j.LoggerFactory. (LoggerFact

org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

This Exception during the maven build in an hibernate based project could come due to various reasons. Primarily one should look into the complete stack trace. The further exception usually do give clue of the actual problem. I my case, the stack trace revealed the below issue Exception in thread "main" org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:110) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:135) at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping. (EntityEntityModeToTuplizerMapping.java:80) at org.hibernate.tuple.entity.EntityMetamodel. (EntityMetamodel.java:323) at org.hibernate.persister.entity.AbstractEntityPersister. (AbstractEntityPersister.java:456) at org.hibernate.persister.entity.SingleTableEntityPersister. (SingleT

java.lang.nosuchmethoderror org.objectweb.asm.classwriter

I was working on a RESTFul Service based project. Recently I migrated the plain JDBC DAO layer to the hibernate based orm layer. As a first step I migrated one of the DAO class. When I deployed the complete solution in Tomcat, I faced the following error java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter. (Z)V at net.sf.cglib.core.DebuggingClassWriter. (Debu ggingClassWriter.java:47) at net.sf.cglib.core.DefaultGeneratorStrategy.getClas sWriter(DefaultGeneratorStrategy.java:30) at net.sf.cglib.core.DefaultGeneratorStrategy.generat e(DefaultGeneratorStrategy.java:24) at net.sf.cglib.core.AbstractClassGenerator.create(Ab stractClassGenerator.java:216) at net.sf.cglib.core.KeyFactory$Generator.create(KeyF actory.java:145) at net.sf.cglib.core.KeyFactory.create(KeyFactory.jav a:117) at net.sf.cglib.core.KeyFactory.create(KeyFactory.jav a:108) at net.sf.cglib.core.KeyFactory.create(KeyFactory.jav a:104) at net.sf.cglib.proxy.Enhancer. (Enhancer.java :69) at java.lang.Class.forN

301 Moved Permanently, URLConnection and HTTPURLConnection

If a website has applied a redirection from " BaseUrl" to " BaseUrl /" then what you see the response by hitting " " in your browser "301 Moved Permanently" and redirected to " /" How to deal this situation when creating a URLConnection and know to what URL you have been redirected to? If you specify URLConnection con = new URL(uri).openConnection(); It would create a connection. Later if you try to get the URL from the "con" object. con.getURL().toString(); This would give you the "BaseUrl " and you would not get the redirected URL. But if you create a HttpURLConnection instead of URLConnection. HttpURLConnection httpURLCon = (HttpURLConnection) new URL(uri).openConnection(); then if you try to get the URL it would give the correct redirected URL "BaseUrl/" If anyone does get contradictory results, please do let me know.

java.lang.AbstractMethodError: org.apache.xerces.dom.DocumentImpl.getXmlStandalone()Z

If you are facing this issue than most probably have a wrong version of XercesImpl.jar file I had a 2.0.2 version, which causing conflict. Replacing it with 2.8.1 resolved the issue.

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value:

This error may crop up if you are doing any DML operation through IN clause. Example String sql = 'update table set status = true where id in (?)' If you are using the above statement as part of the prepared statement and the 'id' column is of long type. Following would give this error. String str = "1,2,3,4"; PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, str); stmt.executeUpdate(); The last line would give the error. Reason being that the column is of Long(BIGINT) type and value is passed as string. You cannot say stmt.setLong(1, str); as the 'str' contains comma separated values. One of the solution in this case is to create separate place holders for each input value String sql = 'update table set status = true where id in (?,?,?,?)' in this case and pass individual long values to the statement object. Other options are welcome.

Core Dump and Stack Tace on Linux of a Java process

Steps for taking the Core Dump Run the command # ps -ef | grep java get the process id of the java process you want to get the core dump. Next run the command # gdb --pid= Next gdb>gcore This should create a file core. in the /var/tmp location Remember its a binary file. If I find some other better way to take the dump, I would update. If you know other ways please let me know. Steps fr taking the stack Trace jstack [-l] pid (simple) Difference between core dump and Stack Trace Core dump prints the complete memory map of a process and stack trace prints the state of threads of a processs.

Behavior of AUTO INCREMENT column when max value has reached

I was looking on the net for the query that "What will happen in an InnoDB MySQL table with column of type AUTO INCREMENT if the max value has reached?" There is so much of information on the net regarding this but does not lead anywhere. I could not find any official word in this query. Most of the links say that it would throw an error. Some had other views that the behavior is not predictable http://www.dbforums.com/mysql/1207954-auto-increment-field-hit-maximum-integer-value.html So i tried a small test myself through mysqlcc by inserting the largest value in int(11) - AUTO INCREMENT type column (name "id"). Th maximum value i could insert manually was "2147483647" (the next number gives "Out of range value" error) The moment I inserted a new row, the new number assigned to the column "id" was "1000000000" Behavior was strange, might help someone that it did not give an error

Struts 2 + Hibernate CRUD application

We had a requirement to provide some CRUD based screens to perform administrative task. After doing some searching I found a tool. Our requirement changed so have not used it, but thought of sharing the tool with all those extreme programmers to save their time. http://sourceforge.net/projects/struts2builder/ I builds a base project on for CRUD operations on selected tables. Also provide maven based structure.

Open Source Crawler in JAVA

In case you have the need to crawl the web to get information. I would suggest few: Smart and Simple Web Crawler - https://crawler.dev.java.net/ Websphnix - http://www.cs.cmu.edu/~rcm/websphinx/ Archive-Crawler - http://archive-crawler.sourceforge.net Of these i would recommend https://crawler.dev.java.net/ Why? because I have used it. This is a quite simple crawler which serves the purpose. It loads the page and parses the page. Throws appropriate events while crawling. (i.e supports event model to serve the requirement). It has HTML and HTTP parsing capabilities.

Things to remember while developing web application (Some Practices)

Image
Below is a list of technical and non-technical high level points to be taken care. There can be definitely many more. (For exhaustive web application security specific guidelines please refer to http://www.owasp.org/index.php/Main_Page ) See to it!! Visual representation plays a big role in boosting customer involvement. The sooner customer is able to see the UI of the application, more he tends to get involved. The visual representation makes the customer come up with modifications sooner than later. Involved evolvement Customer should always be involved throughout the course of application development. Team should create the process to get the frequent feedbacks and directions. Lack of feedback should be taken up as a risk ASAP specially in case of extreme development with Agile. See the point Customers do need the complete application but are not willing to give time. It’s a known fact that application cannot be bug free. If get to understand the business aspect of t

Error "Document could not be opened"

When we try to open any of the jasper reports in pdf, csv or rtf format, it results in an error saying that the document can't be opened. However, when we first save the report then it can be opened. This problem only occurs when we connect directly to Websphere 6.1. When there is a HTTP server in between, everything works ok. Analysis: We studied the HTTP header information being transmitted in both the cases; with HTTP Server and without HTTP server. Realized that the issue does occur because in case of no HTTP Server the HTTP had the cache settings as "Cache-Control: no-cache" Following is what we have suggested the customer: If you have 'CookiesConfigureNoCache' property already configured in your server, then please change its value to False, restart the server and try to replicate the problem. Otherwise, please add this property following the steps mentioned below. Steps to configure custom property CookiesConfigureNoCache on WAS 6.1: Login to the Administra

One or more local transaction resources were rolled back during the cleanup of a LocalTransactionContainment.

You might have seen the following statement in your log file sometimes: [9/11/09 10:26:06:349 CEST] 00000033 LocalTranCoor W WLTC0032W: One or more local transaction resources were rolled back during the cleanup of a LocalTransactionContainment. [9/11/09 10:26:06:762 CEST] 00000030 LocalTranCoor W WLTC0033W: Resource Test Datasource rolled back in cleanup of LocalTransactionContainment. We also recieved the statement for one of our client running on Websphere 6.1 server. The solution was to change the data source settings. (GO TO Resources -> JDBC in Admin Console) Client had the Data Source settings under the option "Resources -> JDBC -> Data Sources (WebSphere Application Server V4)". This section specifies the data source to support older versions of EJB (i believe EJB 1.1) and Servlet (I think 1.1 and earlier). There may me other compatibility issues, please check the WebSphere site for details. For any other later specifications Data Source should be speci

Factory Method Pattern - Misconception

Image
This post does not talk about the Factory Method Pattern, but I would like to discuss about from where it starts. Recently I had the privilege to attend a training on the topic. I do not miss opportunity to attend any session on process or pattern, you always have something to learn. It was an good interactive session but we had the same old discussion that instead getting to the factory method we ended up discussing the implementation (some may call it simple factory idom, but i dont) forgetting that patterns only talk about the behavior and interaction and not about implementation. Let me take a chance to explain the Factory Method Factory Method - I will use the common example of PizzaFactory as used by Head First to explain the factory method: Elements: Pizza (Product) SimplePizzaFactory (Creator) Definition: The essence of the Factory Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a