KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > rm > resources > content > Asset


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  */

19 package org.openharmonise.rm.resources.content;
20
21
22 import java.io.*;
23 import java.sql.*;
24 import java.util.*;
25 import java.util.logging.*;
26
27 import org.openharmonise.commons.cache.CacheException;
28 import org.openharmonise.commons.dsi.*;
29 import org.openharmonise.commons.dsi.dml.*;
30 import org.openharmonise.commons.net.MimeTypeMapping;
31 import org.openharmonise.rm.*;
32 import org.openharmonise.rm.config.*;
33 import org.openharmonise.rm.dsi.ColumnRefCache;
34 import org.openharmonise.rm.publishing.*;
35 import org.openharmonise.rm.resources.AbstractChildObject;
36 import org.openharmonise.rm.resources.lifecycle.*;
37 import org.w3c.dom.*;
38
39
40 /**
41  * The <code>Asset</code> class represents Harmonise resources which
42  * reside on the local file system instead of in the database.
43  *
44  * @author Michael Bell
45  * @version $Revision: 1.9 $
46  *
47  */

48 public class Asset
49     extends AbstractChildObject
50     implements Publishable, Editable, Cloneable JavaDoc, Comparable JavaDoc {
51
52     /**
53      * String constant which is the name of the config property for detailing
54      * what the webapp uri for assets is
55      */

56     private static final String JavaDoc PNAME_ASSET_WEBAPP_URI = "ASSET_WEBAPP_URI";
57     /**
58      * String constant which linking content types begin with
59      */

60     private static final String JavaDoc TXT_LINK = "link";
61     
62     /**
63      * String constant which mime types of text resources begin with
64      */

65     private static final String JavaDoc TXT_TEXT = "text";
66
67     //XML constants
68
/**
69      * The <code>Asset</code> tag name
70      */

71     public static final String JavaDoc TAG_ASSET = "Asset";
72     
73     /**
74      * The URI tag name
75      */

76     public static final String JavaDoc TAG_URI = "URI";
77     
78     public static final String JavaDoc TAG_CONTENT_TYPE = "ContentType";
79
80     //DB constants
81
/**
82      * The <code>Asset</code> database table name
83      */

84     protected static final String JavaDoc TBL_ASSET = "asset";
85     
86     /**
87      * The URI database column name
88      */

89     protected static final String JavaDoc CLMN_URI = "content";
90     
91     /**
92      * The mime type database column name
93      */

94     protected static final String JavaDoc CLMN_MIME_TYPE = "mime_type";
95
96     /**
97      * The site url configuration parameter name
98      */

99     static final String JavaDoc PNAME_SITE_URL = "SITE_URL";
100     
101     /**
102      * The configuration parameter name whose associated value specifies
103      * the file system directory to be used as the root of the asset store
104      */

105     public static final String JavaDoc PNAME_ASSET_ROOT_FILEPATH = "ASSET_ROOT";
106
107     /**
108      * The mime type of this <code>Asset</code>
109      */

110     protected String JavaDoc m_sContentType = null;
111     
112     /**
113      * The URI or file path of this <code>Asset</code>
114      */

115     protected String JavaDoc m_sURI = null;
116     
117     /**
118      * <code>boolean</code> flag which indicates whether the content/URI has been changed
119      */

120     private boolean m_bIsContentChanged = false;
121     
122     /**
123      * Logger for this class
124      */

125     private static final Logger m_logger = Logger.getLogger(Asset.class.getName());
126
127     /**
128      * Constructs a new or anonymous instance without an interface
129      * to the database
130      */

131     public Asset() {
132         super();
133     }
134
135     /**
136      * Standard constructor for a new or anonymous resource.
137      *
138      * @param dbintrf the data store to register
139      */

140     public Asset(AbstractDataStoreInterface dbintrf) {
141         super(dbintrf);
142     }
143
144     /**
145      * Standard constructor for a known resource.
146      *
147      * @param dbintrf the data store to register
148      * @param nId the id of this resource
149      */

150     public Asset(AbstractDataStoreInterface dbintrf, int nId) {
151         super(dbintrf, nId);
152     }
153
154     /**
155      * Sets the content file associated with this <code>Asset</code>.
156      *
157      * @param assetFile the content file
158      * @throws PopulateException if an error occurs setting the specified
159      * file to be the content file for this <code>Asset</code>
160      */

161     public void setContentFile(File assetFile) throws PopulateException {
162         String JavaDoc sContentType = m_sContentType;
163
164         if (m_sContentType == null) {
165             String JavaDoc sExt =
166                 assetFile.getName().substring(
167                     assetFile.getName().indexOf(".") + 1);
168             sContentType = MimeTypeMapping.getMimeTypeFromExtension(sExt);
169             setContentType(sContentType);
170         }
171
172         if (isAssetSavedAsText(sContentType) == true) {
173             try {
174                 FileReader freader = new FileReader(assetFile);
175
176                 StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc();
177
178                 int numRead = 0;
179                 int numToRead = 4096;
180
181                 char[] buf = new char[numToRead];
182
183                 while ((numRead = freader.read(buf, 0, numToRead)) != -1) {
184                     sbuf.append(buf, 0, numRead);
185                 }
186
187                 this.setURI(sbuf.toString());
188
189                 freader.close();
190             } catch (IOException e) {
191                 throw new PopulateException(
192                     "Error occured while reading from the file",e);
193             }
194         } else {
195             setURI(assetFile.getAbsolutePath());
196         }
197
198         setIsChanged(true);
199     }
200
201     /**
202      * Returns the mime type of this <code>Asset</code>.
203      *
204      * @return the mime type of this <code>Asset</code>
205      * @throws DataAccessException if an error occurs populating this
206      * object
207      */

208     public String JavaDoc getContentType() throws DataAccessException {
209         if (isPopulated() == false && m_sContentType == null) {
210             try {
211                 populateFromDatabase();
212             } catch (PopulateException e) {
213                 throw new DataAccessException(
214                     "Error occured populating object",e);
215             }
216         }
217
218         return m_sContentType;
219     }
220
221     /**
222      * Sets the mime type of this <code>Asset</code>.
223      *
224      * @param sContentType the mime type
225      *
226      * @throws PopulateException if an error occurs setting this mime type value
227      */

228     public void setContentType(String JavaDoc sContentType) throws PopulateException {
229         if (isPopulated() == true) {
230             if (m_sContentType.equals(sContentType) == false) {
231                 setIsChanged(true);
232             }
233         }
234
235         m_sContentType = sContentType;
236     }
237
238     /**
239      * Sets the URI for this <code>Asset</code>.
240      *
241      * @param sContent the URI
242      */

243     public void setURI(String JavaDoc sContent) {
244         try {
245             //make a relative path from absolute path
246
sContent = getRelativePath(sContent);
247         } catch (DataAccessException e) {
248             m_logger.log(Level.WARNING, e.getMessage(), e);
249         }
250         
251         
252         if (isPopulated() == true) {
253             if (m_sURI.equals(sContent) == false) {
254                 setIsChanged(true);
255             }
256         }
257
258         if (sContent.equals(m_sURI) == false) {
259             setIsContentChanged(true);
260         }
261         
262         m_sURI = sContent;
263
264     }
265
266     /**
267      * Returns the <code>File</code> associated with this <code>Asset</code>.
268      *
269      * @return the <code>File</code> associated with this <code>Asset</code>
270      * @throws DataAccessException if an error occurs accessing the content
271      * file of this <code>Asset</code>
272      */

273     public File getContentFile() throws DataAccessException {
274         File file = null;
275         String JavaDoc sContentType = getContentType();
276
277         if (isAssetSavedAsText(sContentType) == false) {
278             String JavaDoc sFilename = this.getURI();
279
280             if (sFilename != null) {
281                 file = new File(sFilename);
282             }
283         }
284
285         return file;
286     }
287
288     /**
289      * Returns the URI associated with this <code>Asset</code>.
290      *
291      * @return the URI associated with this <code>Asset</code>
292      * @throws DataAccessException if an error occurs populating this
293      * object from the database
294      */

295     public String JavaDoc getURI() throws DataAccessException {
296         if (isPopulated() == false) {
297             try {
298                 populateFromDatabase();
299             } catch (PopulateException e) {
300                 throw new DataAccessException(
301                     "Error occured populating data",e);
302             }
303         }
304         
305         String JavaDoc sURI = null;
306         
307         //build full path from relative path
308
if(m_sURI != null) {
309             
310             if(isRelativePath(m_sURI) == true) {
311                 StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc();
312                 String JavaDoc sAssetRoot = getAssetRoot();
313                 sbuf.append(sAssetRoot);
314                 
315                 if(sAssetRoot.endsWith(File.separator) == false
316                         && m_sURI.startsWith(File.separator) == false) {
317                     sbuf.append(File.separatorChar);
318                 }
319                 
320                 sbuf.append(m_sURI);
321                 sURI = sbuf.toString();
322             } else {
323                 sURI = m_sURI;
324             }
325         }
326         
327
328         return sURI;
329     }
330
331     /**
332      * Returns <code>true</code> if the specified path is a relative path,
333      * i.e. does not start with a root
334      *
335      * @return
336      */

337     private boolean isRelativePath(String JavaDoc sPath) {
338         boolean bIsRelative = true;
339         
340         try {
341             //if the asset is saved as text then it's not a path to
342
//a local file and therefore not relative
343
bIsRelative = (isAssetSavedAsText(getContentType()) == false);
344         } catch (DataAccessException e) {
345             m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
346         }
347         
348         if(bIsRelative == true) {
349             File[] roots = File.listRoots();
350             
351             for (int i = 0; i < roots.length; i++) {
352                 if(sPath.startsWith(roots[i].getAbsolutePath()) == true) {
353                     bIsRelative = false;
354                     break;
355                 }
356             }
357         }
358         
359         return bIsRelative;
360     }
361
362     /**
363      * Copies an existing file to the specified file location.
364      *
365      * @param from the current file
366      * @param to the copy file
367      * @return <code>true</code> if the operation was successful, otherwise <code>false</code>
368      */

369     static public boolean copyFile(File from, File to) {
370         boolean bMoved = true;
371
372         BufferedInputStream buffIS = null;
373         BufferedOutputStream buffOS = null;
374
375         try {
376             buffIS = new BufferedInputStream(new FileInputStream(from));
377             buffOS = new BufferedOutputStream(new FileOutputStream(to));
378
379             int nByte = buffIS.read();
380
381             while (nByte != -1) {
382                 buffOS.write(nByte);
383                 nByte = buffIS.read();
384             }
385         } catch (Exception JavaDoc e) {
386             bMoved = false;
387             m_logger.log(Level.WARNING,e.getLocalizedMessage(),e);
388         } finally {
389             try {
390                 buffOS.close();
391                 buffIS.close();
392             } catch (Exception JavaDoc e) {
393                 m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
394             }
395         }
396
397         return bMoved;
398     }
399
400     /**
401      * Moves a file from one location to another.
402      *
403      * @param from the current file
404      * @param to the destination file
405      *
406      * @return <code>true</code> if this operation was successful, otherwise <code>false</code>
407      */

408     static public boolean moveFile(File from, File to) {
409         boolean bMoved = true;
410
411         BufferedInputStream buffIS = null;
412         BufferedOutputStream buffOS = null;
413         
414         if(from.exists() == true) {
415
416             try {
417                 buffIS = new BufferedInputStream(new FileInputStream(from));
418                 buffOS = new BufferedOutputStream(new FileOutputStream(to));
419     
420                 int nByte = buffIS.read();
421     
422                 while (nByte != -1) {
423                     buffOS.write(nByte);
424                     nByte = buffIS.read();
425                 }
426             } catch (Exception JavaDoc e) {
427                 bMoved = false;
428                 m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
429             } finally {
430                 try {
431                     buffOS.close();
432                     buffIS.close();
433                 } catch (Exception JavaDoc e) {
434                     m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
435                 }
436             }
437     
438             try {
439                 from.delete();
440             } catch (Exception JavaDoc e) {
441                 bMoved = false;
442                 m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
443             }
444         } else {
445             m_logger.log(Level.WARNING, "Tried to move non-existing file:" + from.getAbsolutePath());
446             bMoved = false;
447         }
448
449         return bMoved;
450     }
451
452     /* (non-Javadoc)
453      * @see org.openharmonise.rm.publishing.Publishable#publish(org.w3c.dom.Element, org.openharmonise.rm.publishing.HarmoniseOutput, org.openharmonise.rm.publishing.State)
454      */

455     public Element publish(Element topEl, HarmoniseOutput output, State state)
456         throws PublishException {
457         Element docEl = null;
458         String JavaDoc sTagName = topEl.getTagName();
459
460         if (sTagName.equals(TAG_URI)) {
461             docEl = output.createElement(sTagName);
462
463             String JavaDoc sContents = "";
464
465             try {
466                 if (m_nId != NOTDBSAVED_ID) {
467                     sContents = getURI();
468                 }
469
470                 if (sContents != null) {
471                     Text txtAssetURL = output.createTextNode(getFullURL());
472                     docEl.appendChild(txtAssetURL);
473                 }
474             } catch (DataAccessException e) {
475                 throw new PublishException(
476                     "Error occured publishing asset url",e);
477             }
478         } else if (sTagName.equals(TAG_CONTENT_TYPE) == true) {
479             docEl = output.createElement(sTagName);
480             try {
481                 Text txt = output.createTextNode(getContentType());
482                 docEl.appendChild(txt);
483             } catch (DataAccessException e) {
484                 throw new PublishException(
485                     "Error occured getting content type",e);
486             }
487             output.copyChildren(docEl, topEl, new Vector());
488         } else {
489             docEl = super.publish(topEl, output, state);
490         }
491
492         return docEl;
493     }
494
495     /**
496      * Returns the full URI for this <code>Asset</code>, specifically
497      * including the installation site URI.
498      *
499      * @return the full URI for this <code>Asset</code>
500      * @throws DataAccessException if an error occurs populating the URI or
501      * obtaining the site URI
502      */

503     public String JavaDoc getFullURL() throws DataAccessException {
504         String JavaDoc path = "";
505         String JavaDoc sURI = this.getURI();
506         String JavaDoc sContentType = getContentType();
507
508         if ((sContentType != null)
509             && (sContentType.startsWith(TXT_LINK) == false)) {
510             try {
511                 String JavaDoc sAssetRootFilePath = getAssetRoot();
512                 String JavaDoc sSiteURL = ConfigSettings.getProperty(PNAME_SITE_URL);
513                 String JavaDoc sAssetWebappURI = ConfigSettings.getProperty(PNAME_ASSET_WEBAPP_URI);
514                 
515                 if(sURI.startsWith(sAssetRootFilePath) == false) {
516                     throw new DataAccessException("Asset path does not start with expected path");
517                 }
518                 
519                 StringBuffer JavaDoc sURL = new StringBuffer JavaDoc();
520                 sURL.append(sSiteURL);
521                 
522                 if(sSiteURL.endsWith("/") == false
523                         && sAssetWebappURI.startsWith("/") == false) {
524                     sURL.append("/");
525                 }
526                 
527                 sURL.append(sAssetWebappURI);
528                 if(sAssetWebappURI.endsWith("/") == false) {
529                     sURL.append("/");
530                 }
531                 sURL.append(sURI
532                             .substring(sAssetRootFilePath.length())
533                                 .replace(File.separatorChar, '/'));
534                 
535                 path = sURL.toString();
536                 
537             } catch (ConfigException e) {
538                 throw new DataAccessException(
539                     "Error occured accessing config property",e);
540             }
541             
542         } else {
543             path = sURI;
544         }
545
546         return path;
547     }
548
549     /* (non-Javadoc)
550      * @see org.openharmonise.rm.resources.AbstractEditableObject#delete(boolean)
551      */

552     public void delete(boolean bDeleteHistory)
553         throws
554             DataStoreException,
555             DataAccessException,
556             EditException,
557             PopulateException {
558         File file = null;
559
560         if (bDeleteHistory == true) {
561             file = getContentFile();
562         }
563
564         super.delete(bDeleteHistory);
565
566         if (file != null) {
567             file.delete();
568         }
569     }
570
571     /* (non-Javadoc)
572      * @see org.openharmonise.rm.dsi.DataStoreObject#getDBTableName()
573      */

574     public String JavaDoc getDBTableName() {
575         return TBL_ASSET;
576     }
577
578     /* (non-Javadoc)
579      * @see org.openharmonise.rm.publishing.Publishable#getTagName()
580      */

581     public String JavaDoc getTagName() {
582         return TAG_ASSET;
583     }
584     
585     /**
586      * Returns the root file path for assets
587      *
588      * @return
589      * @throws DataAccessException
590      */

591     public String JavaDoc getAssetRoot() throws DataAccessException {
592         String JavaDoc sRoot = null;
593         
594         try {
595             sRoot = ConfigSettings.getProperty(PNAME_ASSET_ROOT_FILEPATH);
596         } catch (ConfigException e) {
597             throw new DataAccessException(e);
598         }
599         
600         return sRoot;
601     }
602
603     /* (non-Javadoc)
604      * @see org.openharmonise.rm.dsi.DataStoreObject#getInstanceJoinConditions(java.lang.String, boolean)
605      */

606     public JoinConditions getInstanceJoinConditions(
607         String JavaDoc sObjectTag,
608         boolean bIsOuter)
609         throws DataStoreException {
610
611         return null;
612     }
613
614     /* (non-Javadoc)
615      * @see org.openharmonise.rm.resources.AbstractChildObject#getParentObjectClassName()
616      */

617     public String JavaDoc getParentObjectClassName() {
618
619         return Section.class.getName();
620     }
621
622     /* (non-Javadoc)
623      * @see org.openharmonise.rm.dsi.DataStoreObject#getInstanceColumnRef(java.lang.String, boolean)
624      */

625     public ColumnRef getInstanceColumnRef(String JavaDoc sColumn, boolean bIsHist)
626         throws DataStoreException {
627         ColumnRef colref = null;
628
629         String JavaDoc sTable = getTableName(bIsHist);
630
631         if (sColumn.equals(CLMN_URI) == true) {
632             colref = new ColumnRef(sTable, CLMN_URI, ColumnRef.TEXT);
633         } else if (sColumn.equals(CLMN_MIME_TYPE) == true) {
634             colref = new ColumnRef(sTable, CLMN_MIME_TYPE, ColumnRef.TEXT);
635         } else {
636             colref = super.getInstanceColumnRef(sColumn, bIsHist);
637         }
638
639         return colref;
640     }
641
642     /*--------------------------------------------------------------------------
643     Protected Methods
644     ---------------------------------------------------------------------------*/

645
646     /**
647      * Returns a <code>File</code> representing a new directory in the
648      * file system. Any parent directories which do not already exist will
649      * be created.
650      *
651      * @param sDir The full path of the directory to create
652      * @return a <code>File</code> representing a new directory in the
653      * file system
654      */

655     static protected File createDir(String JavaDoc sDir) {
656         StringTokenizer tokens = new StringTokenizer(sDir, File.separator);
657         File dirNext = null;
658         String JavaDoc sNext = null;
659         StringBuffer JavaDoc sSoFar = new StringBuffer JavaDoc();
660
661         if (sDir.startsWith(File.separator)) {
662             sSoFar.append(File.separator);
663         } else {
664             sNext = tokens.nextToken();
665             sSoFar.append(sNext);
666             sSoFar.append(File.separator);
667         }
668
669         while (tokens.hasMoreTokens()) {
670             sNext = tokens.nextToken();
671             sSoFar.append(sNext);
672             dirNext = new File(sSoFar.toString());
673
674             if (dirNext.exists() == false) {
675                 dirNext.mkdir();
676             }
677         }
678
679         return dirNext;
680     }
681
682     /* (non-Javadoc)
683      * @see org.openharmonise.rm.resources.AbstractEditableObject#addDataToSave(org.openharmonise.commons.dsi.dml.InsertStatement)
684      */

685     protected void addDataToSave(InsertStatement insert)
686         throws DataStoreException {
687
688         try {
689             if (getContentType().startsWith(TXT_LINK) == false
690                 && isContentChanged() == true) {
691                 String JavaDoc sFileName = getURI();
692
693                 // need to discover if the changes in the asset mean the file should be moved
694
File newFile = createFile();
695                 
696                 if (sFileName.equals(newFile.getAbsolutePath()) == false) {
697                     boolean bSuccess = true;
698
699                     //if content has changed move the file
700
//otherwise, we're just creating a new version and we need to
701
//keep the old one
702
if (m_bIsContentChanged == true) {
703                         bSuccess = moveFile(new File(sFileName), newFile);
704                     } else {
705                         bSuccess = copyFile(new File(sFileName), newFile);
706                     }
707
708                     if (bSuccess == false) {
709                         throw new DataStoreException("File manipulation failed");
710                     }
711
712                 }
713
714                 m_sURI = newFile.getAbsolutePath();
715             }
716         } catch (DataAccessException e) {
717             throw new DataStoreException(
718                 "Error occured accessing object data",
719                 e);
720         } catch (AssetException e) {
721             throw new DataStoreException("Error handling asset", e);
722         } catch (ConfigException e) {
723             throw new DataStoreException("Error accessing config setting", e);
724         }
725
726         insert.addColumnValue(
727             getInstanceColumnRef(CLMN_MIME_TYPE, isHistorical()),
728             m_sContentType);
729         
730         try {
731             
732             //ensure the saved path is a relative path
733
m_sURI = getRelativePath(m_sURI);
734             
735             
736             insert.addColumnValue(
737                 getInstanceColumnRef(CLMN_URI, isHistorical()),
738                 m_sURI);
739         } catch (DataAccessException e) {
740             throw new DataStoreException(e);
741         }
742
743         super.addDataToSave(insert);
744
745         //reset content changed flag
746
m_bIsContentChanged = false;
747     }
748
749     /* (non-Javadoc)
750      * @see org.openharmonise.rm.resources.AbstractEditableObject#saveCoreData()
751      */

752     protected void saveCoreData() throws EditException {
753         super.saveCoreData();
754     }
755
756     /* (non-Javadoc)
757      * @see org.openharmonise.rm.resources.AbstractObject#populateFromResultSetRow(java.sql.ResultSet, org.openharmonise.commons.dsi.dml.SelectStatement)
758      */

759     protected void populateFromResultSetRow(
760         ResultSet rs,
761         SelectStatement select)
762         throws PopulateException {
763         if (isPopulated() == false) {
764
765             String JavaDoc sTemp = null;
766
767             try {
768
769                 ColumnRefCache cache = ColumnRefCache.getInstance();
770                 boolean bIsHist = isHistorical();
771
772                 ColumnRef colref = cache.getColumnRef(this, CLMN_URI, bIsHist);
773                 if (select.containsSelectColumn(colref) == true) {
774                     sTemp = rs.getString(select.getResultSetIndex(colref));
775
776                     if ((sTemp != null) && (sTemp.length() > 0)) {
777                         if ((m_sURI == null) || (m_sURI.length() == 0)) {
778                             m_sURI = sTemp;
779                         } else if (m_sURI.equals(sTemp) == false) {
780                             setIsChanged(true);
781                         }
782                     }
783                 }
784
785                 colref = cache.getColumnRef(this, CLMN_MIME_TYPE, bIsHist);
786                 if (select.containsSelectColumn(colref) == true) {
787                     sTemp = rs.getString(select.getResultSetIndex(colref));
788
789                     if ((sTemp != null) && (sTemp.length() > 0)) {
790                         if ((m_sContentType == null)
791                             || (m_sContentType.length() == 0)) {
792                             m_sContentType = sTemp;
793                         } else if (m_sContentType.equals(sTemp) == false) {
794                             setIsChanged(true);
795                         }
796                     }
797                 }
798             } catch (SQLException e) {
799                 throw new PopulateException("Error occured populating", e);
800             } catch (CacheException e) {
801                 throw new PopulateException("Error occured populating", e);
802             }
803
804             super.populateFromResultSetRow(rs, select);
805         }
806
807     }
808
809     /* (non-Javadoc)
810      * @see org.openharmonise.rm.resources.AbstractObject#addColumnsToPopulateQuery(org.openharmonise.commons.dsi.dml.SelectStatement, boolean)
811      */

812     protected void addColumnsToPopulateQuery(
813         SelectStatement select,
814         boolean bIsHist)
815         throws DataStoreException {
816
817         try {
818             ColumnRefCache cache = ColumnRefCache.getInstance();
819
820             select.addSelectColumn(cache.getColumnRef(this, CLMN_URI, bIsHist));
821
822             select.addSelectColumn(
823                 cache.getColumnRef(this, CLMN_MIME_TYPE, bIsHist));
824         } catch (CacheException e) {
825             throw new DataStoreException(e.getLocalizedMessage(), e);
826         }
827
828         super.addColumnsToPopulateQuery(select, bIsHist);
829
830     }
831
832     /*--------------------------------------------------------------------------
833     Private Methods
834     ---------------------------------------------------------------------------*/

835
836     /**
837      * Returns a <code>File</code> which has a path correct for the current
838      * <code>Asset</code>.
839      *
840      * Note: the file path will follow the pattern
841      * &lt;asset root&gt;/&lt;first letter of asset name&gt;/&lt;asset name&gt;
842      * for example 'C:\assets\F\foo.gif'
843      *
844      *
845      * @return a <code>File</code> which has a path correct for the current
846      * <code>Asset</code>.
847      * @throws AssetException if the parent directory of the new content
848      * file does not exist
849      * @throws ConfigException if an error occurs obtaining the asset root
850      * configuration property
851      * @throws DataAccessException if an error occurs getting this object's
852      * name, used for the file name
853      */

854     protected File createFile()
855         throws AssetException, ConfigException, DataAccessException {
856         String JavaDoc sFilePath = null;
857
858         sFilePath =
859             ConfigSettings.getProperty(PNAME_ASSET_ROOT_FILEPATH).replace(
860                 '/',
861                 File.separatorChar);
862
863         String JavaDoc sName = getName();
864         String JavaDoc sSuffix = MimeTypeMapping.getExtensionFromMimeType(getContentType());
865
866         StringBuffer JavaDoc sFullPath = new StringBuffer JavaDoc();
867         sFullPath.append(sFilePath);
868
869         //esure there's a separator at the end of the path
870
if (sFilePath.charAt(sFilePath.length() - 1) != File.separatorChar) {
871             sFullPath.append(File.separatorChar);
872         }
873
874         //ensure file is in a directory under the root which matches the first
875
//letter of this Asset's name
876
sFullPath.append(Character.toUpperCase(sName.charAt(0)));
877
878         sFullPath.append(File.separatorChar);
879
880         sFullPath.append(sName).append("_").append(getKey());
881         sFullPath.append(".").append(sSuffix);
882
883         //check path is valid, i.e. that parent exists
884
File test = new File(sFullPath.toString());
885
886         if (ensureParentExists(test) == false) {
887             throw new AssetException("Trouble creating asset file - parent does not exist");
888         }
889
890         int nCount = 1;
891
892         //in the unlikely event that there already exists a file with the same name
893
//rename it with a count added
894
while (test.exists()) {
895             sFullPath = new StringBuffer JavaDoc();
896             sFullPath.append(sFilePath);
897             if(sFilePath.endsWith(File.separator) == false) {
898                 sFullPath.append(File.separatorChar);
899             }
900             sFullPath.append(sName);
901             sFullPath.append("_[");
902             sFullPath.append(nCount);
903             sFullPath.append("]");
904             sFullPath.append(".");
905             sFullPath.append(sSuffix);
906             test = new File(sFullPath.toString());
907             nCount++;
908         }
909
910         return test;
911     }
912
913     /**
914      * Returns <code>true</code> if the parent of the given <code>File</code> exists.
915      * If the parent does not exist an attempt will be made to create it, if this
916      * fails the method will return <code>false</code>.
917      *
918      * @param file the file whose parent's existance is to be tested
919      * @return <code>true</code> if the parent of the given <code>File</code> exists
920      */

921     protected boolean ensureParentExists(File file) {
922         File parent = file.getParentFile();
923
924         boolean breturn = parent.exists();
925
926         if (breturn == false) {
927             if (ensureParentExists(parent) == true) {
928                 
929                 breturn = parent.mkdir();
930             }
931         }
932
933         return breturn;
934     }
935
936     /* (non-Javadoc)
937      * @see org.openharmonise.rm.resources.AbstractEditableObject#saveNonCoreData()
938      */

939     protected void saveNonCoreData() throws EditException {
940
941     }
942     
943     /**
944      * Returns <code>true</code> if the URI value for this <code>Asset</code>
945      * has changed.
946      *
947      * @return <code>true</code> if the URI value for this <code>Asset</code>
948      * has changed
949      */

950     public boolean isContentChanged() {
951         return m_bIsContentChanged;
952     }
953
954     /**
955      * Sets the value of the content changed flag.
956      *
957      * @param bContentChanged <code>true</code> to indicate a change in the content, otherwise <code>false</code>
958      */

959     public void setIsContentChanged(boolean bContentChanged) {
960         m_bIsContentChanged = bContentChanged;
961     }
962
963     /* (non-Javadoc)
964      * @see org.openharmonise.rm.resources.AbstractObject#clear()
965      */

966     public void clear() {
967         m_sContentType = null;
968         m_sURI = null;
969         m_bIsContentChanged = false;
970         super.clear();
971     }
972     
973     /**
974      * Returns <code>true</code> if an asset of the specified mime type
975      * should be saved in DB as text rather than as a file.
976      *
977      * @param sContentType the mime type
978      * @return <code>true</code> if asset should be saved in DB as
979      * text rather than as a file
980      */

981     protected boolean isAssetSavedAsText(String JavaDoc sContentType) {
982         return sContentType.startsWith(TXT_LINK)
983                     || sContentType.startsWith(TXT_TEXT);
984     }
985     
986     /**
987      * Returns the relative path for the given absolute path.
988      *
989      * Note: this assumes that the absolute path starts with the
990      * current asset root path
991      *
992      * @param sAbsolutePath
993      * @return
994      * @throws DataAccessException
995      */

996     protected String JavaDoc getRelativePath(String JavaDoc sAbsolutePath) throws DataAccessException {
997         String JavaDoc sRelPath = sAbsolutePath;
998         
999         String JavaDoc sAssetRoot = getAssetRoot();
1000        
1001        if(sAbsolutePath != null
1002                && sAbsolutePath.startsWith(sAssetRoot) == true) {
1003            sRelPath = sAbsolutePath.substring(sAssetRoot.length());
1004        }
1005        
1006        return sRelPath;
1007    }
1008
1009}
Popular Tags