KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opencms > defaults > master > genericsql > CmsDbAccess


1 /*
2 * File : $Source: /usr/local/cvs/opencms/src-modules/com/opencms/defaults/master/genericsql/CmsDbAccess.java,v $
3 * Date : $Date: 2005/06/27 23:22:23 $
4 * Version: $Revision: 1.7 $
5 *
6 * This library is part of OpenCms -
7 * the Open Source Content Mananagement System
8 *
9 * Copyright (C) 2001 The OpenCms Group
10 *
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
15 *
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
20 *
21 * For further information about OpenCms, please see the
22 * OpenCms Website: http://www.opencms.org
23 *
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
26 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 */

28
29 package com.opencms.defaults.master.genericsql;
30
31 import org.opencms.db.CmsDbUtil;
32 import org.opencms.db.CmsPublishedResource;
33 import org.opencms.db.CmsUserSettings;
34 import org.opencms.file.CmsGroup;
35 import org.opencms.file.CmsObject;
36 import org.opencms.file.CmsProject;
37 import org.opencms.file.CmsResource;
38 import org.opencms.file.CmsUser;
39 import org.opencms.main.CmsException;
40 import org.opencms.main.CmsLog;
41 import org.opencms.main.OpenCms;
42 import org.opencms.security.CmsSecurityException;
43 import org.opencms.setup.CmsSetupDb;
44 import org.opencms.util.CmsUUID;
45
46 import com.opencms.defaults.master.CmsMasterContent;
47 import com.opencms.defaults.master.CmsMasterDataSet;
48 import com.opencms.defaults.master.CmsMasterMedia;
49 import com.opencms.legacy.CmsLegacyException;
50 import com.opencms.legacy.CmsLegacySecurityException;
51
52 import java.io.ByteArrayInputStream JavaDoc;
53 import java.lang.reflect.Constructor JavaDoc;
54 import java.sql.Connection JavaDoc;
55 import java.sql.PreparedStatement JavaDoc;
56 import java.sql.ResultSet JavaDoc;
57 import java.sql.SQLException JavaDoc;
58 import java.sql.Timestamp JavaDoc;
59 import java.sql.Types JavaDoc;
60 import java.util.Iterator JavaDoc;
61 import java.util.Map JavaDoc;
62 import java.util.Vector JavaDoc;
63
64 /**
65  * This class provides methods to access the database in a generic way.
66  *
67  * @deprecated Will not be supported past the OpenCms 6 release.
68  */

