View Javadoc

1   /**
2    * Copyright 2005-2006 the original author or authors.
3    *
4    * Licensed under the Gnu General Pubic License, Version 2.0 (the
5    * "License"); you may not use this file except in compliance with
6    * the License. You may obtain a copy of the License at
7    *
8    *      http://www.opensource.org/licenses/gpl-license.php
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13   * See the Gnu General Public License for more details.
14   */
15  package org.figure8.join.core.persistence;
16  
17  import org.figure8.join.core.InfrastructureException;
18  import org.figure8.join.util.LogUtil;
19  
20  import org.apache.commons.logging.Log;
21  import org.springframework.orm.hibernate.support.HibernateDaoSupport;
22  import org.springframework.orm.hibernate.HibernateCallback;
23  import net.sf.hibernate.SessionFactory;
24  import net.sf.hibernate.HibernateException;
25  import net.sf.hibernate.Session;
26  
27  import java.io.Writer;
28  import java.io.InputStream;
29  import java.io.IOException;
30  import java.util.Date;
31  import java.util.Collection;
32  import java.util.List;
33  import java.text.SimpleDateFormat;
34  import java.text.ParseException;
35  /**
36   * This is an implementation of {@link XmlDatabinder} for entity objects
37   * using Hibernate as an ORM system.
38   * @author <a href="mailto:laurent.broudoux@free.fr">Laurent Broudoux</a>
39   * @version $Revision: 1.1 $
40   */
41  public class HibernateXmlDatabinder extends HibernateDaoSupport implements XmlDatabinder{
42  
43     // Static -------------------------------------------------------------------
44  
45     /** Get a commons logger. */
46     private static final Log log = LogUtil.getLog(HibernateXmlDatabinder.class);
47  
48     /** Constant representing default encoding for writing Xml */
49     public static final String DEFAULT_ENCODING = "UTF-8";
50     /** Simple date formater for ISO dates */
51     public static SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-MM-dd");
52     /** Simple date formater for ISO timestamps */
53     public static SimpleDateFormat isoTimestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
54  
55     /* String constant for writing/reading the Xml format */
56     public static final String LEFT_CHEVRON = "<";
57     public static final String RIGHT_CHEVRON = ">";
58     public static final String CARRIAGE_RETURN = "\n";
59     public static final String START_CLOSE_TAG = "</";
60     public static final String END_TAG_CARRIAGE_RETURN = ">\n";
61     public static final String CONST_OBJECT = "object";
62     public static final String CONST_OPEN_OBJECT_TAG = "<object";
63     public static final String CONST_CLOSE_OBJECT_TAG = "</object>\n";
64     public static final String CONST_NAME = "name";
65     public static final String CONST_CLASS = "class";
66     public static final String CONST_INDEX_ID = "index-id";
67     public static final String CONST_INDEX_TYPE = "index-type";
68     public static final String CONST_COMPOSITE_ELEMENT = "composite-element";
69     public static final String CONST_ELEMENT = "element";
70     public static final String CONST_SUBCOLLECTION = "subcollection";
71     public static final String CONST_ID = "id";
72     public static final String CONST_COMPOSITE_ID = "composite-id";
73     public static final String CONST_COLLECTION = "collection";
74     public static final String CONST_PROPERTY = "property";
75     public static final String CONST_COMPONENT = "component";
76     public static final String CONST_TYPE = "type";
77     public static final String CONST_OPEN_CDATA = "<![CDATA[";
78     public static final String CONST_CLOSE_CDATA = "]]>";
79  
80  
81     // Attributes ---------------------------------------------------------------
82  
83     /** The encoding for Xml output */
84     private String encoding = DEFAULT_ENCODING;
85  
86  
87     // Constructors -------------------------------------------------------------
88  
89     /** Creates a new instance of HibernateXmlDatabinder */
90     public HibernateXmlDatabinder(){
91     }
92  
93  
94     // Public -------------------------------------------------------------------
95  
96     /** @param encoding The encoding for Xml output */
97     public void setEncoding(String encoding){
98        this.encoding = encoding;
99     }
100 
101    /**
102     * @param date The date to format
103     * @return The string representing date
104     */
105    public static String formatDate(Date date){
106       return isoDateFormat.format(date);
107    }
108    /**
109     * @param date The date to format as a timestamp
110     * @return The string representing timestamp
111     */
112    public static String formatTimestamp(Date date){
113       return isoTimestampFormat.format(date);
114    }
115 
116    /**
117     * @param dateStr the string representation of date
118     * @throws ParseException if string cannot be parsed
119     * @return The date represented by this string
120     */
121    public static Date parseDate(String dateStr) throws ParseException{
122       return isoDateFormat.parse(dateStr);
123    }
124    /**
125     * @param dateStr the string representation of timestamp
126     * @throws ParseException if string cannot be parsed
127     * @return The timestamp represented by this string
128     */
129    public static Date parseTimestamp(String dateStr) throws ParseException{
130       return isoTimestampFormat.parse(dateStr);
131    }
132 
133 
134    // Implementation of XmlDatabinder ------------------------------------------
135 
136    /**
137     * Load a collection of {@link org.figure8.join.core.EntityObject}s from a Xml stream
138     * @param is An input stream containing Xml exported form of entity objects
139     * @throws InfrastructureException if entity objects cannot be recreated from stream
140     * @throws IOException if stream cannot be correctly read
141     * @return A collection of {@link org.figure8.join.core.EntityObject}s
142     */
143    public Collection loadFromXml(InputStream is) throws InfrastructureException, IOException{
144       Collection entityObjects = null;
145       try{
146          // Create an import handler.
147          HibernateXmlImportHandler handler = new HibernateXmlImportHandler(getSessionFactory());
148          // Load the entity objects.
149          entityObjects = handler.loadEntityObjects(is);
150       }
151       catch (HibernateException he){
152          // Log and wrap into an infrastructure exception.
153          log.error("Exception while importing entity objects from their Xml representation");
154          log.error("Here's the detailed message: " + he.getMessage());
155          throw new InfrastructureException("Exception while importing entities from Xml", he);
156       }
157       return entityObjects;
158    }
159 
160    /**
161     * Write a collection of {@link org.figure8.join.core.EntityObject}s using their Xml form
162     * @param writer The writer to use for outputing entity objects
163     * @param dao The data access objects from whom are retrievied entities (using the findAll() method)
164     * @throws InfrastructureException if entity objects cannot be exported corectly
165     * @throws IOException if writer cannot be correctly written
166     */
167    public void writeToXml(final Writer writer, final ObjectDao dao) throws InfrastructureException, IOException{
168       getHibernateTemplate().execute(new HibernateCallback(){
169          public Object doInHibernate(Session session) throws HibernateException{
170             List entityObjects = null;
171             if (dao == null || dao instanceof GenericHibernateObjectDao){
172                log.debug("Extracting all entities to export in Xml from GenericHibernateObjectsDao");
173                entityObjects = GenericHibernateObjectDao.PersistentObjectsLoader.loadPersistentObjects(session);
174             }
175             else{
176                log.debug("Extracting all entities to export in Xml from " + dao);
177                entityObjects = dao.findAll();
178             }
179             try{
180                // Create an export handler and configure its encoding.
181                HibernateXmlExportHandler handler = new HibernateXmlExportHandler(session.getSessionFactory(), entityObjects);
182                handler.setEncoding(encoding);
183                // Write the entity objects.
184                handler.writeEntityObjects(writer);
185             }
186             catch (Exception e){
187                // Log and wrap into an infrastructure exception.
188                log.error("Exception while exporting entity objects into their Xml representation");
189                log.error("Here's the detailed message: " + e.getMessage());
190                throw new InfrastructureException("Exception while exporting entities into Xml", e);
191             }
192             return entityObjects;
193          }
194       });
195    }
196 }