69 public class CmsDbAccess {
70
71     /** The root channel of the module */
72     protected String JavaDoc m_rootChannel = "/";
73
74     /** TODO: delete this after successful change of dbpool */
75     private String JavaDoc m_poolUrl;
76
77     /** 'Constants' file. */
78     protected com.opencms.defaults.master.genericsql.CmsSqlManager m_sqlManager;
79
80     /**
81      * Public empty constructor, call "init(String)" on this class afterwards.
82      * This allows more flexible custom module development.<p>
83      */

84     public CmsDbAccess() {}
85
86     /**
87      * Constructs a new DbAccessObject and calls init(String) with the given String.<p>
88      * @param dbPool the pool to access resources.
89      */

90     public CmsDbAccess(String JavaDoc dbPool) {
91         init(dbPool);
92     }
93
94     /**
95      * Initializes the SqlManager with the used pool.<p>
96      */

97     public com.opencms.defaults.master.genericsql.CmsSqlManager init(String JavaDoc dbPool) {
98         m_sqlManager = initQueries(dbPool, getClass());
99         m_poolUrl = dbPool;
100         
101         return m_sqlManager;
102     }
103
104     /**
105      * Retrieve the correct instance of the queries holder.
106      * This method should be overloaded if other query strings should be used.<p>
107      */

108     public com.opencms.defaults.master.genericsql.CmsSqlManager initQueries(String JavaDoc dbPoolUrl, Class JavaDoc currentClass) {
109         return new com.opencms.defaults.master.genericsql.CmsSqlManager(dbPoolUrl, currentClass);
110     }
111
112     /**
113      * Checks if the master module table is available by performing
114      * a simple query on it.<p>
115      *
116      * @return true if the query was successfully performed, false otherwise
117      */

118     public boolean checkTables() {
119         PreparedStatement JavaDoc stmt = null;
120         Connection JavaDoc conn = null;
121         try {
122             conn = m_sqlManager.getConnection();
123             stmt = m_sqlManager.getPreparedStatement(conn, "check_module_master");
124             stmt.executeQuery();
125             return true;
126                 
127         } catch (SQLException JavaDoc exc) {
128             return false;
129             
130         } finally {
131             m_sqlManager.closeAll(null, conn, stmt, null);
132         }
133     }
134
135     /**
136      * Performs an update script on a database.<p>
137      *
138      * @param updateScript the script
139      * @param replacers parameter/values to replace within the script
140      * @throws CmsException if something goes wrong
141      */

142     public void updateDatabase(String JavaDoc updateScript, Map JavaDoc replacers) throws CmsException {
143         CmsSetupDb setup = new CmsSetupDb(""); /* TODO: add base path, even if not needed */
144         Connection JavaDoc conn = null;
145         
146         try {
147             conn = m_sqlManager.getConnection();
148             setup.setConnection(conn);
149             setup.updateDatabase(updateScript, replacers, true);
150             
151             Vector JavaDoc errors = setup.getErrors();
152             if (!errors.isEmpty()) {
153                 StringBuffer JavaDoc errorMessages = new StringBuffer JavaDoc();
154                 for (Iterator JavaDoc i = errors.iterator(); i.hasNext();) {
155                     errorMessages.append((String JavaDoc)i.next());
156                     errorMessages.append("\n");
157                 }
158                 throw new CmsLegacyException(errorMessages.toString(), CmsLegacyException.C_SQL_ERROR);
159             }
160         } catch (SQLException JavaDoc exc) {
161             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
162         } finally {
163             m_sqlManager.closeAll(null, conn, null, null);
164         }
165     }
166     
167     /**
168      * Set the root channel of the content.<p>
169      *
170      * @param newRootChannel the new value for the rootChannel.
171      */

172     public void setRootChannel(String JavaDoc newRootChannel) {
173         m_rootChannel = newRootChannel;
174     }
175
176     /**
177      * Get the root channel of the content.<p>
178      *
179      * @return String the root channel.
180      */

181     public String JavaDoc getRootChannel() {
182         return m_rootChannel;
183     }
184
185     /**
186      * Inserts a new single row in the database with the dataset.<p>
187      *
188      * @param cms the CmsObject to get access to cms resources.
189      * @param content the CmsMasterContent to write to the database.
190      * @param dataset the set of data for this contentdefinition.
191      * @throws CmsException if somethong goes wrong
192      */

193     public void insert(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset) throws CmsException {
194         if (isOnlineProject(cms)) {
195             // this is the onlineproject - don't write into this project directly
196
throw new CmsSecurityException(Messages.get().container(Messages.ERR_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT_0));
197         }
198        
199         if (dataset.m_masterId == null || CmsUUID.getNullUUID().equals(dataset.m_masterId)) {
200             // create a new master ID
201
dataset.m_masterId = new CmsUUID();
202         }
203         
204         int projectId = cms.getRequestContext().currentProject().getId();
205         long currentTime = new java.util.Date JavaDoc().getTime();
206         
207         CmsUUID currentUserId = cms.getRequestContext().currentUser().getId();
208         dataset.m_userId = currentUserId;
209
210         CmsUUID defaultGroupId = CmsUUID.getNullUUID();
211         String JavaDoc defaultGroupName = null;
212         
213         try {
214             defaultGroupName = (String JavaDoc)cms.getRequestContext().currentUser().getAdditionalInfo(
215                 CmsUserSettings.ADDITIONAL_INFO_DEFAULTGROUP);
216             
217             if (defaultGroupName == null || "".equalsIgnoreCase(defaultGroupName)) {
218                 if (CmsLog.getLog(this).isWarnEnabled()) {
219                     CmsLog.getLog(this).warn(
220                         "Error reading default group of user "
221                         + cms.getRequestContext().currentUser().getName()
222                         + ", using group "
223                         + OpenCms.getDefaultUsers().getGroupUsers()
224                         + " instead");
225                 }
226                 
227                 defaultGroupName = OpenCms.getDefaultUsers().getGroupUsers();
228             }
229             
230             CmsGroup defaultGroup = cms.readGroup(defaultGroupName);
231             defaultGroupId = defaultGroup.getId();
232         } catch (CmsException e) {
233             if (CmsLog.getLog(this).isErrorEnabled()) {
234                 CmsLog.getLog(this).error(
235                     "Error reading default group "
236                         + defaultGroupName
237                         + " of user "
238                         + cms.getRequestContext().currentUser().getName(),
239                     e);
240             }
241
242             defaultGroupId = CmsUUID.getNullUUID();
243         }
244         
245         dataset.m_groupId = defaultGroupId;
246
247         dataset.m_projectId = projectId;
248         dataset.m_lockedInProject = projectId;
249         dataset.m_state = CmsResource.STATE_NEW;
250         dataset.m_lockedBy = currentUserId;
251         dataset.m_lastModifiedBy = currentUserId;
252         dataset.m_dateCreated = currentTime;
253         dataset.m_dateLastModified = currentTime;
254
255         PreparedStatement JavaDoc stmt = null;
256         Connection JavaDoc conn = null;
257         try {
258             conn = m_sqlManager.getConnection();
259             stmt = m_sqlManager.getPreparedStatement(conn, "insert_offline");
260             sqlFillValues(stmt, content.getSubId(), dataset);
261             stmt.executeUpdate();
262             // after inserting the row, we have to update media and channel tables
263
updateMedia(dataset.m_masterId, dataset.m_mediaToAdd, new Vector JavaDoc(), new Vector JavaDoc());
264             updateChannels(cms, dataset.m_masterId, dataset.m_channelToAdd, dataset.m_channelToDelete);
265         } catch (SQLException JavaDoc exc) {
266             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
267         } finally {
268             m_sqlManager.closeAll(null, conn, stmt, null);
269         }
270     }
271
272     /**
273      * Inserts a new row in the database with the copied dataset.<p>
274      *
275      * @param cms the CmsObject to get access to cms resources.
276      * @param content the CmsMasterContent to write to the database.
277      * @param dataset the set of data for this contentdefinition.
278      * @param mediaToAdd a Vector of media to add.
279      * @param channelToAdd a Vector of channels to add.
280      * @return CmsUUID The uuid of the new content definition
281      * @throws CmsException in case something goes wrong
282      */

283     public CmsUUID copy(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset, Vector JavaDoc mediaToAdd, Vector JavaDoc channelToAdd) throws CmsException {
284         if (isOnlineProject(cms)) {
285             // this is the onlineproject - don't write into this project directly
286
throw new CmsSecurityException(Messages.get().container(Messages.ERR_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT_0));
287         }
288         if (dataset.m_versionId != CmsDbUtil.UNKNOWN_ID) {
289             // this is not the online row - it was read from history
290
// don't write it!
291
throw new CmsLegacySecurityException("Can't update a cd with a backup cd ", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
292         }
293         if (!content.isWriteable()) {
294             // no write access
295
throw new CmsLegacySecurityException("Not writeable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
296         }
297         CmsUUID newMasterId = new CmsUUID();
298         int projectId = cms.getRequestContext().currentProject().getId();
299         CmsUUID currentUserId = cms.getRequestContext().currentUser().getId();
300         long currentTime = new java.util.Date JavaDoc().getTime();
301         // filling some default-values for new dataset's
302
dataset.m_masterId = newMasterId;
303         dataset.m_projectId = projectId;
304         dataset.m_lockedInProject = projectId;
305         dataset.m_state = CmsResource.STATE_NEW;
306         dataset.m_lockedBy = currentUserId;
307         dataset.m_lastModifiedBy = currentUserId;
308         dataset.m_dateCreated = currentTime;
309         dataset.m_dateLastModified = currentTime;
310
311         PreparedStatement JavaDoc stmt = null;
312         Connection JavaDoc conn = null;
313         try {
314             conn = m_sqlManager.getConnection();
315             stmt = m_sqlManager.getPreparedStatement(conn, "insert_offline");
316             sqlFillValues(stmt, content.getSubId(), dataset);
317             stmt.executeUpdate();
318             // after inserting the row, we have to update media and channel tables
319
updateMedia(dataset.m_masterId, mediaToAdd, new Vector JavaDoc(), new Vector JavaDoc());
320             updateChannels(cms, dataset.m_masterId, channelToAdd, new Vector JavaDoc());
321         } catch (SQLException JavaDoc exc) {
322             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
323         } finally {
324             m_sqlManager.closeAll(null, conn, stmt, null);
325         }
326         return newMasterId;
327     }
328
329     /**
330      * Updates the lockstate in the database.<p>
331      *
332      * @param cms the CmsObject to get access to cms resources.
333      * @param content the CmsMasterContent to write to the database.
334      * @param dataset the set of data for this contentdefinition.
335      */

336     public void writeLockstate(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset) throws CmsException {
337         if (isOnlineProject(cms)) {
338             // this is the onlineproject - don't write into this project directly
339
throw new CmsSecurityException(Messages.get().container(Messages.ERR_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT_0));
340         }
341         if (!content.isWriteable()) {
342             // no write access
343
throw new CmsLegacySecurityException("Not writeable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
344         }
345         if (!dataset.m_lockedBy.isNullUUID()) {
346             // lock the resource into the current project
347
dataset.m_lockedInProject = cms.getRequestContext().currentProject().getId();
348         }
349
350         PreparedStatement JavaDoc stmt = null;
351         Connection JavaDoc conn = null;
352         try {
353             conn = m_sqlManager.getConnection();
354             stmt = m_sqlManager.getPreparedStatement(conn, "update_lockstate_offline");
355             stmt.setString(1, dataset.m_lockedBy.toString());
356             stmt.setInt(2, dataset.m_lockedInProject);
357             stmt.setString(3, dataset.m_masterId.toString());
358             stmt.setInt(4, content.getSubId());
359             stmt.executeUpdate();
360         } catch (SQLException JavaDoc exc) {
361             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
362         } finally {
363             m_sqlManager.closeAll(null, conn, stmt, null);
364         }
365     }
366
367     /**
368      * Write the dataset to the database.<p>
369      *
370      * @param cms the CmsObject to get access to cms resources.
371      * @param content the CmsMasterContent to write to the database.
372      * @param dataset the set of data for this contentdefinition.
373      */

374     public void write(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset) throws CmsException {
375         if (isOnlineProject(cms)) {
376             // this is the onlineproject - don't write into this project directly
377
throw new CmsSecurityException(Messages.get().container(Messages.ERR_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT_0));
378         }
379         if (dataset.m_versionId != CmsDbUtil.UNKNOWN_ID) {
380             // this is not the online row - it was read from history
381
// don't write it!
382
throw new CmsLegacySecurityException("Can't update a cd with a backup cd", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
383         }
384         // read the lockstate
385
readLockstate(dataset, content.getSubId());
386         if (!dataset.m_lockedBy.equals(cms.getRequestContext().currentUser().getId())) {
387             // is not locked by this user
388
throw new CmsLegacySecurityException("Not locked by this user", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
389         }
390         if (dataset.m_lockedInProject != dataset.m_projectId) {
391             // not locked in this project
392
throw new CmsLegacySecurityException("Not locked in this project", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
393         }
394         if (!content.isWriteable()) {
395             // no write access
396
throw new CmsLegacySecurityException("Not writeable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
397         }
398
399         long currentTime = new java.util.Date JavaDoc().getTime();
400         CmsUUID currentUserId = cms.getRequestContext().currentUser().getId();
401         // updateing some values for updated dataset
402
if (dataset.m_state != CmsResource.STATE_NEW) {
403             // if the state is not new then set the state to changed
404
dataset.m_state = CmsResource.STATE_CHANGED;
405         }
406         dataset.m_lastModifiedBy = currentUserId;
407         dataset.m_dateLastModified = currentTime;
408
409         PreparedStatement JavaDoc stmt = null;
410         Connection JavaDoc conn = null;
411         try {
412             conn = m_sqlManager.getConnection();
413             stmt = m_sqlManager.getPreparedStatement(conn, "update_offline");
414             int rowcounter = sqlFillValues(stmt, content.getSubId(), dataset);
415             stmt.setString(rowcounter++, dataset.m_masterId.toString());
416             stmt.setInt(rowcounter++, content.getSubId());
417             stmt.executeUpdate();
418             // after inserting the row, we have to update media and channel tables
419
updateMedia(dataset.m_masterId, dataset.m_mediaToAdd, dataset.m_mediaToUpdate, dataset.m_mediaToDelete);
420             updateChannels(cms, dataset.m_masterId, dataset.m_channelToAdd, dataset.m_channelToDelete);
421         } catch (SQLException JavaDoc exc) {
422             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
423         } finally {
424             m_sqlManager.closeAll(null, conn, stmt, null);
425         }
426     }
427
428     /**
429      * Read the dataset with the given UUID from the database.<p>
430      *
431      * @param cms the CmsObject to get access to cms-ressources.
432      * @param content the CmsMasterContent to write to the database.
433      * @param dataset the set of data for this contentdefinition.
434      * @param contentId the UUID of the contentdefinition.
435      */

436     public void read(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset, CmsUUID contentId) throws CmsException {
437         if (!content.isReadable()) {
438             // no read access
439
throw new CmsLegacySecurityException("Not readable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
440         }
441         String JavaDoc statement_key = "read_offline";
442         if (isOnlineProject(cms)) {
443             statement_key = "read_online";
444         }
445
446         PreparedStatement JavaDoc stmt = null;
447         ResultSet JavaDoc res = null;
448         Connection JavaDoc conn = null;
449         try {
450             conn = m_sqlManager.getConnection();
451             stmt = m_sqlManager.getPreparedStatement(conn, statement_key);
452             stmt.setString(1, contentId.toString());
453             stmt.setInt(2, content.getSubId());
454             res = stmt.executeQuery();
455             if (res.next()) {
456                 sqlFillValues(res, cms, dataset);
457             } else {
458                 throw new CmsLegacyException("[" + this.getClass().getName() + ".read] no content found for CID:" + contentId + ", SID: " + content.getSubId() + ", statement: " + statement_key, CmsLegacyException.C_NOT_FOUND);
459             }
460             if (!checkAccess(content, false)) {
461                 throw new CmsLegacySecurityException("Not readable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
462             }
463         } catch (SQLException JavaDoc exc) {
464             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
465         } finally {
466             m_sqlManager.closeAll(null, conn, stmt, res);
467         }
468     }
469
470     /**
471      * Read the lockstate from the database.
472      * We need this because of someone has maybe stolen the lock.<p>
473      *
474      * @param dataset the dataset to read the lockstate into.
475      * @param subId the subId of this cd
476      */

477     protected void readLockstate(CmsMasterDataSet dataset, int subId) throws CmsException {
478         PreparedStatement JavaDoc stmt = null;
479         ResultSet JavaDoc res = null;
480         Connection JavaDoc conn = null;
481         try {
482             conn = m_sqlManager.getConnection();
483             stmt = m_sqlManager.getPreparedStatement(conn, "read_lockstate_offline");
484             stmt.setString(1, dataset.m_masterId.toString());
485             stmt.setInt(2, subId);
486             res = stmt.executeQuery();
487             if (res.next()) {
488                 // update the values
489
dataset.m_lockedInProject = res.getInt(1);
490                 dataset.m_lockedBy = new CmsUUID(res.getString(2));
491             } else {
492                 // no values found - this is a new row
493
}
494         } catch (SQLException JavaDoc exc) {
495             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
496         } finally {
497             m_sqlManager.closeAll(null, conn, stmt, res);
498         }
499     }
500
501     /**
502      * Reads all media contents from the database.<p>
503      *
504      * @param cms the CmsObject to get access to cms resources.
505      * @param content the CmsMasterContent to write to the database.
506      * @return a Vector of media objects.
507      */

508     public Vector JavaDoc readMedia(CmsObject cms, CmsMasterContent content) throws CmsException {
509         if (!content.isReadable()) {
510             // no read access
511
throw new CmsLegacySecurityException("Not readable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
512         }
513         Vector JavaDoc retValue = new Vector JavaDoc();
514         String JavaDoc statement_key = "read_media_offline";
515         if (isOnlineProject(cms)) {
516             statement_key = "read_media_online";
517         }
518
519         PreparedStatement JavaDoc stmt = null;
520         ResultSet JavaDoc res = null;
521         Connection JavaDoc conn = null;
522         try {
523             conn = m_sqlManager.getConnection();
524             stmt = m_sqlManager.getPreparedStatement(conn, statement_key);
525             stmt.setString(1, content.getId().toString());
526             res = stmt.executeQuery();
527             while (res.next()) {
528                 int i = 1;
529                 retValue.add(new CmsMasterMedia(res.getInt(i++), new CmsUUID(res.getString(i++)), res.getInt(i++), res.getInt(i++), res.getInt(i++), res.getInt(i++), res.getString(i++), res.getInt(i++), res.getString(i++), res.getString(i++), res.getString(i++), res.getBytes(i++)));
530             }
531         } catch (SQLException JavaDoc exc) {
532             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
533         } finally {
534             m_sqlManager.closeAll(null, conn, stmt, res);
535         }
536         return retValue;
537     }
538
539     /**
540      * Reads all channels from the database.<p>
541      *
542      * @param cms the CmsObject to get access to cms resources.
543      * @param content the CmsMasterContent to write to the database.
544      * @return a Vector of channel names.
545      */

546     public Vector JavaDoc readChannels(CmsObject cms, CmsMasterContent content) throws CmsException {
547         if (!content.isReadable()) {
548             // no read access
549
throw new CmsLegacySecurityException("Not readable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
550         }
551         Vector JavaDoc retValue = new Vector JavaDoc();
552         String JavaDoc statement_key = "read_channel_names_offline";
553         if (isOnlineProject(cms)) {
554             statement_key = "read_channel_names_online";
555         }
556
557         PreparedStatement JavaDoc stmt = null;
558         ResultSet JavaDoc res = null;
559         Connection JavaDoc conn = null;
560         try {
561             conn = m_sqlManager.getConnection();
562             stmt = m_sqlManager.getPreparedStatement(conn, statement_key);
563             stmt.setString(1, content.getId().toString());
564             res = stmt.executeQuery();
565
566             while (res.next()) {
567                 // get the channel id
568
String JavaDoc channeldName = res.getString(1);
569                 retValue.add(channeldName );
570             }
571             
572         } catch (SQLException JavaDoc exc) {
573             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
574         } finally {
575             m_sqlManager.closeAll(null, conn, stmt, res);
576         }
577         return retValue;
578     }
579
580     /**
581      * Reads all content definitions of a given channel.<p>
582      *
583      * @param cms the CmsObject to get access to cms resources.
584      * @param channelId the id of the channel.
585      * @param subId the sub ID of the contentdefinition.
586      * @return Vector the datasets of the contentdefinitions in the channel.
587      */

588     public Vector JavaDoc readAllByChannel(CmsObject cms, String JavaDoc channelId, int subId) throws CmsException {
589         Vector JavaDoc theDataSets = new Vector JavaDoc();
590         String JavaDoc statement_key = "readallbychannel_offline";
591         if (isOnlineProject(cms)) {
592             statement_key = "readallbychannel_online";
593         }
594
595         PreparedStatement JavaDoc stmt = null;
596         ResultSet JavaDoc res = null;
597         Connection JavaDoc conn = null;
598         try {
599             conn = m_sqlManager.getConnection();
600             stmt = m_sqlManager.getPreparedStatement(conn, statement_key);
601             stmt.setInt(1, subId);
602             stmt.setString(2, channelId);
603             res = stmt.executeQuery();
604             while (res.next()) {
605                 CmsMasterDataSet dataset = new CmsMasterDataSet();
606                 sqlFillValues(res, cms, dataset);
607                 theDataSets.add(dataset);
608             }
609         } catch (SQLException JavaDoc exc) {
610             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
611         } finally {
612             m_sqlManager.closeAll(null, conn, stmt, res);
613         }
614         return theDataSets;
615     }
616
617     /**
618      * Delete a dataset from the offline table.<p>
619      *
620      * @param cms the CmsObject to get access to cms-ressources.
621      * @param content the CmsMasterContent to write to the database.
622      * @param dataset the set of data for this contentdefinition.
623      */

624     public void delete(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset) throws CmsException {
625         if (isOnlineProject(cms)) {
626             // this is the onlineproject - don't write into this project directly
627
throw new CmsSecurityException(Messages.get().container(Messages.ERR_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT_0));
628         }
629         if (dataset.m_versionId != CmsDbUtil.UNKNOWN_ID) {
630             // this is not the online row - it was read from history
631
// don't delete it!
632
throw new CmsLegacySecurityException("Can't delete a backup cd", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
633         }
634         // read the lockstate
635
readLockstate(dataset, content.getSubId());
636         if ((!dataset.m_lockedBy.equals(cms.getRequestContext().currentUser().getId()))) {
637             // is not locked by this user
638
throw new CmsLegacySecurityException("Not locked by this user", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
639         }
640         if (dataset.m_lockedInProject != dataset.m_projectId) {
641             // not locked in this project
642
throw new CmsLegacySecurityException("Not locked in this project", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
643         }
644         if (!content.isWriteable()) {
645             // no write access
646
throw new CmsLegacySecurityException("Not writeable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
647         }
648
649         if (dataset.m_state == CmsResource.STATE_NEW) {
650             // this is a new line in this project and can be deleted
651
String JavaDoc statement_key = "delete_offline";
652             PreparedStatement JavaDoc stmt = null;
653             Connection JavaDoc conn = null;
654             try {
655                 conn = m_sqlManager.getConnection();
656                 stmt = m_sqlManager.getPreparedStatement(conn, statement_key);
657                 stmt.setString(1, dataset.m_masterId.toString());
658                 stmt.setInt(2, content.getSubId());
659                 if (stmt.executeUpdate() != 1) {
660                     // no line deleted - row wasn't found
661
throw new CmsLegacyException("Row not found: " + dataset.m_masterId + " " + content.getSubId(), CmsLegacyException.C_NOT_FOUND);
662                 }
663                 // after deleting the row, we have to delete media and channel rows
664
deleteAllMedia(dataset.m_masterId);
665                 deleteAllChannels(dataset.m_masterId);
666             } catch (SQLException JavaDoc exc) {
667                 throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
668             } finally {
669                 m_sqlManager.closeAll(null, conn, stmt, null);
670             }
671         } else {
672             // set state to deleted and update the line
673
dataset.m_state = CmsResource.STATE_DELETED;
674             dataset.m_lockedBy = CmsUUID.getNullUUID();
675             PreparedStatement JavaDoc stmt = null;
676             Connection JavaDoc conn = null;
677             try {
678                 conn = m_sqlManager.getConnection();
679                 stmt = m_sqlManager.getPreparedStatement(conn, "update_offline");
680                 int rowcounter = sqlFillValues(stmt, content.getSubId(), dataset);
681                 stmt.setString(rowcounter++, dataset.m_masterId.toString());
682                 stmt.setInt(rowcounter++, content.getSubId());
683                 stmt.executeUpdate();
684             } catch (SQLException JavaDoc exc) {
685                 throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
686             } finally {
687                 m_sqlManager.closeAll(null, conn, stmt, null);
688             }
689         }
690     }
691
692     /**
693      * Undelete a prevoiusly deleted contentdefinition.<p>
694      *
695      * @param cms the CmsObject to get access to cms resources.
696      * @param content the CmsMasterContent to write to the database.
697      * @param dataset the set of data for this contentdefinition.
698      */

699     public void undelete(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset) throws CmsException {
700         if (isOnlineProject(cms)) {
701             // this is the onlineproject - don't write into this project directly
702
throw new CmsSecurityException(Messages.get().container(Messages.ERR_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT_0));
703         }
704         if (dataset.m_versionId != CmsDbUtil.UNKNOWN_ID) {
705             // this is not the online row - it was read from history
706
// don't delete it!
707
throw new CmsLegacySecurityException("Can't undelete a backup cd ", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
708         }
709         if (!content.isWriteable()) {
710             // no write access
711
throw new CmsLegacySecurityException("Not writeable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
712         }
713         // set state to deleted and update the line
714
dataset.m_state = CmsResource.STATE_CHANGED;
715         dataset.m_lockedBy = cms.getRequestContext().currentUser().getId();
716         dataset.m_lockedInProject = cms.getRequestContext().currentProject().getId();
717         PreparedStatement JavaDoc stmt = null;
718         Connection JavaDoc conn = null;
719         try {
720             conn = m_sqlManager.getConnection();
721             stmt = m_sqlManager.getPreparedStatement(conn, "update_offline");
722             int rowcounter = sqlFillValues(stmt, content.getSubId(), dataset);
723             stmt.setString(rowcounter++, dataset.m_masterId.toString());
724             stmt.setInt(rowcounter++, content.getSubId());
725             stmt.executeUpdate();
726         } catch (SQLException JavaDoc exc) {
727             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
728         } finally {
729             m_sqlManager.closeAll(null, conn, stmt, null);
730         }
731     }
732
733     /**
734      * Changes the permissions of the content.<p>
735      *
736      * @param cms the CmsObject to get access to cms resources.
737      * @param content the CmsMasterContent to write to the database.
738      * @param dataset the set of data for this contentdefinition.
739      */

740     public void changePermissions(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset) throws CmsException {
741         if (isOnlineProject(cms)) {
742             // this is the onlineproject - don't write into this project directly
743
throw new CmsSecurityException(Messages.get().container(Messages.ERR_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT_0));
744         }
745         if (dataset.m_versionId != CmsDbUtil.UNKNOWN_ID) {
746             // this is not the online row - it was read from history
747
// don't delete it!
748
throw new CmsLegacySecurityException("Can't change permissions of a backup cd ", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
749         }
750         // read the lockstate
751
readLockstate(dataset, content.getSubId());
752         if (!dataset.m_lockedBy.equals(cms.getRequestContext().currentUser().getId())) {
753             // is not locked by this user
754
throw new CmsLegacySecurityException("Not locked by this user", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
755         }
756         if (dataset.m_lockedInProject != dataset.m_projectId) {
757             // not locked in this project
758
throw new CmsLegacySecurityException("Not locked in this project", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
759         }
760         if (!content.isWriteable()) {
761             // no write access
762
throw new CmsLegacySecurityException("Not writeable", CmsLegacySecurityException.C_SECURITY_NO_PERMISSIONS);
763         }
764         if (dataset.m_state != CmsResource.STATE_NEW) {
765             dataset.m_state = CmsResource.STATE_CHANGED;
766         }
767         dataset.m_dateLastModified = System.currentTimeMillis();
768         dataset.m_lastModifiedBy = cms.getRequestContext().currentUser().getId();
769         // update the line
770
PreparedStatement JavaDoc stmt = null;
771         Connection JavaDoc conn = null;
772         try {
773             conn = m_sqlManager.getConnection();
774             stmt = m_sqlManager.getPreparedStatement(conn, "update_permissions_offline");
775             stmt.setString(1, dataset.m_userId.toString());
776             stmt.setString(2, dataset.m_groupId.toString());
777             stmt.setInt(3, dataset.m_accessFlags);
778             stmt.setInt(4, dataset.m_state);
779             stmt.setString(5, dataset.m_lastModifiedBy.toString());
780             stmt.setTimestamp(6, new Timestamp JavaDoc(dataset.m_dateLastModified));
781             stmt.setString(7, dataset.m_masterId.toString());
782             stmt.setInt(8, content.getSubId());
783             stmt.executeUpdate();
784         } catch (SQLException JavaDoc exc) {
785             throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
786         } finally {
787             m_sqlManager.closeAll(null, conn, stmt, null);
788         }
789     }
790
791     /**
792      * Returns a string representation of this instance.
793      * This can be used for debugging.<p>
794      *
795      * @return the string representation of this instance.
796      */

797     public String JavaDoc toString() {
798         StringBuffer JavaDoc returnValue = new StringBuffer JavaDoc();
799         returnValue.append(this.getClass().getName() + "{");
800         returnValue.append("Used db pool=" + m_poolUrl + ";");
801         returnValue.append("}");
802         return returnValue.toString();
803     }
804
805     /**
806      * Inserts all values to the statement for insertion and update.<p>
807      *
808      * @param stmt the Statement to fill the values to.
809      * @param subId the subid of this module.
810      * @param dataset the set of data for this contentdefinition.
811      * @return the current rowcounter.
812      */

813     protected int sqlFillValues(PreparedStatement JavaDoc stmt, int subId, CmsMasterDataSet dataset) throws SQLException JavaDoc {
814         // columncounter
815
int i = 1;
816         //// COREDATA ////
817
stmt.setString(i++, dataset.m_masterId.toString());
818         stmt.setInt(i++, subId);
819         stmt.setString(i++, dataset.m_userId.toString());
820         stmt.setString(i++, dataset.m_groupId.toString());
821         stmt.setInt(i++, dataset.m_lockedInProject);
822         stmt.setInt(i++, dataset.m_accessFlags);
823         stmt.setInt(i++, dataset.m_state);
824         stmt.setString(i++, dataset.m_lockedBy.toString());
825         stmt.setString(i++, dataset.m_lastModifiedBy.toString());
826         stmt.setTimestamp(i++, new Timestamp JavaDoc(dataset.m_dateCreated));
827         stmt.setTimestamp(i++, new Timestamp JavaDoc(dataset.m_dateLastModified));
828         //// USERDATA ////
829
stmt.setTimestamp(i++, new Timestamp JavaDoc(dataset.m_publicationDate));
830         stmt.setTimestamp(i++, new Timestamp JavaDoc(dataset.m_purgeDate));
831         stmt.setInt(i++, dataset.m_flags);
832         stmt.setInt(i++, dataset.m_feedId);
833         stmt.setInt(i++, dataset.m_feedReference);
834         if (dataset.m_feedFilename == null) {
835             stmt.setNull(i++, Types.VARCHAR);
836         } else {
837             stmt.setString(i++, dataset.m_feedFilename);
838         }
839         if (dataset.m_title == null) {
840             stmt.setNull(i++, Types.VARCHAR);
841         } else {
842             stmt.setString(i++, dataset.m_title);
843         }
844         //// GENERIC DATA ////
845
i = sqlSetTextArray(stmt, dataset.m_dataBig, i);
846         i = sqlSetTextArray(stmt, dataset.m_dataMedium, i);
847         i = sqlSetTextArray(stmt, dataset.m_dataSmall, i);
848         i = sqlSetIntArray(stmt, dataset.m_dataInt, i);
849         i = sqlSetIntArray(stmt, dataset.m_dataReference, i);
850         i = sqlSetDateArray(stmt, dataset.m_dataDate, i);
851         return i;
852     }
853
854     /**
855      * Inserts all values to the statement for insert and update.<p>
856      *
857      * @param res the Resultset read the values from.
858      * @param cms the CmsObject to get access to cms resources.
859      * @param dataset the set of data for this contentdefinition.
860      * @return the current rowcounter.
861      */

862     protected int sqlFillValues(ResultSet JavaDoc res, CmsObject cms, CmsMasterDataSet dataset) throws SQLException JavaDoc {
863         // columncounter
864
int i = 1;
865         //// COREDATA ////
866
dataset.m_masterId = new CmsUUID(res.getString(i++));
867         // cw/12.02.2004 - subId was not read, but was already defined in data set - need it in search
868
dataset.m_subId = res.getInt(i++);
869         dataset.m_userId = new CmsUUID(res.getString(i++));
870         dataset.m_groupId = new CmsUUID(res.getString(i++));
871         dataset.m_lockedInProject = res.getInt(i++);
872         // compute project based on the current project and the channels
873
dataset.m_projectId = computeProjectId(cms, dataset);
874         dataset.m_accessFlags = res.getInt(i++);
875         dataset.m_state = res.getInt(i++);
876         dataset.m_lockedBy = new CmsUUID(res.getString(i++));
877         dataset.m_lastModifiedBy = new CmsUUID(res.getString(i++));
878         dataset.m_dateCreated = res.getTimestamp(i++).getTime();
879         dataset.m_dateLastModified = res.getTimestamp(i++).getTime();
880         //// USERDATA ////
881
dataset.m_publicationDate = res.getTimestamp(i++).getTime();
882         dataset.m_purgeDate = res.getTimestamp(i++).getTime();
883         dataset.m_flags = res.getInt(i++);
884         dataset.m_feedId = res.getInt(i++);
885         dataset.m_feedReference = res.getInt(i++);
886         dataset.m_feedFilename = res.getString(i++);
887         dataset.m_title = res.getString(i++);
888         //// GENERIC DATA ////
889
i = sqlSetTextArray(res, dataset.m_dataBig, i);
890         i = sqlSetTextArray(res, dataset.m_dataMedium, i);
891         i = sqlSetTextArray(res, dataset.m_dataSmall, i);
892         i = sqlSetIntArray(res, dataset.m_dataInt, i);
893         i = sqlSetIntArray(res, dataset.m_dataReference, i);
894         i = sqlSetDateArray(res, dataset.m_dataDate, i);
895         return i;
896     }
897
898     /**
899      * Computes the correct project id based on the current user and the channels.<p>
900      *
901      * @param cms the CmsObject
902      * @param dataset the dataSet
903      * @return int the project id
904      * @throws SQLException if something goes wrong
905      */

906     protected int computeProjectId(CmsObject cms, CmsMasterDataSet dataset) throws SQLException JavaDoc {
907         //int onlineProjectId = I_CmsConstants.UNKNOWN_ID;
908
int offlineProjectId = CmsDbUtil.UNKNOWN_ID;
909
910         offlineProjectId = cms.getRequestContext().currentProject().getId();
911         //onlineProjectId = I_CmsConstants.ONLINE_PROJECT_ID;
912

913         if (!isOnlineProject(cms)) {
914             // this is an offline project -> compute if we have to return the
915
// online project id or the offline project id
916

917             // the owner and the administrtor has always access
918
if ((cms.getRequestContext().currentUser().getId().equals(dataset.m_userId)) || cms.isAdmin()) {
919                 return offlineProjectId;
920             }
921             
922             return offlineProjectId;
923
924             // DISABLED: always return current offline project ID!
925
// String statement_key = "read_channel_offline";
926
//
927
// PreparedStatement stmt = null;
928
// ResultSet res = null;
929
// Connection conn = null;
930
// cms.getRequestContext().saveSiteRoot();
931
// try {
932
// cms.setContextToCos();
933
// conn = m_sqlManager.getConnection();
934
// stmt = m_sqlManager.getPreparedStatement(conn, statement_key);
935
// stmt.setString(1, dataset.m_masterId.toString());
936
// res = stmt.executeQuery();
937
// while (res.next()) {
938
// // get the channel id
939
// String channelId = res.getString(1);
940
// // read the resource by property "channelid"
941
// CmsFolder channelFolder = null;
942
// try {
943
// channelFolder = cms.readFolder(new CmsUUID(channelId), false);
944
// //resources = cms.getResourcesWithPropertyDefintion(I_CmsConstants.C_PROPERTY_CHANNELID, channelId + "", CmsResourceTypeFolder.C_RESOURCE_TYPE_ID);
945
// } catch (CmsException exc) {
946
// // ignore the exception - read the next one
947
// }
948
// if (channelFolder != null) {
949
// int resProjectId = channelFolder.getProjectLastModified();
950
// if (resProjectId == offlineProjectId) {
951
// // yes - we have found a channel that belongs to
952
// // the current offlineproject -> we can return the
953
// // offline project id as computed project id
954
// return offlineProjectId;
955
// }
956
// }
957
// }
958
// } finally {
959
// cms.getRequestContext().restoreSiteRoot();
960
// m_sqlManager.closeAll(conn, stmt, res);
961
// }
962
}
963         // no channel found that belongs to the offlineproject ->
964
// return the online project id.
965
return offlineProjectId;
966     }
967
968     /**
969      * Sets an array of strings into the statement.<p>
970      *
971      * @param stmt the PreparedStatement to set the values into.
972      * @param array the array of strings to set.
973      * @param the columnscounter for the statement.
974      * @return the increased columnscounter;
975      */

976     protected int sqlSetTextArray(PreparedStatement JavaDoc stmt, String JavaDoc[] array, int columnscounter) throws SQLException JavaDoc {
977         for (int j = 0; j < array.length; j++) {
978             if (array[j] == null) {
979                 stmt.setNull(columnscounter++, Types.LONGVARCHAR);
980             } else {
981                 stmt.setString(columnscounter++, array[j]);
982             }
983         }
984         return columnscounter;
985     }
986
987     /**
988      * Sets an array of strings from the resultset.<p>
989      *
990      * @param res the ResultSet to get the values from.
991      * @param array the array of strings to set.
992      * @param the columnscounter for the res.
993      * @return the increased columnscounter;
994      */

995     protected int sqlSetTextArray(ResultSet JavaDoc res, String JavaDoc[] array, int columnscounter) throws SQLException JavaDoc {
996         for (int j = 0; j < array.length; j++) {
997             array[j] = res.getString(columnscounter++);
998         }
999         return columnscounter;
1000    }
1001
1002    /**
1003     * Sets an array of ints into the statement.<p>
1004     *
1005     * @param stmt the PreparedStatement to set the values into.
1006     * @param array the array of ints to set.
1007     * @param the columnscounter for the stmnt.
1008     * @return the increased columnscounter;
1009     */

1010    protected int sqlSetIntArray(PreparedStatement JavaDoc stmt, int[] array, int columnscounter) throws SQLException JavaDoc {
1011        for (int j = 0; j < array.length; j++) {
1012            stmt.setInt(columnscounter++, array[j]);
1013        }
1014        return columnscounter;
1015    }
1016
1017    /**
1018     * Sets an array of ints from the resultset.<p>
1019     *
1020     * @param res the ResultSet to get the values from.
1021     * @param array the array of ints to set.
1022     * @param the columnscounter for the res.
1023     * @return the increased columnscounter;
1024     */

1025    protected int sqlSetIntArray(ResultSet JavaDoc res, int[] array, int columnscounter) throws SQLException JavaDoc {
1026        for (int j = 0; j < array.length; j++) {
1027            array[j] = res.getInt(columnscounter++);
1028        }
1029        return columnscounter;
1030    }
1031
1032    /**
1033     * Sets an array of longs (dates) into the statement.<p>
1034     *
1035     * @param stmt the PreparedStatement to set the values into.
1036     * @param array the array of longs to set.
1037     * @param the columnscounter for the stmnt.
1038     * @return the increased columnscounter;
1039     */

1040    protected int sqlSetDateArray(PreparedStatement JavaDoc stmt, long[] array, int columnscounter) throws SQLException JavaDoc {
1041        for (int j = 0; j < array.length; j++) {
1042            stmt.setTimestamp(columnscounter++, new Timestamp JavaDoc(array[j]));
1043        }
1044        return columnscounter;
1045    }
1046
1047    /**
1048     * Sets an array of longs (dates) from the resultset.<p>
1049     *
1050     * @param res the ResultSet to get the values from.
1051     * @param array the array of longs to set.
1052     * @param the columnscounter for the res.
1053     * @return the increased columnscounter;
1054     */

1055    protected int sqlSetDateArray(ResultSet JavaDoc res, long[] array, int columnscounter) throws SQLException JavaDoc {
1056        for (int j = 0; j < array.length; j++) {
1057            array[j] = res.getTimestamp(columnscounter++).getTime();
1058        }
1059        return columnscounter;
1060    }
1061
1062    /**
1063     * Returns a vector of contentdefinitions based on the sql resultset.
1064     * Never mind about the visible flag.<p>
1065     *
1066     * @param res the ResultSet to get data lines from.
1067     * @param contentDefinitionClass the class of the cd to create new instances.
1068     * @param cms the CmsObject to get access to cms resources.
1069     * @throws SqlException if nothing could be read from the resultset.
1070     */

1071    protected Vector JavaDoc createVectorOfCd(ResultSet JavaDoc res, Class JavaDoc contentDefinitionClass, CmsObject cms) throws SQLException JavaDoc {
1072        return createVectorOfCd(res, contentDefinitionClass, cms, false);
1073    }
1074
1075    /**
1076     * Returns a vector of contentdefinitions based on the sql resultset.<p>
1077     *
1078     * @param res the ResultSet to get data-lines from.
1079     * @param contentDefinitionClass the class of the cd to create new instances.
1080     * @param cms the CmsObject to get access to cms resources.
1081     * @param viewonly decides, if only the ones that are visible should be returned
1082     * @throws SqlException if nothing could be read from the resultset.
1083     */

1084    protected Vector JavaDoc createVectorOfCd(ResultSet JavaDoc res, Class JavaDoc contentDefinitionClass, CmsObject cms, boolean viewonly) throws SQLException JavaDoc {
1085        Constructor JavaDoc constructor;
1086        Vector JavaDoc retValue = new Vector JavaDoc();
1087       
1088        try { // to get the constructor to create an empty contentDefinition
1089
constructor = contentDefinitionClass.getConstructor(new Class JavaDoc[] { CmsObject.class, CmsMasterDataSet.class });
1090        } catch (NoSuchMethodException JavaDoc exc) {
1091            
1092            if (CmsLog.getLog(this).isWarnEnabled()) {
1093                CmsLog.getLog(this).warn("Cannot locate constructor", exc);
1094            }
1095            // canno't fill the vector - missing constructor
1096
return retValue;
1097        }
1098        while (res.next()) { // while there is data in the resultset
1099
CmsMasterDataSet dataset = new CmsMasterDataSet();
1100            try { // to invoce the constructor to get a new empty instance
1101
CmsMasterContent content = (CmsMasterContent)constructor.newInstance(new Object JavaDoc[] { cms, dataset });
1102                
1103                sqlFillValues(res, cms, dataset);
1104                // add the cd only if read (and visible) permissions are granted.
1105
// the visible-permissens will be checked, if viewonly is set to true
1106
// viewonly=true is needed for the backoffice
1107
if (checkAccess(content, viewonly)) {
1108                    retValue.add(content);
1109                }
1110            } catch (Exception JavaDoc exc) {
1111                if (CmsLog.getLog(this).isWarnEnabled()) {
1112                    CmsLog.getLog(this).warn("Cannot invoce constructor", exc);
1113                }
1114            }
1115        }
1116        return retValue;
1117    }
1118
1119    /**
1120     * Returns a vector of contentdefinitions based on the sql resultset.<p>
1121     *
1122     * @param datasets the vector with the datasets.
1123     * @param contentDefinitionClass the class of the cd to create new instances.
1124     * @param cms the CmsObject to get access to cms-ressources.
1125     * @throws SqlException if nothing could be read from the resultset.
1126     */

1127    protected Vector JavaDoc createVectorOfCd(Vector JavaDoc datasets, Class JavaDoc contentDefinitionClass, CmsObject cms) throws SQLException JavaDoc {
1128        Constructor JavaDoc constructor;
1129        Vector JavaDoc retValue = new Vector JavaDoc();
1130        try { // to get the constructor to create an empty contentDefinition
1131
constructor = contentDefinitionClass.getConstructor(new Class JavaDoc[] { CmsObject.class, CmsMasterDataSet.class });
1132        } catch (NoSuchMethodException JavaDoc exc) {
1133            if (CmsLog.getLog(this).isWarnEnabled()) {
1134                CmsLog.getLog(this).warn("Cannot locate constructor", exc);
1135            }
1136            // canno't fill the vector - missing constructor
1137
return retValue;
1138        }
1139        // create content definition for each dataset
1140
for (int i = 0; i < datasets.size(); i++) {
1141            CmsMasterDataSet dataset = (CmsMasterDataSet)datasets.elementAt(i);
1142            try { // to invoce the constructor to get a new empty instance
1143
CmsMasterContent content = (CmsMasterContent)constructor.newInstance(new Object JavaDoc[] { cms, dataset });
1144                retValue.add(content);
1145            } catch (Exception JavaDoc exc) {
1146                if (CmsLog.getLog(this).isWarnEnabled()) {
1147                    CmsLog.getLog(this).warn("Cannot invoce constructor", exc);
1148                }
1149            }
1150        }
1151        return retValue;
1152    }
1153
1154    /**
1155     * Checks if read (and visible) permissions are granted.
1156     * the visible permissions will be checked, if viewonly is set to true
1157     * viewonly=true is needed for the backoffice.<p>
1158     *
1159     * @param content the cd to check.
1160     * @param viewonly if set to true the v-Flag will be checked, too.
1161     */

1162    protected boolean checkAccess(CmsMasterContent content, boolean viewonly) {
1163        if (!content.isReadable()) {
1164            // was not readable
1165
return false;
1166        } else if (viewonly) {
1167            // additional check for v-Flags
1168
return content.isVisible();
1169        } else {
1170            // was readable - return true
1171
return true;
1172        }
1173    }
1174
1175    /**
1176     * Returns true, if the current project is the online project.<p>
1177     *
1178     * @param cms the CmsObject to get access to cms resources.
1179     * @return true, if this is the onlineproject, else returns false
1180     */

1181    protected boolean isOnlineProject(CmsObject cms) {
1182        return cms.getRequestContext().currentProject().isOnlineProject();
1183    }
1184
1185    /**
1186     * Deletes all media lines for a master content definition.<p>
1187     *
1188     * @param masterId - the masterId to delete the media for.
1189     * @throws SQLException if an sql error occurs.
1190     */

1191    protected void deleteAllMedia(CmsUUID masterId) throws SQLException JavaDoc {
1192        String JavaDoc statement_key = "delete_all_media_offline";
1193        PreparedStatement JavaDoc stmt = null;
1194        Connection JavaDoc conn = null;
1195        try {
1196            conn = m_sqlManager.getConnection();
1197            stmt = m_sqlManager.getPreparedStatement(conn, statement_key);
1198            stmt.setString(1, masterId.toString());
1199            stmt.executeUpdate();
1200        } finally {
1201            m_sqlManager.closeAll(null, conn, stmt, null);
1202        }
1203    }
1204
1205    /**
1206     * Deletes all channel lines for one master.<p>
1207     *
1208     * @param masterId - the masterId to delete the channels for.
1209     * @throws SQLException if an sql error occurs.
1210     */

1211    protected void deleteAllChannels(CmsUUID masterId) throws SQLException JavaDoc {
1212        String JavaDoc statement_key = "delete_all_channel_offline";
1213        PreparedStatement JavaDoc stmt = null;
1214        Connection JavaDoc conn = null;
1215        try {
1216            conn = m_sqlManager.getConnection();
1217            stmt = m_sqlManager.getPreparedStatement(conn, statement_key);
1218            stmt.setString(1, masterId.toString());
1219            stmt.executeUpdate();
1220        } finally {
1221            m_sqlManager.closeAll(null, conn, stmt, null);
1222        }
1223    }
1224
1225    /**
1226     * Updates the media object of a content definition.<p>
1227     *
1228     * @param masterId the content definition master id.
1229     * @param mediaToAdd vector of media objects to add.
1230     * @param mediaToUpdate vector of media objects to update.
1231     * @param mediaToDelete vector of media objects to delete.
1232     * @throws SQLException if an sql error occurs.
1233     * @throws CmsException if an error occurs.
1234     */

1235    protected void updateMedia(CmsUUID masterId, Vector JavaDoc mediaToAdd, Vector JavaDoc mediaToUpdate, Vector JavaDoc mediaToDelete) throws SQLException JavaDoc, CmsException {
1236        // add new media
1237
PreparedStatement JavaDoc stmt = null;
1238        Connection JavaDoc conn = null;
1239        try {
1240            conn = m_sqlManager.getConnection();
1241            stmt = m_sqlManager.getPreparedStatement(conn, "insert_media_offline");
1242            for (int i = 0; i < mediaToAdd.size(); i++) {
1243                CmsMasterMedia media = (CmsMasterMedia)mediaToAdd.get(i);
1244                media.setId(CmsDbUtil.nextId(m_poolUrl, "CMS_MODULE_MEDIA"));
1245                media.setMasterId(masterId);
1246                sqlFillValues(stmt, media);
1247                stmt.executeUpdate();
1248            }
1249        } finally {
1250            m_sqlManager.closeAll(null, conn, stmt, null);
1251        }
1252
1253        // update existing media
1254
stmt = null;
1255        conn = null;
1256        try {
1257            conn = m_sqlManager.getConnection();
1258            stmt = m_sqlManager.getPreparedStatement(conn, "update_media_offline");
1259            for (int i = 0; i < mediaToUpdate.size(); i++) {
1260                CmsMasterMedia media = (CmsMasterMedia)mediaToUpdate.get(i);
1261                media.setMasterId(masterId);
1262                int rowCounter = sqlFillValues(stmt, media);
1263                stmt.setInt(rowCounter++, media.getId());
1264                stmt.setString(rowCounter++, masterId.toString());
1265                stmt.executeUpdate();
1266            }
1267        } finally {
1268            m_sqlManager.closeAll(null, conn, stmt, null);
1269        }
1270        // delete unneeded media
1271
stmt = null;
1272        conn = null;
1273        try {
1274            conn = m_sqlManager.getConnection();
1275            stmt = m_sqlManager.getPreparedStatement(conn, "delete_media_offline");
1276            for (int i = 0; i < mediaToDelete.size(); i++) {
1277                CmsMasterMedia media = (CmsMasterMedia)mediaToDelete.get(i);
1278                stmt.setInt(1, media.getId());
1279                stmt.setString(2, masterId.toString());
1280                stmt.executeUpdate();
1281            }
1282        } finally {
1283            m_sqlManager.closeAll(null, conn, stmt, null);
1284        }
1285    }
1286
1287    /**
1288     * Updates the channels of a content definition.<p>
1289     *
1290     * @param cms the current context object.
1291     * @param masterId the content definition master id.
1292     * @param channelToAdd vector of channels to add.
1293     * @param channelToDelete vector of channels to delete.
1294     * @throws SQLException if an sql error occurs.
1295     */

1296    protected void updateChannels(CmsObject cms, CmsUUID masterId, Vector JavaDoc channelToAdd, Vector JavaDoc channelToDelete) throws SQLException JavaDoc {
1297        // add new channel
1298
PreparedStatement JavaDoc stmt = null;
1299        Connection JavaDoc conn = null;
1300        cms.getRequestContext().saveSiteRoot();
1301        cms.getRequestContext().setSiteRoot(CmsResource.VFS_FOLDER_CHANNELS);
1302           conn = m_sqlManager.getConnection();
1303            stmt = m_sqlManager.getPreparedStatement(conn, "insert_channel_offline");
1304            for (int i = 0; i < channelToAdd.size(); i++) {
1305                try {
1306                    stmt.setString(1, masterId.toString());
1307
1308
1309                    //int id=Integer.parseInt(cms.readProperty(channelToAdd.get(i) + "", I_CmsConstants.C_PROPERTY_CHANNELID));
1310
//stmt.setInt(2, id);
1311
CmsResource channel=cms.readFolder((String JavaDoc)channelToAdd.get(i));
1312                    String JavaDoc id=channel.getResourceId().toString();
1313                   
1314                    stmt.setString(2, id);
1315                    stmt.setString(3,(String JavaDoc)channelToAdd.get(i));
1316                    // I_CmsConstants.C_PROPERTY_CHANNELID)));
1317
stmt.executeUpdate();
1318                } catch (CmsException exc) {
1319                    // no channel found - write to logfile
1320
if (CmsLog.getLog(this).isWarnEnabled()) {
1321                        CmsLog.getLog(this).warn("Couldn't find channel " + channelToAdd.get(i), exc);
1322                    }
1323                }
1324            }
1325            m_sqlManager.closeAll(null, conn, stmt, null);
1326            
1327        // delete unneeded channel
1328
stmt = null;
1329        conn = null;
1330        try {
1331            conn = m_sqlManager.getConnection();
1332            stmt = m_sqlManager.getPreparedStatement(conn, "delete_channel_offline");
1333            for (int i = 0; i < channelToDelete.size(); i++) {
1334                //try {
1335
stmt.setString(1, masterId.toString());
1336                    stmt.setString(2, (String JavaDoc)channelToDelete.get(i) );
1337                    // stmnt.setInt(2, Integer.parseInt(cms.readProperty(C_COS_PREFIX + channelToDelete.get(i),
1338
// I_CmsConstants.C_PROPERTY_CHANNELID)));
1339
stmt.executeUpdate();
1340                /*} catch (CmsException exc) {
1341                    // no channel found - write to logfile
1342                    if (CmsLog.getLog(this).isWarnEnabled()) {
1343                        CmsLog.getLog(this).warn("Couldn't find channel " + channelToAdd.get(i), exc);
1344                    }
1345                }*/

1346            }
1347        } finally {
1348            m_sqlManager.closeAll(null, conn, stmt, null);
1349            cms.getRequestContext().restoreSiteRoot();
1350        }
1351    }
1352
1353    /**
1354     * Fills a prepared statement with media values.<p>
1355     *
1356     * @param stmt the statement to fill.
1357     * @param media the data to fill the statement with.
1358     * @return int the number of values set in the statement.
1359     * @throws SQLException if data could not be set in statement.
1360     */

1361    protected int sqlFillValues(PreparedStatement JavaDoc stmt, CmsMasterMedia media) throws SQLException JavaDoc {
1362        int i = 1;
1363        stmt.setInt(i++, media.getId());
1364        stmt.setString(i++, media.getMasterId().toString());
1365        stmt.setInt(i++, media.getPosition());
1366        stmt.setInt(i++, media.getWidth());
1367        stmt.setInt(i++, media.getHeight());
1368        stmt.setInt(i++, media.getSize());
1369        stmt.setString(i++, media.getMimetype());
1370        stmt.setInt(i++, media.getType());
1371        stmt.setString(i++, media.getTitle());
1372        stmt.setString(i++, media.getName());
1373        stmt.setString(i++, media.getDescription());
1374        stmt.setBinaryStream(i++, new ByteArrayInputStream JavaDoc(media.getMedia()), media.getMedia().length);
1375        //stmnt.setBytes(i++, media.getMedia());
1376
return i;
1377    }
1378
1379    /**
1380     * Returns a vector with all version of a master in the backup table.<p>
1381     *
1382     * @param cms the CmsObject.
1383     * @param contentDefinitionClass the Class of the current master.
1384     * @param masterId the id of the master.
1385     * @param subId the sub id of the master.
1386     * @return Vector a vector with all versions of the master.
1387     */

1388    public Vector JavaDoc getHistory(CmsObject cms, Class JavaDoc contentDefinitionClass, CmsUUID masterId, int subId) throws CmsException {
1389        Vector JavaDoc retVector = new Vector JavaDoc();
1390        Vector JavaDoc allBackup = new Vector JavaDoc();
1391        PreparedStatement JavaDoc stmt = null;
1392        ResultSet JavaDoc res = null;
1393        Connection JavaDoc conn = null;
1394        try {
1395            conn = m_sqlManager.getConnection();
1396            stmt = m_sqlManager.getPreparedStatement(conn, "read_all_backup");
1397            stmt.setString(1, masterId.toString());
1398            stmt.setInt(2, subId);
1399            // gets all versions of the master in the backup table
1400
res = stmt.executeQuery();
1401            while (res.next()) {
1402                CmsMasterDataSet dataset = new CmsMasterDataSet();
1403                sqlFillValues(res, cms, dataset);
1404                dataset.m_versionId = res.getInt("TAG_ID");
1405                dataset.m_userName = res.getString("USER_NAME");
1406                dataset.m_groupName = res.getString("GROUP_NAME");
1407                dataset.m_lastModifiedByName = res.getString("LASTMODIFIED_BY_NAME");
1408                allBackup.add(dataset);
1409            }
1410            retVector = createVectorOfCd(allBackup, contentDefinitionClass, cms);
1411        } catch (SQLException JavaDoc e) {
1412            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, e);
1413        } finally {
1414            m_sqlManager.closeAll(null, conn, stmt, res);
1415        }
1416        return retVector;
1417    }
1418
1419    /**
1420     * Returns the version of a master in the backup.<p>
1421     *
1422     * @param cms The CmsObject.
1423     * @param contentDefinitionClass The class of the content definition.
1424     * @param masterId the id of the master.
1425     * @param subId the sub id.
1426     * @param versionId the version id.
1427     * @return CmsMasterContent a content definition of the version.
1428     */

1429    public CmsMasterContent getVersionFromHistory(CmsObject cms, Class JavaDoc contentDefinitionClass, CmsUUID masterId, int subId, int versionId) throws CmsException {
1430        CmsMasterContent content = null;
1431        CmsMasterDataSet dataset = this.getVersionFromHistory(cms, masterId, subId, versionId);
1432        Constructor JavaDoc constructor;
1433        try { // to get the constructor to create an empty contentDefinition
1434
constructor = contentDefinitionClass.getConstructor(new Class JavaDoc[] { CmsObject.class, CmsMasterDataSet.class });
1435        } catch (NoSuchMethodException JavaDoc exc) {
1436            if (CmsLog.getLog(this).isWarnEnabled()) {
1437                CmsLog.getLog(this).warn("Cannot locate constructor", exc);
1438            }
1439            // canno't fill the vector - missing constructor
1440
return content;
1441        }
1442        // create content definition for each dataset
1443
if (dataset != null) {
1444            try { // to invoce the constructor to get a new empty instance
1445
content = (CmsMasterContent)constructor.newInstance(new Object JavaDoc[] { cms, dataset });
1446            } catch (Exception JavaDoc exc) {
1447                if (CmsLog.getLog(this).isWarnEnabled()) {
1448                    CmsLog.getLog(this).warn("Cannot invoke constructor", exc);
1449                }
1450            }
1451        }
1452        return content;
1453    }
1454
1455    /**
1456     * Returns the version of a master from the backup.<p>
1457     *
1458     * @param cms the CmsObject.
1459     * @param masterId the id of the master.
1460     * @param subId the sub id.
1461     * @param versionId the version id.
1462     * @return Vector A vector with all versions of the master
1463     */

1464    public CmsMasterDataSet getVersionFromHistory(CmsObject cms, CmsUUID masterId, int subId, int versionId) throws CmsException {
1465        CmsMasterDataSet dataset = new CmsMasterDataSet();
1466        PreparedStatement JavaDoc stmt = null;
1467        ResultSet JavaDoc res = null;
1468        Connection JavaDoc conn = null;
1469        try {
1470            conn = m_sqlManager.getConnection();
1471            stmt = m_sqlManager.getPreparedStatement(conn, "read_backup");
1472            stmt.setString(1, masterId.toString());
1473            stmt.setInt(2, subId);
1474            stmt.setInt(3, versionId);
1475            // gets the master in the backup table with the given versionid
1476
res = stmt.executeQuery();
1477            if (res.next()) {
1478                sqlFillValues(res, cms, dataset);
1479                dataset.m_versionId = res.getInt("TAG_ID");
1480                dataset.m_userName = res.getString("USER_NAME");
1481                dataset.m_groupName = res.getString("GROUP_NAME");
1482                dataset.m_lastModifiedByName = res.getString("LASTMODIFIED_BY_NAME");
1483            } else {
1484                throw new CmsLegacyException("Row not found: " + masterId + " " + subId + " version " + versionId, CmsLegacyException.C_NOT_FOUND);
1485            }
1486        } catch (SQLException JavaDoc e) {
1487            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, e);
1488        } finally {
1489            m_sqlManager.closeAll(null, conn, stmt, res);
1490        }
1491        return dataset;
1492    }
1493
1494    /**
1495     * Restores a version of the master and media from backup.<p>
1496     *
1497     * @param cms the CmsObject.
1498     * @param content the master content.
1499     * @param dataset the dataset of the master.
1500     * @param versionId the version id of the master and media to restore.
1501     */

1502    public void restore(CmsObject cms, CmsMasterContent content, CmsMasterDataSet dataset, int versionId) throws CmsException {
1503        Connection JavaDoc conn = null;
1504        Connection JavaDoc conn2 = null;
1505        PreparedStatement JavaDoc stmt = null;
1506        PreparedStatement JavaDoc stmt2 = null;
1507        ResultSet JavaDoc res = null;
1508        // first read the version from backup
1509
CmsMasterDataSet backup = getVersionFromHistory(cms, dataset.m_masterId, content.getSubId(), versionId);
1510        // update the dataset
1511
dataset.m_accessFlags = backup.m_accessFlags;
1512        dataset.m_dataBig = backup.m_dataBig;
1513        dataset.m_dataInt = backup.m_dataInt;
1514        dataset.m_dataMedium = backup.m_dataMedium;
1515        dataset.m_dataReference = backup.m_dataReference;
1516        dataset.m_dataDate = backup.m_dataDate;
1517        dataset.m_dataSmall = backup.m_dataSmall;
1518        dataset.m_feedFilename = backup.m_feedFilename;
1519        dataset.m_feedId = backup.m_feedId;
1520        dataset.m_feedReference = backup.m_feedReference;
1521        dataset.m_flags = backup.m_flags;
1522        dataset.m_title = backup.m_title;
1523        dataset.m_publicationDate = backup.m_publicationDate;
1524        dataset.m_purgeDate = backup.m_purgeDate;
1525        dataset.m_channel = new Vector JavaDoc();
1526        dataset.m_channelToAdd = new Vector JavaDoc();
1527        dataset.m_channelToDelete = new Vector JavaDoc();
1528        dataset.m_media = new Vector JavaDoc();
1529        dataset.m_mediaToAdd = new Vector JavaDoc();
1530        dataset.m_mediaToUpdate = new Vector JavaDoc();
1531        dataset.m_mediaToDelete = new Vector JavaDoc();
1532        dataset.m_lastModifiedBy = cms.getRequestContext().currentUser().getId();
1533        if (dataset.m_state != CmsResource.STATE_NEW) {
1534            dataset.m_state = CmsResource.STATE_CHANGED;
1535        }
1536        // check if the group exists
1537
CmsUUID groupId = CmsUUID.getNullUUID();
1538        try {
1539            groupId = cms.readGroup(backup.m_groupId).getId();
1540        } catch (CmsException exc) {
1541            groupId = dataset.m_groupId;
1542        }
1543        dataset.m_groupId = groupId;
1544        // check if the user exists
1545
CmsUUID userId = CmsUUID.getNullUUID();
1546        try {
1547            userId = cms.readUser(backup.m_userId).getId();
1548        } catch (CmsException exc) {
1549            userId = dataset.m_userId;
1550        }
1551        dataset.m_userId = userId;
1552        // write the master
1553
this.write(cms, content, dataset);
1554        // delete the media
1555
try {
1556            deleteAllMedia(dataset.m_masterId);
1557        } catch (SQLException JavaDoc exc) {
1558            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1559        }
1560        // copy the media from backup
1561
try {
1562            conn = m_sqlManager.getConnection();
1563            stmt = m_sqlManager.getPreparedStatement(conn, "read_media_backup");
1564            stmt.setString(1, dataset.m_masterId.toString());
1565            stmt.setInt(2, versionId);
1566            res = stmt.executeQuery();
1567            while (res.next()) {
1568                int i = 1;
1569                CmsMasterMedia media = new CmsMasterMedia(res.getInt(i++), new CmsUUID(res.getString(i++)), res.getInt(i++), res.getInt(i++), res.getInt(i++), res.getInt(i++), res.getString(i++), res.getInt(i++), res.getString(i++), res.getString(i++), res.getString(i++), res.getBytes(i++));
1570                // store the data in offline table
1571
try {
1572                    stmt2 = null;
1573                    conn2 = null;
1574                    conn2 = m_sqlManager.getConnection();
1575                    stmt2 = m_sqlManager.getPreparedStatement(conn2, "insert_media_offline");
1576                    sqlFillValues(stmt2, media);
1577                    stmt2.executeUpdate();
1578                } catch (SQLException JavaDoc ex) {
1579                    throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, ex);
1580                } finally {
1581                    m_sqlManager.closeAll(null, conn2, stmt2, null);
1582                }
1583            }
1584        } catch (SQLException JavaDoc e) {
1585            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, e);
1586        } finally {
1587            m_sqlManager.closeAll(null, conn, stmt, res);
1588        }
1589    }
1590
1591    /**
1592     * Publishes a single content definition.<p>
1593     *
1594     * @param cms The CmsObject
1595     * @param publishHistoryId the ID of the current publish task
1596     * @param dataset the dataset to publish.
1597     * @param subId the subId to publish cd's for.
1598     * @param contentDefinitionName the name of the contentdefinition.
1599     * @param enableHistory set to true if backup tables should be filled.
1600     * @param versionId the versionId to save in the backup tables.
1601     * @param publishingDate the date and time of this publishing process.
1602     * @param changedResources a Vector of changed resources.
1603     * @param changedModuleData a Vector of changed moduledata.
1604     */

1605    public void publishResource(CmsObject cms, CmsUUID publishHistoryId, CmsMasterDataSet dataset, int subId, String JavaDoc contentDefinitionName, boolean enableHistory, int versionId, long publishingDate, Vector JavaDoc changedResources, Vector JavaDoc changedModuleData) throws CmsException {
1606        this.publishOneLine(cms, publishHistoryId, dataset, subId, contentDefinitionName, enableHistory, versionId, publishingDate, changedResources, changedModuleData);
1607    }
1608    /**
1609     * Publishes all resources for this project.
1610     * Publishes all modified content definitions for this project.<p>
1611     *
1612     * @param cms The CmsObject
1613     * @param publishHistoryId the ID of the current publish task
1614     * @param enableHistory set to true if backup tables should be filled.
1615     * @param projectId the Project that should be published.
1616     * @param versionId the versionId to save in the backup tables.
1617     * @param publishingDate the date and time of this publishing process.
1618     * @param subId the subId to publish cd's for.
1619     * @param contentDefinitionName the name of the contentdefinition.
1620     * @param changedRessources a Vector of Resources that were changed by this publishing process.
1621     * @param changedModuleData a Vector of Resources that were changed by this publishing process.
1622     * New published data will be added to this Vector to return it.
1623     */

1624    public void publishProject(CmsObject cms, CmsUUID publishHistoryId, boolean enableHistory, int projectId, int versionId, long publishingDate, int subId, String JavaDoc contentDefinitionName, Vector JavaDoc changedRessources, Vector JavaDoc changedModuleData) throws CmsException {
1625
1626        String JavaDoc statement_key = "read_all_for_publish";
1627
1628        PreparedStatement JavaDoc stmt = null;
1629        ResultSet JavaDoc res = null;
1630        Connection JavaDoc conn = null;
1631        
1632        try {
1633            conn = m_sqlManager.getConnection();
1634            stmt = m_sqlManager.getPreparedStatement(conn, statement_key);
1635            stmt.setInt(1, subId);
1636            stmt.setInt(2, projectId);
1637            stmt.setInt(3, CmsResource.STATE_UNCHANGED);
1638            // gets all ressources that are changed int this project
1639
// and that belongs to this subId
1640
res = stmt.executeQuery();
1641            while (res.next()) {
1642                // create a new dataset to fill the values
1643
CmsMasterDataSet dataset = new CmsMasterDataSet();
1644                // fill the values to the dataset
1645
sqlFillValues(res, cms, dataset);
1646                publishOneLine(cms, publishHistoryId, dataset, subId, contentDefinitionName, enableHistory, versionId, publishingDate, changedRessources, changedModuleData);
1647            }
1648        } catch (SQLException JavaDoc exc) {
1649            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1650        } finally {
1651            m_sqlManager.closeAll(null, conn, stmt, res);
1652        }
1653    }
1654
1655    /**
1656     * Publish one content definition.<p>
1657     *
1658     * @param cms The CmsObject
1659     * @param publishHistoryId the ID of the current publish task
1660     * @param dataset the dataset to publish.
1661     * @param subId the subId to publish cd's for.
1662     * @param contentDefinitionName the name of the contentdefinition.
1663     * @param enableHistory set to true if backup tables should be filled.
1664     * @param versionId the versionId to save in the backup tables.
1665     * @param publishingDate the date and time of this publishing process.
1666     * @param changedRessources a Vector of Resources that were changed by this publishing process.
1667     * @param changedModuleData a Vector of Ressource that were changed by this publishing process.
1668     * New published data will be add to this Vector to return it.
1669     */

1670    protected void publishOneLine(CmsObject cms, CmsUUID publishHistoryId, CmsMasterDataSet dataset, int subId, String JavaDoc contentDefinitionName, boolean enableHistory, int versionId, long publishingDate, Vector JavaDoc changedRessources, Vector JavaDoc changedModuleData) throws CmsException {
1671        int state = dataset.m_state;
1672
1673        try {
1674            Class.forName(contentDefinitionName).getMethod("beforePublish", new Class JavaDoc[] { CmsObject.class, Boolean JavaDoc.class, Integer JavaDoc.class, Integer JavaDoc.class, Long JavaDoc.class, Vector JavaDoc.class, Vector JavaDoc.class, CmsMasterDataSet.class }).invoke(null, new Object JavaDoc[] { cms, new Boolean JavaDoc(enableHistory), new Integer JavaDoc(subId), new Integer JavaDoc(versionId), new Long JavaDoc(publishingDate), changedRessources, changedModuleData, dataset });
1675        } catch (Exception JavaDoc e) {
1676            CmsLog.getLog(this).warn("Error calling method beforePublish() in class " + contentDefinitionName, e);
1677        }
1678
1679        // backup the data
1680
if (enableHistory) {
1681            // store the creationdate, because it will be set to publishingdate
1682
// with this method.
1683
long backupCreationDate = dataset.m_dateCreated;
1684            publishBackupData(cms, dataset, subId, versionId, publishingDate);
1685            // restore the creationdate to the correct one
1686
dataset.m_dateCreated = backupCreationDate;
1687        }
1688
1689        // delete the online data
1690
publishDeleteData(dataset.m_masterId, subId, "online");
1691
1692        if (state == CmsResource.STATE_DELETED) {
1693            // delete the data from offline
1694
// the state was DELETED
1695
publishDeleteData(dataset.m_masterId, subId, "offline");
1696        } else {
1697            // copy the data from offline to online
1698
// the state was NEW or CHANGED
1699
publishCopyData(dataset, subId);
1700        }
1701
1702        // now update state, lockstate and projectId in offline
1703
PreparedStatement JavaDoc stmt = null;
1704        Connection JavaDoc conn = null;
1705        try {
1706            conn = m_sqlManager.getConnection();
1707            stmt = m_sqlManager.getPreparedStatement(conn, "update_state_offline");
1708            stmt.setInt(1, CmsResource.STATE_UNCHANGED);
1709            stmt.setString(2, CmsUUID.getNullUUID().toString());
1710            stmt.setString(3, dataset.m_masterId.toString());
1711            stmt.setInt(4, subId);
1712            stmt.executeUpdate();
1713        } catch (SQLException JavaDoc exc) {
1714            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1715        } finally {
1716            m_sqlManager.closeAll(null, conn, stmt, null);
1717        }
1718        
1719        // add an entry to the publish history
1720
writePublishHistory(
1721            cms.getRequestContext().currentProject(),
1722            publishHistoryId,
1723            versionId,
1724            contentDefinitionName,
1725            dataset.m_masterId,
1726            subId,
1727            state);
1728
1729        // update changedModuleData Vector
1730
changedModuleData.add(
1731            new CmsPublishedResource(
1732                CmsUUID.getNullUUID(),
1733                dataset.m_masterId,
1734                CmsDbUtil.UNKNOWN_ID,
1735                contentDefinitionName,
1736                subId,
1737                false,
1738                state,
1739                1));
1740    }
1741
1742    /**
1743     * Publish all deletions.<p>
1744     * @param masterId the id of the content definition.
1745     * @param subId the sub id of the cd.
1746     * @param table the used table.
1747     * @throws CmsException if sql or other errors occur.
1748     */

1749    protected void publishDeleteData(CmsUUID masterId, int subId, String JavaDoc table) throws CmsException {
1750        PreparedStatement JavaDoc stmt = null;
1751        Connection JavaDoc conn = null;
1752        String JavaDoc deleteChannel = "delete_all_channel_" + table;
1753        // delete channel relation
1754
try {
1755            conn = m_sqlManager.getConnection();
1756            stmt = m_sqlManager.getPreparedStatement(conn, deleteChannel);
1757            stmt.setString(1, masterId.toString());
1758            stmt.executeUpdate();
1759        } catch (SQLException JavaDoc exc) {
1760            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1761        } finally {
1762            m_sqlManager.closeAll(null, conn, stmt, null);
1763        }
1764        // delete media
1765
try {
1766            conn = null;
1767            stmt = null;
1768            String JavaDoc deleteMedia = "delete_all_media_" + table;
1769            conn = m_sqlManager.getConnection();
1770            stmt = m_sqlManager.getPreparedStatement(conn, deleteMedia);
1771            stmt.setString(1, masterId.toString());
1772            stmt.executeUpdate();
1773        } catch (SQLException JavaDoc exc) {
1774            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1775        } finally {
1776            m_sqlManager.closeAll(null, conn, stmt, null);
1777        }
1778        // delete the row
1779
try {
1780            stmt = null;
1781            conn = null;
1782            String JavaDoc delete = "delete_" + table;
1783            conn = m_sqlManager.getConnection();
1784            stmt = m_sqlManager.getPreparedStatement(conn, delete);
1785            stmt.setString(1, masterId.toString());
1786            stmt.setInt(2, subId);
1787            stmt.executeUpdate();
1788        } catch (SQLException JavaDoc exc) {
1789            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1790        } finally {
1791            m_sqlManager.closeAll(null, conn, stmt, null);
1792        }
1793    }
1794
1795    /**
1796     * Publishes a copied row of a content definition.<p>
1797     *
1798     * @param dataset the dataset.
1799     * @param subId the used sub id.
1800     * @throws CmsException if sql or other errors occur.
1801     */

1802    protected void publishCopyData(CmsMasterDataSet dataset, int subId) throws CmsException {
1803        PreparedStatement JavaDoc stmt = null;
1804        PreparedStatement JavaDoc stmt2 = null;
1805        ResultSet JavaDoc res = null;
1806        Connection JavaDoc conn = null;
1807        Connection JavaDoc conn2 = null;
1808        CmsUUID masterId = dataset.m_masterId;
1809
1810        // copy the row
1811
try {
1812            stmt = null;
1813            conn = m_sqlManager.getConnection();
1814            stmt = m_sqlManager.getPreparedStatement(conn, "insert_online");
1815            // correct the data in the dataset
1816
dataset.m_projectId = CmsProject.ONLINE_PROJECT_ID;
1817            dataset.m_lockedInProject = CmsProject.ONLINE_PROJECT_ID;
1818            dataset.m_state = CmsResource.STATE_UNCHANGED;
1819            dataset.m_lockedBy = CmsUUID.getNullUUID();
1820            sqlFillValues(stmt, subId, dataset);
1821            stmt.executeUpdate();
1822        } catch (SQLException JavaDoc exc) {
1823            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1824        } finally {
1825            m_sqlManager.closeAll(null, conn, stmt, null);
1826        }
1827        // copy media
1828
try {
1829            // read all media of master from offline
1830
stmt = null;
1831            res = null;
1832            conn = null;
1833            conn = m_sqlManager.getConnection();
1834            stmt = m_sqlManager.getPreparedStatement(conn, "read_media_offline");
1835            stmt.setString(1, masterId.toString());
1836            res = stmt.executeQuery();
1837            while (res.next()) {
1838                // create a new dataset to fill the values
1839
int i = 1;
1840                CmsMasterMedia mediaset = new CmsMasterMedia(res.getInt(i++), new CmsUUID(res.getString(i++)), res.getInt(i++), res.getInt(i++), res.getInt(i++), res.getInt(i++), res.getString(i++), res.getInt(i++), res.getString(i++), res.getString(i++), res.getString(i++), res.getBytes(i++));
1841                // insert media of master into online
1842
try {
1843                    stmt2 = null;
1844                    conn2 = null;
1845                    conn2 = m_sqlManager.getConnection();
1846                    stmt2 = m_sqlManager.getPreparedStatement(conn2, "insert_media_online");
1847                    sqlFillValues(stmt2, mediaset);
1848                    stmt2.executeUpdate();
1849                } catch (SQLException JavaDoc ex) {
1850                    throw ex;
1851                } finally {
1852                    m_sqlManager.closeAll(null, conn2, stmt2, null);
1853                }
1854            }
1855        } catch (SQLException JavaDoc exc) {
1856            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1857        } finally {
1858            m_sqlManager.closeAll(null, conn, stmt, res);
1859        }
1860
1861        // copy channel relation
1862
try {
1863            stmt = null;
1864            res = null;
1865            conn = null;
1866            conn = m_sqlManager.getConnection();
1867            // read all channel relations for master from offline
1868
stmt = m_sqlManager.getPreparedStatement(conn, "read_channel_offline");
1869            stmt.setString(1, masterId.toString());
1870            res = stmt.executeQuery();
1871            while (res.next()) {
1872                // insert all channel relations for master into online
1873
try {
1874                    stmt2 = null;
1875                    conn2 = null;
1876                    conn2 = m_sqlManager.getConnection();
1877                    stmt2 = m_sqlManager.getPreparedStatement(conn2, "insert_channel_online");
1878                    stmt2.setString(1, masterId.toString());
1879                    stmt2.setString(2, res.getString(1));
1880                    stmt2.setString(3, res.getString(2));
1881                    stmt2.executeUpdate();
1882                } catch (SQLException JavaDoc ex) {
1883                    throw ex;
1884                } finally {
1885                    m_sqlManager.closeAll(null, conn2, stmt2, null);
1886                }
1887            }
1888        } catch (SQLException JavaDoc exc) {
1889            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1890        } finally {
1891            m_sqlManager.closeAll(null, conn, stmt, res);
1892        }
1893    }
1894
1895    /**
1896     * Insert content definitions in backup table<p>
1897     * @param cms the CmsObject.
1898     * @param dataset the current data set.
1899     * @param subId the used sub id.
1900     * @param versionId the version of the backup.
1901     * @param publishDate the publishing date.
1902     * @throws CmsException if sql or other errors occur.
1903     */

1904    protected void publishBackupData(CmsObject cms, CmsMasterDataSet dataset, int subId, int versionId, long publishDate) throws CmsException {
1905        PreparedStatement JavaDoc stmt = null;
1906        PreparedStatement JavaDoc stmt2 = null;
1907        ResultSet JavaDoc res = null;
1908        Connection JavaDoc conn = null;
1909        Connection JavaDoc conn2 = null;
1910        CmsUUID masterId = dataset.m_masterId;
1911
1912        // copy the row
1913
try {
1914            stmt = null;
1915            conn = null;
1916            conn = m_sqlManager.getConnection();
1917            stmt = m_sqlManager.getPreparedStatement(conn, "insert_backup");
1918            // correct the data in the dataset
1919
dataset.m_lockedBy = CmsUUID.getNullUUID();
1920            dataset.m_dateCreated = publishDate;
1921            // get the name of the owner
1922
String JavaDoc ownerName = "";
1923            try {
1924                CmsUser owner = cms.readUser(dataset.m_userId);
1925                ownerName = owner.getName() + " " + owner.getFirstname() + " " + owner.getLastname();
1926            } catch (CmsException ex) {
1927                ownerName = "";
1928            }
1929            // get the name of the group
1930
String JavaDoc groupName = "";
1931            try {
1932                CmsGroup group = cms.readGroup(dataset.m_groupId);
1933                groupName = group.getName();
1934            } catch (CmsException ex) {
1935                groupName = "";
1936            }
1937            // get the name of the user who has modified the resource
1938
String JavaDoc userName = "";
1939            try {
1940                CmsUser user = cms.readUser(dataset.m_lastModifiedBy);
1941                userName = user.getName() + " " + user.getFirstname() + " " + user.getLastname();
1942            } catch (CmsException ex) {
1943                userName = "";
1944            }
1945            int lastId = sqlFillValues(stmt, subId, dataset);
1946            // set version
1947
stmt.setInt(lastId++, versionId);
1948            stmt.setString(lastId++, ownerName);
1949            stmt.setString(lastId++, groupName);
1950            stmt.setString(lastId++, userName);
1951            stmt.executeUpdate();
1952        } catch (SQLException JavaDoc exc) {
1953            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1954        } finally {
1955            m_sqlManager.closeAll(null, conn, stmt, null);
1956        }
1957        // copy media
1958
try {
1959            // read all media of master from offline
1960
stmt = null;
1961            res = null;
1962            conn = null;
1963            conn = m_sqlManager.getConnection();
1964            stmt = m_sqlManager.getPreparedStatement(conn, "read_media_offline");
1965            stmt.setString(1, masterId.toString());
1966            res = stmt.executeQuery();
1967            while (res.next()) {
1968                // create a new dataset to fill the values
1969
int i = 1;
1970                CmsMasterMedia mediaset = new CmsMasterMedia(res.getInt(i++), new CmsUUID(res.getString(i++)), res.getInt(i++), res.getInt(i++), res.getInt(i++), res.getInt(i++), res.getString(i++), res.getInt(i++), res.getString(i++), res.getString(i++), res.getString(i++), res.getBytes(i++));
1971                // insert media of master into backup
1972
try {
1973                    conn2 = null;
1974                    stmt2 = null;
1975                    conn2 = m_sqlManager.getConnection();
1976                    stmt2 = m_sqlManager.getPreparedStatement(conn2, "insert_media_backup");
1977                    int lastId = sqlFillValues(stmt2, mediaset);
1978                    stmt2.setInt(lastId, versionId);
1979                    stmt2.executeUpdate();
1980                } catch (SQLException JavaDoc ex) {
1981                    throw ex;
1982                } finally {
1983                    m_sqlManager.closeAll(null, conn2, stmt2, null);
1984                }
1985            }
1986        } catch (SQLException JavaDoc exc) {
1987            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, exc);
1988        } finally {
1989            m_sqlManager.closeAll(null, conn, stmt, res);
1990        }
1991    }
1992    
1993    /**
1994     * Inserts an entry in the publish history for a published COS resource.<p>
1995     *
1996     * @param project the current project
1997     * @param publishId the ID of the current publishing process
1998     * @param tagId the current backup ID
1999     * @param contentDefinitionName the package/class name of the content definition
2000     * @param masterId the content ID of the published module data
2001     * @param subId the module ID of the published module data
2002     * @param state the state of the resource *before* it was published
2003     *
2004     * @throws CmsException if something goes wrong
2005     */

2006    public void writePublishHistory(CmsProject project, CmsUUID publishId, int tagId, String JavaDoc contentDefinitionName, CmsUUID masterId, int subId, int state) throws CmsException {
2007        
2008        PreparedStatement JavaDoc stmt = null;
2009        ResultSet JavaDoc res = null;
2010        Connection JavaDoc conn = null;
2011        
2012        try {
2013            conn = m_sqlManager.getConnection(project.getId());
2014            stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_WRITE_PUBLISH_HISTORY");
2015            stmt.setInt(1, tagId);
2016            // structure id is null
2017
stmt.setString(2, CmsUUID.getNullUUID().toString());
2018            // master ID
2019
stmt.setString(3, masterId.toString());
2020            // content definition name
2021
stmt.setString(4, contentDefinitionName);
2022            // state
2023
stmt.setInt(5, state);
2024            // sub ID
2025
stmt.setInt(6, subId);
2026            stmt.setString(7, publishId.toString());
2027            stmt.setInt(8, 0);
2028            stmt.executeUpdate();
2029        } catch (SQLException JavaDoc e) {
2030            throw new CmsLegacyException(CmsLegacyException.C_SQL_ERROR, e);
2031        } finally {
2032            m_sqlManager.closeAll(null, conn, stmt, res);
2033        }
2034    }
2035
2036}
Popular Tags