KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > slide > store > impl > rdbms > StandardRDBMSAdapter


1 /*
2  * $Header: /home/cvs/jakarta-slide/src/stores/org/apache/slide/store/impl/rdbms/StandardRDBMSAdapter.java,v 1.32.2.4 2004/11/30 07:08:36 masonjm Exp $
3  * $Revision: 1.32.2.4 $
4  * $Date: 2004/11/30 07:08:36 $
5  *
6  * ====================================================================
7  *
8  * Copyright 1999-2003 The Apache Software Foundation
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  *
22  */

23
24 package org.apache.slide.store.impl.rdbms;
25
26 import org.apache.slide.common.*;
27 import org.apache.slide.content.*;
28 import org.apache.slide.lock.LockTokenNotFoundException;
29 import org.apache.slide.lock.NodeLock;
30 import org.apache.slide.security.NodePermission;
31 import org.apache.slide.structure.LinkNode;
32 import org.apache.slide.structure.ObjectAlreadyExistsException;
33 import org.apache.slide.structure.ObjectNode;
34 import org.apache.slide.structure.ObjectNotFoundException;
35 import org.apache.slide.util.logger.Logger;
36
37 import java.io.*;
38 import java.lang.reflect.Constructor JavaDoc;
39 import java.sql.Connection JavaDoc;
40 import java.sql.PreparedStatement JavaDoc;
41 import java.sql.ResultSet JavaDoc;
42 import java.sql.SQLException JavaDoc;
43 //import java.sql.Statement;
44
import java.util.*;
45 import java.util.Date JavaDoc;
46
47 /**
48  * J2EENodeStore Implementation based on the modified NewSlide Schema.
49  * This is combined store of DescriptorStore and ContentStore
50  * This combined store is necessary to make every operation behave in
51  * one transaction.
52  *
53  * @version $Revision: 1.32.2.4 $
54  */

55
56 public class StandardRDBMSAdapter extends AbstractRDBMSAdapter {
57
58     protected static final String JavaDoc LOG_CHANNEL = StandardRDBMSAdapter.class.getName();
59
60     protected boolean bcompress;
61
62     public StandardRDBMSAdapter(Service service, Logger logger) {
63         super(service, logger);
64         bcompress = false;
65     }
66
67     public void setParameters(Hashtable parameters)
68         throws ServiceParameterErrorException, ServiceParameterMissingException {
69         try {
70             bcompress = "true".equalsIgnoreCase((String JavaDoc) parameters.get("compress"));
71             if (bcompress)
72                 getLogger().log("Switching on content compression", LOG_CHANNEL, Logger.INFO);
73             super.setParameters(parameters);
74         } catch (Exception JavaDoc e) {
75             getLogger().log(e.toString(), LOG_CHANNEL, Logger.ERROR);
76         }
77     }
78
79     // Object
80

81     public void createObject(Connection JavaDoc connection, Uri uri, ObjectNode object)
82         throws ObjectAlreadyExistsException, ServiceAccessException {
83         if (!storeObject(connection, uri, object, true))
84             throw new ObjectAlreadyExistsException(uri.toString());
85     }
86
87     public void storeObject(Connection JavaDoc connection, Uri uri, ObjectNode object)
88         throws ObjectNotFoundException, ServiceAccessException {
89         if (!storeObject(connection, uri, object, false))
90             throw new ObjectNotFoundException(uri.toString());
91     }
92
93     protected boolean storeObject(Connection JavaDoc connection, Uri uri, ObjectNode object, boolean create)
94         throws ServiceAccessException {
95         String JavaDoc className = object.getClass().getName();
96         long uriid;
97         try {
98             PreparedStatement JavaDoc statement = null;
99             ResultSet JavaDoc res = null;
100             try {
101                 uriid = assureUriId(connection, uri.toString());
102                 statement =
103                     connection.prepareStatement(
104                         "select 1 from OBJECT o, URI u where o.URI_ID=u.URI_ID and u.URI_STRING=?");
105                 statement.setString(1, uri.toString());
106                 res = statement.executeQuery();
107                 if (res.next()) {
108                     if (create)
109                         return false;
110                 } else {
111                     if (!create)
112                         return false;
113                 }
114             } finally {
115                 close(statement, res);
116             }
117
118             if (create) {
119                 // create object in database
120
try {
121                     statement = connection.prepareStatement("insert into OBJECT (URI_ID,CLASS_NAME) values (?,?)");
122                     statement.setLong(1, uriid);
123                     statement.setString(2, className);
124                     statement.executeUpdate();
125                 } finally {
126                     close(statement);
127                 }
128             }
129
130             // update binding...
131

132             try {
133                 clearBinding(connection, uri);
134             } catch (ObjectNotFoundException e1) {
135                 // clear only if it existed
136
}
137             
138             Enumeration bindings = object.enumerateBindings();
139             while (bindings.hasMoreElements()) {
140                 ObjectNode.Binding binding = (ObjectNode.Binding) bindings.nextElement();
141                 try {
142                     statement =
143                         connection.prepareStatement(
144                             "insert into BINDING (URI_ID, NAME, CHILD_UURI_ID) select ?, ?, URI_ID from URI where URI_STRING = ?");
145                     statement.setLong(1, uriid);
146                     statement.setString(2, binding.getName());
147                     statement.setString(3, binding.getUuri());
148                     statement.executeUpdate();
149                 } finally {
150                     close(statement);
151                 }
152             }
153
154             Enumeration parentBindings = object.enumerateParentBindings();
155             while (parentBindings.hasMoreElements()) {
156                 ObjectNode.ParentBinding parentBinding = (ObjectNode.ParentBinding) parentBindings.nextElement();
157                 try {
158                     statement =
159                         connection.prepareStatement(
160                             "insert into PARENT_BINDING (URI_ID, NAME, PARENT_UURI_ID) select ?, ?, URI_ID from URI where URI_STRING = ?");
161                     statement.setLong(1, uriid);
162                     statement.setString(2, parentBinding.getName());
163                     statement.setString(3, parentBinding.getUuri());
164                     statement.executeUpdate();
165                 } finally {
166                     close(statement);
167                 }
168             }
169
170             if (object instanceof LinkNode) {
171                 // update link target
172
try {
173                     statement = connection.prepareStatement("delete from LINKS where URI_ID = ?");
174                     statement.setLong(1, uriid);
175                     statement.executeUpdate();
176                 } finally {
177                     close(statement);
178                 }
179                 try {
180                     statement =
181                         connection.prepareStatement(
182                             "insert into LINKS (URI_ID, LINK_TO_ID) select ?, u.URI_ID from URI u where u.URI_STRING = ?");
183                     statement.setLong(1, uriid);
184                     statement.setString(2, ((LinkNode) object).getLinkedUri());
185                     statement.executeUpdate();
186                 } finally {
187                     close(statement);
188                 }
189             }
190         } catch (SQLException JavaDoc e) {
191             throw createException(e, uri.toString());
192         }
193         return true;
194     }
195
196     public void removeObject(Connection JavaDoc connection, Uri uri, ObjectNode object)
197         throws ServiceAccessException, ObjectNotFoundException {
198         PreparedStatement JavaDoc statement = null;
199         try {
200
201             clearBinding(connection, uri);
202
203             // delete links
204
try {
205                 statement =
206                     connection.prepareStatement(
207                         "delete LINKS from LINKS l, URI u where l.URI_ID = u.URI_ID and u.URI_STRING = ?");
208                 statement.setString(1, uri.toString());
209                 statement.executeUpdate();
210             } finally {
211                 close(statement);
212             }
213             // delete version history
214
// FIXME: Is this true??? Should the version history be removed if the object is removed???
215
try {
216                 statement =
217                     connection.prepareStatement(
218                         "delete VERSION_HISTORY from VERSION_HISTORY vh, URI u where vh.URI_ID = u.URI_ID and u.URI_STRING = ?");
219                 statement.setString(1, uri.toString());
220                 statement.executeUpdate();
221             } finally {
222                 close(statement);
223             }
224             // delete version
225
try {
226                 statement =
227                     connection.prepareStatement(
228                         "delete VERSION from VERSION v, URI u where v.URI_ID = u.URI_ID and u.URI_STRING = ?");
229                 statement.setString(1, uri.toString());
230                 statement.executeUpdate();
231             } finally {
232                 close(statement);
233             }
234             // delete the object itself
235
try {
236                 statement =
237                     connection.prepareStatement(
238                         "delete OBJECT from OBJECT o, URI u where o.URI_ID = u.URI_ID and u.URI_STRING = ?");
239                 statement.setString(1, uri.toString());
240                 statement.executeUpdate();
241             } finally {
242                 close(statement);
243             }
244             // finally delete the uri
245
try {
246                 statement = connection.prepareStatement("delete from URI where URI_STRING = ?");
247                 statement.setString(1, uri.toString());
248                 statement.executeUpdate();
249             } finally {
250                 close(statement);
251             }
252         } catch (SQLException JavaDoc e) {
253             throw createException(e, uri.toString());
254
255         }
256     }
257
258     public ObjectNode retrieveObject(Connection JavaDoc connection, Uri uri)
259         throws ServiceAccessException, ObjectNotFoundException {
260         ObjectNode result = null;
261         try {
262             PreparedStatement JavaDoc statement = null;
263             ResultSet JavaDoc res = null;
264             String JavaDoc className;
265             Vector children = new Vector();
266             Vector parents = new Vector();
267             Vector links = new Vector();
268             try {
269                 statement =
270                     connection.prepareStatement(
271                         "select o.CLASS_NAME from OBJECT o, URI u where o.URI_ID = u.URI_ID and u.URI_STRING = ?");
272                 statement.setString(1, uri.toString());
273                 res = statement.executeQuery();
274                 if (res.next()) {
275                     className = res.getString(1);
276                 } else {
277                     throw new ObjectNotFoundException(uri);
278                 }
279             } finally {
280                 close(statement, res);
281             }
282
283             try {
284                 statement =
285                     connection.prepareStatement(
286                         "SELECT c.NAME, cu.URI_STRING FROM URI u, URI cu, BINDING c WHERE cu.URI_ID = c.CHILD_UURI_ID AND c.URI_ID = u.URI_ID and u.URI_STRING = ?");
287                 statement.setString(1, uri.toString());
288                 res = statement.executeQuery();
289                 while (res.next()) {
290                     children.addElement(new ObjectNode.Binding(res.getString(1), res.getString(2)));
291                 }
292             } finally {
293                 close(statement, res);
294             }
295
296             try {
297                 statement =
298                     connection.prepareStatement(
299                         "SELECT c.NAME, cu.URI_STRING FROM URI u, URI cu, PARENT_BINDING c WHERE cu.URI_ID = c.PARENT_UURI_ID AND c.URI_ID = u.URI_ID and u.URI_STRING = ?");
300                 statement.setString(1, uri.toString());
301                 res = statement.executeQuery();
302                 while (res.next()) {
303                     parents.addElement(new ObjectNode.ParentBinding(res.getString(1), res.getString(2)));
304                 }
305             } finally {
306                 close(statement, res);
307             }
308
309             try {
310                 statement =
311                     connection.prepareStatement(
312                         "SELECT lu.URI_STRING FROM URI u, URI lu, LINKS l WHERE lu.URI_ID = l.URI_ID AND l.LINK_TO_ID = u.URI_ID and u.URI_STRING = ?");
313                 statement.setString(1, uri.toString());
314                 res = statement.executeQuery();
315                 while (res.next()) {
316                     links.addElement(res.getString(1));
317                 }
318             } finally {
319                 close(statement, res);
320             }
321             if (className.equals(LinkNode.class.getName())) {
322                 try {
323                     statement =
324                         connection.prepareStatement(
325                             "SELECT lu.URI_STRING FROM URI u, URI lu, LINKS l WHERE lu.URI_ID = l.LINK_TO_ID AND l.URI_ID = u.URI_ID and u.URI_STRING = ?");
326                     statement.setString(1, uri.toString());
327                     res = statement.executeQuery();
328                     if (res.next()) {
329                         String JavaDoc linkTarget = res.getString(1);
330                         result = new LinkNode(uri.toString(), children, links, linkTarget);
331                     } else {
332                         result = new LinkNode(uri.toString(), children, links);
333                     }
334                 } finally {
335                     close(statement, res);
336                 }
337             } else {
338                 try {
339                     Class JavaDoc objclass = Class.forName(className);
340                     Class JavaDoc argClasses[] = { String JavaDoc.class, Vector.class, Vector.class, Vector.class };
341                     Object JavaDoc arguments[] = { uri.toString(), children, parents, links };
342                     Constructor JavaDoc constructor = objclass.getConstructor(argClasses);
343                     result = (ObjectNode) constructor.newInstance(arguments);
344                     result.setUri(result.getUuri());
345                 } catch (Exception JavaDoc e) {
346                     throw new ServiceAccessException(service, e);
347                 }
348             }
349         } catch (SQLException JavaDoc e) {
350             throw createException(e, uri.toString());
351         }
352         return result;
353     }
354
355     // Locks
356
public Enumeration enumerateLocks(Connection JavaDoc connection, Uri uri) throws ServiceAccessException {
357
358         Vector lockVector = new Vector();
359         PreparedStatement JavaDoc statement = null;
360         ResultSet JavaDoc res = null;
361         try {
362             statement =
363                 connection.prepareStatement(
364                     "select l.EXPIRATION_DATE, l.IS_INHERITABLE, l.IS_EXCLUSIVE, u2.URI_STRING as LCK, u3.URI_STRING as SUBJECT, u4.URI_STRING as TYPE, l.OWNER from LOCKS l, URI u, URI u2, URI u3, URI u4 where l.OBJECT_ID=u.URI_ID and u.URI_STRING=? and l.LOCK_ID=u2.URI_ID and l.SUBJECT_ID=u3.URI_ID and l.TYPE_ID = u4.URI_ID");
365             statement.setString(1, uri.toString());
366             res = statement.executeQuery();
367
368             while (res.next()) {
369                 Date JavaDoc expirationDate = null;
370                 try {
371                     Long JavaDoc timeValue = new Long JavaDoc(res.getLong("EXPIRATION_DATE"));
372                     expirationDate = new Date JavaDoc(timeValue.longValue());
373                 } catch (NumberFormatException JavaDoc e) {
374                     getLogger().log(e, LOG_CHANNEL, Logger.WARNING);
375                     expirationDate = new Date JavaDoc();
376                 }
377                 NodeLock lock =
378                     new NodeLock(
379                         res.getString("LCK"),
380                         uri.toString(),
381                         res.getString("SUBJECT"),
382                         res.getString("TYPE"),
383                         expirationDate,
384                         res.getInt("IS_INHERITABLE") == 1,
385                         res.getInt("IS_EXCLUSIVE") == 1,
386             res.getString("OWNER"));
387
388                 lockVector.addElement(lock);
389             }
390         } catch (SQLException JavaDoc e) {
391             throw createException(e, uri.toString());
392         } finally {
393             close(statement, res);
394         }
395         return lockVector.elements();
396     }
397
398     public void killLock(Connection JavaDoc connection, Uri uri, NodeLock lock)
399         throws ServiceAccessException, LockTokenNotFoundException {
400         removeLock(connection, uri, lock);
401     }
402
403     public void putLock(Connection JavaDoc connection, Uri uri, NodeLock lock) throws ServiceAccessException {
404         PreparedStatement JavaDoc statement = null;
405         try {
406             int inheritable = lock.isInheritable() ? 1 : 0;
407             int exclusive = lock.isExclusive() ? 1 : 0;
408             long lockid = assureUriId(connection, lock.getLockId());
409             statement =
410                 connection.prepareStatement(
411                     "insert into LOCKS (LOCK_ID,OBJECT_ID,SUBJECT_ID,TYPE_ID,EXPIRATION_DATE,IS_INHERITABLE,IS_EXCLUSIVE,OWNER) select ?, object.URI_ID, subject.URI_ID, type.URI_ID, ?, ?, ?, ? from URI object, URI subject, URI type WHERE object.URI_STRING=? and subject.URI_STRING=? and type.URI_STRING=?");
412             statement.setLong(1, lockid);
413             statement.setLong(2, lock.getExpirationDate().getTime());
414             statement.setInt(3, inheritable);
415             statement.setInt(4, exclusive);
416             statement.setString(5, lock.getOwnerInfo());
417             statement.setString(6, lock.getObjectUri());
418             statement.setString(7, lock.getSubjectUri());
419             statement.setString(8, lock.getTypeUri());
420
421             statement.execute();
422         } catch (SQLException JavaDoc e) {
423             throw createException(e, uri.toString());
424         } finally {
425             close(statement);
426         }
427     }
428
429     public void renewLock(Connection JavaDoc connection, Uri uri, NodeLock lock)
430         throws ServiceAccessException, LockTokenNotFoundException {
431         try {
432             PreparedStatement JavaDoc statement = null;
433             ResultSet JavaDoc rslt = null;
434             try {
435                 statement =
436                     connection.prepareStatement(
437                         "select 1 from LOCKS l, URI u where l.LOCK_ID = u.URI_ID and u.URI_STRING = ?");
438                 statement.setString(1, lock.getLockId());
439                 rslt = statement.executeQuery();
440                 if (rslt.next()) {
441                     removeLock(connection,uri,lock);
442                     putLock(connection, uri, lock);
443                 } else {
444                     throw new LockTokenNotFoundException(lock);
445                 }
446             } finally {
447                 close(statement, rslt);
448             }
449         } catch (SQLException JavaDoc e) {
450             throw createException(e, uri.toString());
451         }
452     }
453
454     public void removeLock(Connection JavaDoc connection, Uri uri, NodeLock lock)
455         throws ServiceAccessException, LockTokenNotFoundException {
456         PreparedStatement JavaDoc statement = null;
457         try {
458             try {
459                 statement =
460                     connection.prepareStatement(
461                         "delete LOCKS from LOCKS, URI u where LOCK_ID = u.URI_ID and u.URI_STRING=?");
462                 statement.setString(1, lock.getLockId());
463                 statement.executeUpdate();
464             } finally {
465                 close(statement);
466             }
467             try {
468                 statement =
469                     connection.prepareStatement(
470                         "delete URI from URI, LOCKS l where URI_STRING=?");
471                 statement.setString(1, lock.getLockId());
472                 statement.executeUpdate();
473             } finally {
474                 close(statement);
475             }
476         } catch (SQLException JavaDoc e) {
477             throw createException(e, uri.toString());
478         }
479     }
480
481     // Permissions
482

483     public Enumeration enumeratePermissions(Connection JavaDoc connection, Uri uri) throws ServiceAccessException {
484         Vector permissions = new Vector();
485         PreparedStatement JavaDoc statement = null;
486         ResultSet JavaDoc res = null;
487         try {
488             statement =
489                 connection.prepareStatement(
490                     "select ou.URI_STRING, su.URI_STRING, au.URI_STRING, p.VERSION_NO, p.IS_INHERITABLE, p.IS_NEGATIVE from PERMISSIONS p, URI ou, URI su, URI au where p.OBJECT_ID = ou.URI_ID and ou.URI_STRING = ? and p.SUBJECT_ID = su.URI_ID and p.ACTION_ID = au.URI_ID order by SUCCESSION");
491             statement.setString(1, uri.toString());
492             res = statement.executeQuery();
493             while (res.next()) {
494                 String JavaDoc object = res.getString(1);
495                 String JavaDoc subject = res.getString(2);
496                 String JavaDoc action = res.getString(3);
497                 String JavaDoc revision = res.getString(4);
498                 if ("NULL".equals(revision)) {
499                     revision = null;
500                 }
501                 boolean inheritable = (res.getInt(5) == 1);
502                 boolean negative = (res.getInt(6) == 1);
503                 NodePermission permission =
504                     new NodePermission(object, revision, subject, action, inheritable, negative);
505                 permissions.add(permission);
506             }
507         } catch (SQLException JavaDoc e) {
508             throw createException(e, uri.toString());
509         } finally {
510             close(statement, res);
511         }
512         return permissions.elements();
513     }
514
515     public void grantPermission(Connection JavaDoc connection, Uri uri, NodePermission permission)
516         throws ServiceAccessException {
517         PreparedStatement JavaDoc statement = null;
518         ResultSet JavaDoc res = null;
519         int succession = 0;
520
521         try {
522             // FIXME: This might be useless if insert inserts nothing if insert...select works a i expect
523
// FIXME: What happens, if only revision number, inheritable or negative changes?
524
// FIXME
525
// revokePermission(connection, uri, permission);
526

527             try {
528                 statement =
529                     connection.prepareStatement(
530                         "select max(p.SUCCESSION) from URI ou, PERMISSIONS p where p.OBJECT_ID = ou.URI_ID and ou.URI_STRING = ?");
531                 statement.setString(1, permission.getObjectUri());
532                 res = statement.executeQuery();
533                 res.next();
534                 succession = res.getInt(1) + 1;
535             } finally {
536                 close(statement, res);
537             }
538
539             assureUriId(connection,permission.getSubjectUri());
540             assureUriId(connection,permission.getActionUri());
541
542             try {
543                 
544                 int inheritable = permission.isInheritable() ? 1 : 0;
545                 int negative = permission.isNegative() ? 1 : 0;
546
547                 statement =
548                     connection.prepareStatement(
549                         "insert into PERMISSIONS (OBJECT_ID,SUBJECT_ID,ACTION_ID,VERSION_NO, IS_INHERITABLE,IS_NEGATIVE,SUCCESSION) select ou.URI_ID, su.URI_ID, au.URI_ID, ?, ?, ?, ? from URI ou, URI su, URI au where ou.URI_STRING = ? and su.URI_STRING = ? and au.URI_STRING = ?");
550                 statement.setString(1, getRevisionNumberAsString(permission.getRevisionNumber()));
551                 statement.setInt(2, inheritable);
552                 statement.setInt(3, negative);
553                 statement.setInt(4, succession);
554                 statement.setString(5, permission.getObjectUri());
555                 statement.setString(6, permission.getSubjectUri());
556                 statement.setString(7, permission.getActionUri());
557                 if (statement.executeUpdate() != 1) {
558                     String JavaDoc msg = "Failed to insert permission ("
559                     + permission.getObjectUri()
560                     + "," + permission.getSubjectUri()
561                     + "," + permission.getActionUri()
562                     + ")";
563                     getLogger().log(msg,LOG_CHANNEL,Logger.ERROR);
564                 }
565             } finally {
566                 close(statement);
567             }
568         } catch (SQLException JavaDoc e) {
569             throw createException(e, uri.toString());
570         }
571     }
572
573     public void revokePermission(Connection JavaDoc connection, Uri uri, NodePermission permission)
574         throws ServiceAccessException {
575         if (permission == null) return;
576         PreparedStatement JavaDoc statement = null;
577         try {
578             NodeRevisionNumber revisionNumber = permission.getRevisionNumber();
579             statement =
580                 connection.prepareStatement(
581                     "delete PERMISSIONS from PERMISSIONS, URI ou, URI su, URI au where OBJECT_ID = ou.URI_ID and ou.URI_STRING = ? and SUBJECT_ID = su.URI_ID and su.URI_STRING = ? and ACTION_ID = au.URI_ID and au.URI_STRING = ? and VERSION_NO" + ((revisionNumber == null) ? " IS NULL " : " = '" + revisionNumber.toString() + "'"));
582             statement.setString(1, permission.getObjectUri());
583             statement.setString(2, permission.getSubjectUri());
584             statement.setString(3, permission.getActionUri());
585             statement.executeUpdate();
586         } catch (SQLException JavaDoc e) {
587             throw createException(e, uri.toString());
588         } finally {
589             close(statement);
590         }
591     }
592
593     public void revokePermissions(Connection JavaDoc connection, Uri uri) throws ServiceAccessException {
594         PreparedStatement JavaDoc statement = null;
595         try {
596             statement =
597                 connection.prepareStatement(
598                     "delete PERMISSIONS from PERMISSIONS, URI u where OBJECT_ID = u.URI_ID and u.URI_STRING = ?");
599             statement.setString(1, uri.toString());
600             statement.executeUpdate();
601         } catch (SQLException JavaDoc e) {
602             throw createException(e, uri.toString());
603         } finally {
604             close(statement);
605         }
606     }
607
608     public void createRevisionDescriptor(Connection JavaDoc connection, Uri uri, NodeRevisionDescriptor revisionDescriptor)
609         throws ServiceAccessException {
610
611         PreparedStatement JavaDoc statement = null;
612         try {
613
614             assureVersionInfo(connection, uri, revisionDescriptor);
615
616             for (Enumeration labels = revisionDescriptor.enumerateLabels(); labels.hasMoreElements();) {
617                 long labelId = assureLabelId(connection, (String JavaDoc) labels.nextElement());
618                 try {
619                     statement =
620                         connection.prepareStatement(
621                             "insert into VERSION_LABELS (VERSION_ID, LABEL_ID) select VERSION_ID, ? from VERSION_HISTORY vh, URI u where vh.URI_ID = u.URI_ID and u.URI_STRING = ? and vh.REVISION_NO = ?");
622                     statement.setLong(1, labelId);
623                     statement.setString(2, uri.toString());
624                     statement.setString(3, revisionDescriptor.getRevisionNumber().toString());
625                     statement.executeUpdate();
626                 } finally {
627                     close(statement);
628                 }
629             }
630             for (Enumeration properties = revisionDescriptor.enumerateProperties(); properties.hasMoreElements();) {
631                 try {
632                     NodeProperty property = (NodeProperty) properties.nextElement();
633                     statement =
634                         connection.prepareStatement(
635                             "insert into PROPERTIES (VERSION_ID,PROPERTY_NAMESPACE,PROPERTY_NAME,PROPERTY_VALUE,PROPERTY_TYPE,IS_PROTECTED) select vh.VERSION_ID, ?, ?, ?, ?, ? from VERSION_HISTORY vh, URI u where vh.URI_ID = u.URI_ID and u.URI_STRING = ? and vh.REVISION_NO = ?");
636                     int protectedProperty = property.isProtected() ? 1 : 0;
637                     statement.setString(1, property.getNamespace());
638                     statement.setString(2, property.getName());
639                     statement.setString(3, property.getValue().toString());
640                     statement.setString(4, property.getType());
641                     statement.setInt(5, protectedProperty);
642                     statement.setString(6, uri.toString());
643                     statement.setString(7, revisionDescriptor.getRevisionNumber().toString());
644                     statement.executeUpdate();
645                 } finally {
646                     close(statement);
647                 }
648             }
649         } catch (SQLException JavaDoc e) {
650             throw createException(e, uri.toString());
651         }
652     }
653
654     public void removeRevisionContent(Connection JavaDoc connection, Uri uri, NodeRevisionDescriptor revisionDescriptor)
655         throws ServiceAccessException {
656         try {
657             PreparedStatement JavaDoc statement = null;
658             try {
659                 statement =
660                     connection.prepareStatement(
661                         "delete VERSION_CONTENT from VERSION_CONTENT vc, VERSION_HISTORY vh, URI u where vc.VERSION_ID = vh.VERSION_ID and vh.REVISION_NO = ? and vh.URI_ID=u.URI_ID AND u.URI_STRING=?");
662                 statement.setString(1, revisionDescriptor.getRevisionNumber().toString());
663                 statement.setString(2, uri.toString());
664                 statement.executeUpdate();
665             } finally {
666                 close(statement);
667             }
668         } catch (SQLException JavaDoc e) {
669             throw createException(e, uri.toString());
670         }
671     }
672
673     public void removeRevisionDescriptor(Connection JavaDoc connection, Uri uri, NodeRevisionNumber revisionNumber)
674         throws ServiceAccessException {
675         PreparedStatement JavaDoc statement = null;
676         try {
677             try {
678                 statement =
679                     connection.prepareStatement(
680                         "delete VERSION_LABELS from VERSION_LABELS vl, VERSION_HISTORY vh, URI u where vl.VERSION_ID = vh.VERSION_ID and vh.REVISION_NO = ? and vh.URI_ID = u.URI_ID AND u.URI_STRING = ?");
681                 statement.setString(1, revisionNumber.toString());
682                 statement.setString(2, uri.toString());
683                 statement.executeUpdate();
684             } finally {
685                 close(statement);
686             }
687             try {
688                 statement =
689                     connection.prepareStatement(
690                         "delete PROPERTIES from PROPERTIES p, VERSION_HISTORY vh, URI u where p.VERSION_ID = vh.VERSION_ID and vh.REVISION_NO = ? and vh.URI_ID = u.URI_ID AND u.URI_STRING = ?");
691                 statement.setString(1, revisionNumber.toString());
692                 statement.setString(2, uri.toString());
693                 statement.executeUpdate();
694             } finally {
695                 close(statement);
696             }
697         } catch (SQLException JavaDoc e) {
698             throw createException(e, uri.toString());
699         }
700     }
701
702     public void removeRevisionDescriptors(Connection JavaDoc connection, Uri uri) throws ServiceAccessException {
703         PreparedStatement JavaDoc statement = null;
704         try {
705             statement =
706                 connection.prepareStatement(
707                     "delete VERSION_PREDS from VERSION_PREDS vp, VERSION_HISTORY vh, URI u where vp.VERSION_ID = vh.VERSION_ID and vh.URI_ID = u.URI_ID and u.URI_STRING = ?");
708             statement.setString(1, uri.toString());
709             statement.executeUpdate();
710         } catch (SQLException JavaDoc e) {
711             throw createException(e, uri.toString());
712         } finally {
713             close(statement);
714         }
715     }
716
717     public NodeRevisionContent retrieveRevisionContent(
718         Connection JavaDoc connection,
719         Uri uri,
720         NodeRevisionDescriptor revisionDescriptor,
721         boolean temporaryConnection)
722         throws ServiceAccessException, RevisionNotFoundException {
723         NodeRevisionContent result = null;
724         try {
725             PreparedStatement JavaDoc statement = null;
726             ResultSet JavaDoc res = null;
727             try {
728                 statement =
729                     connection.prepareStatement(
730                         "select vc.CONTENT from VERSION_CONTENT vc, VERSION_HISTORY vh, URI u where vc.VERSION_ID = vh.VERSION_ID and vh.URI_ID = u.URI_ID and u.URI_STRING = ? and vh.REVISION_NO = ?");
731                 statement.setString(1, uri.toString());
732                 statement.setString(2, revisionDescriptor.getRevisionNumber().toString());
733                 res = statement.executeQuery();
734                 if (!res.next()) {
735                     throw new RevisionNotFoundException(uri.toString(), revisionDescriptor.getRevisionNumber());
736                 }
737                 InputStream is = res.getBinaryStream("CONTENT");
738                 if (is == null) {
739                     throw new RevisionNotFoundException(uri.toString(), revisionDescriptor.getRevisionNumber());
740                 }
741                 result = new NodeRevisionContent();
742                 if (bcompress) {
743                     getLogger().log("DeCompressing the data", LOG_CHANNEL, Logger.DEBUG);
744                     StoreContentZip ziputil = new StoreContentZip();
745                     ziputil.UnZip(is);
746                     revisionDescriptor.setContentLength(ziputil.getContentLength());
747                     is = ziputil.getInputStream();
748                     result.setContent(is);
749                 } else {
750                     if (temporaryConnection) {
751                         result.setContent(new JDBCAwareInputStream(is, statement, res, connection));
752                     } else {
753                         result.setContent(new JDBCAwareInputStream(is, statement, res, null));
754                     }
755                 }
756             } finally {
757                 try {
758                     close(statement, res);
759                 } finally {
760                     // do not close when not compressed, as stream needs to be read
761
// before
762
if (bcompress) {
763                         if (temporaryConnection) {
764                             // XXX is needed, as calling store does not know if
765
// connection should be closed now
766
try {
767                                 connection.commit();
768                             } finally {
769                                 connection.close();
770                             }
771                         }
772                     }
773                 }
774             }
775         } catch (SQLException JavaDoc e) {
776             throw createException(e, uri.toString());
777         } catch (RevisionNotFoundException e) {
778             // This is not that bad, but only means, no content available. Do not warn, as this happens frequently with users / actions
779
/*
780             getLogger().log(
781                 "RevisionNotFoundException encountered for " + uri.toString() + " revision " + revisionDescriptor.getRevisionNumber(),
782                 LOG_CHANNEL,
783                 4);
784             */

785             throw e;
786         } catch (Exception JavaDoc e) {
787             getLogger().log(e, LOG_CHANNEL, Logger.ERROR);
788             throw new ServiceAccessException(service, e);
789         }
790         return result;
791     }
792
793     public NodeRevisionDescriptor retrieveRevisionDescriptor(
794         Connection JavaDoc connection,
795         Uri uri,
796         NodeRevisionNumber revisionNumber)
797         throws ServiceAccessException, RevisionDescriptorNotFoundException {
798         NodeRevisionDescriptor revisionDescriptor = null;
799         if (revisionNumber == null)
800             throw new RevisionDescriptorNotFoundException(uri.toString());
801         try {
802             PreparedStatement JavaDoc statement = null;
803             ResultSet JavaDoc res = null;
804
805             String JavaDoc branch = null;
806             Vector labels = new Vector();
807             Hashtable properties = new Hashtable();
808             long versionId = 0;
809             try {
810                 statement =
811                     connection.prepareStatement(
812                         "select vh.VERSION_ID, b.BRANCH_STRING from VERSION_HISTORY vh, BRANCH b, URI u where vh.URI_ID = u.URI_ID and u.URI_STRING = ? and b.BRANCH_ID = vh.BRANCH_ID and vh.REVISION_NO = ?");
813                 statement.setString(1, uri.toString());
814                 statement.setString(2, revisionNumber.toString());
815                 res = statement.executeQuery();
816                 if (res.next()) {
817                     versionId = res.getLong(1);
818                     branch = res.getString(2);
819                 } else {
820                     throw new RevisionDescriptorNotFoundException(uri.toString());
821                 }
822             } finally {
823                 close(statement, res);
824             }
825             try {
826                 statement =
827                     connection.prepareStatement(
828                         "select l.LABEL_STRING from VERSION_LABELS vl, LABEL l where vl.VERSION_ID = ? and l.LABEL_ID = vl.LABEL_ID");
829                 statement.setLong(1, versionId);
830                 res = statement.executeQuery();
831                 while (res.next()) {
832                     labels.addElement(res.getString(1));
833                 }
834             } finally {
835                 close(statement, res);
836             }
837             try {
838                 statement =
839                     connection.prepareStatement(
840                         "select PROPERTY_NAME, PROPERTY_NAMESPACE, PROPERTY_VALUE, PROPERTY_TYPE, IS_PROTECTED from PROPERTIES where VERSION_ID = ?");
841                 statement.setLong(1, versionId);
842                 res = statement.executeQuery();
843                 while (res.next()) {
844                     String JavaDoc propertyName = res.getString(1);
845                     String JavaDoc propertyNamespace = res.getString(2);
846                     NodeProperty property =
847                         new NodeProperty(
848                             propertyName,
849                             res.getString(3),
850                             propertyNamespace,
851                             res.getString(4),
852                             res.getInt(5) == 1);
853                     properties.put(propertyNamespace + propertyName, property);
854                 }
855             } finally {
856                 close(statement, res);
857             }
858             revisionDescriptor = new NodeRevisionDescriptor(revisionNumber, branch, labels, properties);
859         } catch (SQLException JavaDoc e) {
860             throw createException(e, uri.toString());
861         }
862         return revisionDescriptor;
863     }
864
865     public NodeRevisionDescriptors retrieveRevisionDescriptors(Connection JavaDoc connection, Uri uri)
866         throws ServiceAccessException, RevisionDescriptorNotFoundException {
867
868         NodeRevisionDescriptors revisionDescriptors = null;
869         PreparedStatement JavaDoc statement = null;
870         ResultSet JavaDoc res = null;
871         try {
872             NodeRevisionNumber initialRevision = new NodeRevisionNumber();
873             // FIXME: Some code might be lost: workingRevisions is not filled with values
874
Hashtable workingRevisions = new Hashtable();
875             Hashtable latestRevisionNumbers = new Hashtable();
876             Hashtable branches = new Hashtable();
877             Vector allRevisions = new Vector();
878             
879             boolean isVersioned = false;
880             // check if versioned
881
try {
882                 statement =
883                     connection.prepareStatement(
884                         "select IS_VERSIONED from VERSION v, URI u where v.URI_ID = u.URI_ID and u.URI_STRING = ?");
885                 statement.setString(1, uri.toString());
886                 res = statement.executeQuery();
887                 if (res.next()) {
888                     isVersioned = (res.getInt("IS_VERSIONED") == 1);
889                 } else {
890                     throw new RevisionDescriptorNotFoundException(uri.toString());
891                 }
892             } finally {
893                 close(statement, res);
894             }
895             // retrieve revision numbers
896
try {
897                 statement =
898                     connection
899                         .prepareStatement(
900                             "select vh.REVISION_NO, b.BRANCH_STRING from VERSION_HISTORY vh, BRANCH b, URI u where vh.BRANCH_ID = b.BRANCH_ID and vh.URI_ID = u.URI_ID and u.URI_STRING = ? order by "
901                                 + convertRevisionNumberToComparable("vh.REVISION_NO"));
902                 statement.setString(1, uri.toString());
903                 res = statement.executeQuery();
904                 while (res.next()) {
905                     NodeRevisionNumber revisionNumber = new NodeRevisionNumber(res.getString(1));
906                     allRevisions.add(revisionNumber); // will be used to get revisions successor
907
latestRevisionNumbers.put(res.getString(2), revisionNumber); // store the lastest revision / branch
908
}
909             } finally {
910                 close(statement, res);
911             }
912             
913             for (Enumeration e = allRevisions.elements(); e.hasMoreElements();) {
914                 NodeRevisionNumber revisionNumber = (NodeRevisionNumber) e.nextElement();
915                 // get successors
916
try {
917                     statement =
918                         connection.prepareStatement(
919                             "select distinct pvh.REVISION_NO from VERSION_HISTORY vh, VERSION_HISTORY pvh, VERSION_PREDS vp, URI u where pvh.VERSION_ID = vp.VERSION_ID and vp.VERSION_ID = vh.VERSION_ID and vh.URI_ID = u.URI_ID and u.URI_STRING = ? and vh.REVISION_NO = ?");
920                     statement.setString(1, uri.toString());
921                     statement.setString(2, revisionNumber.toString());
922                     res = statement.executeQuery();
923                     Vector predecessors = new Vector();
924                     while (res.next()) {
925                         predecessors.add(new NodeRevisionNumber(res.getString(1)));
926                     }
927                     // XXX it is important to call ctor with String, otherwise it does an increment in minor number :(
928
branches.put(new NodeRevisionNumber(revisionNumber.toString()), predecessors);
929                 } finally {
930                     close(statement, res);
931                 }
932             }
933             revisionDescriptors =
934                 new NodeRevisionDescriptors(
935                     uri.toString(),
936                     initialRevision,
937                     workingRevisions,
938                     latestRevisionNumbers,
939                     branches,
940                     isVersioned);
941         } catch (SQLException JavaDoc e) {
942             throw createException(e, uri.toString());
943         }
944         return revisionDescriptors;
945     }
946
947     public void createRevisionDescriptors(Connection JavaDoc connection, Uri uri, NodeRevisionDescriptors revisionDescriptors)
948         throws ServiceAccessException {
949
950         PreparedStatement JavaDoc statement = null;
951         ResultSet JavaDoc res = null;
952         try {
953             int isVersioned = 0;
954             if (revisionDescriptors.isVersioned())
955                 isVersioned = 1;
956             boolean revisionExists;
957             try {
958                 statement =
959                     connection.prepareStatement(
960                         "SELECT 1 FROM VERSION v, URI u WHERE v.URI_ID = u.URI_ID and u.URI_STRING = ?");
961                 statement.setString(1, uri.toString());
962                 res = statement.executeQuery();
963                 revisionExists = res.next();
964             } finally {
965                 close(statement, res);
966             }
967             if (!revisionExists) {
968                 try {
969                     statement =
970                         connection.prepareStatement(
971                             "insert into VERSION (URI_ID, IS_VERSIONED) select u.URI_ID, ? from URI u where u.URI_STRING = ?");
972                     statement.setInt(1, isVersioned);
973                     statement.setString(2, uri.toString());
974                     statement.executeUpdate();
975                 } finally {
976                     close(statement, res);
977                 }
978             }
979             boolean versionHistoryExists;
980             NodeRevisionNumber versionNumber = revisionDescriptors.hasRevisions() ? revisionDescriptors.getLatestRevision() : new NodeRevisionNumber();
981             try {
982                 statement =
983                     connection.prepareStatement(
984                         "SELECT 1 FROM VERSION_HISTORY vh, URI u WHERE vh.URI_ID = u.URI_ID and u.URI_STRING = ? and REVISION_NO = ?");
985                 statement.setString(1, uri.toString());
986                 statement.setString(2, versionNumber.toString());
987                 res = statement.executeQuery();
988                 versionHistoryExists = res.next();
989             } finally {
990                 close(statement, res);
991             }
992             if (!versionHistoryExists && revisionDescriptors.getLatestRevision() != null) {
993                 try {
994                     statement =
995                         connection.prepareStatement(
996                             "insert into VERSION_HISTORY (URI_ID, BRANCH_ID, REVISION_NO) select u.URI_ID, b.BRANCH_ID, ? from URI u, BRANCH b where u.URI_STRING = ? and b.BRANCH_STRING = ?");
997                     statement.setString(1, getRevisionNumberAsString(versionNumber));
998                     statement.setString(2, uri.toString());
999                     statement.setString(3, NodeRevisionDescriptors.MAIN_BRANCH);
1000                    // FIXME: Create new revisions on the main branch???
1001
statement.executeUpdate();
1002                } finally {
1003                    close(statement, res);
1004                }
1005            }
1006            
1007            
1008            // Add revision successors
1009
Enumeration revisionNumbers = revisionDescriptors.enumerateRevisionNumbers();
1010            while (revisionNumbers.hasMoreElements()) {
1011                NodeRevisionNumber nodeRevisionNumber = (NodeRevisionNumber) revisionNumbers.nextElement();
1012                
1013                Enumeration successors = revisionDescriptors.getSuccessors(nodeRevisionNumber);
1014                while (successors.hasMoreElements())
1015                {
1016                    try {
1017                        NodeRevisionNumber successor = (NodeRevisionNumber) successors.nextElement();
1018                        
1019                        statement =
1020                            connection.prepareStatement(
1021                                    "insert into VERSION_PREDS (VERSION_ID, PREDECESSOR_ID) " +
1022                                    " select vr.VERSION_ID, suc.VERSION_ID" +
1023                                    " FROM URI uri, VERSION_HISTORY vr, VERSION_HISTORY suc " +
1024                                    " where vr.URI_ID = uri.URI_ID " +
1025                                    " and suc.URI_ID = uri.URI_ID " +
1026                                    " and uri.URI_STRING = ? " +
1027                                    " and vr.REVISION_NO = ? " +
1028                                    " and suc.REVISION_NO = ? " );
1029                        
1030                        statement.setString(1, uri.toString());
1031                        statement.setString(2, nodeRevisionNumber.toString());
1032                        statement.setString(3, successor.toString());
1033                        statement.executeUpdate();
1034                    } finally {
1035                        close(statement);
1036                    }
1037                }
1038            }
1039            getLogger().log(
1040                revisionDescriptors.getOriginalUri() + revisionDescriptors.getInitialRevision(),
1041                LOG_CHANNEL,
1042                Logger.DEBUG);
1043        } catch (SQLException JavaDoc e) {
1044            throw createException(e, uri.toString());
1045        }
1046    }
1047
1048    public void createRevisionContent(
1049        Connection JavaDoc connection,
1050        Uri uri,
1051        NodeRevisionDescriptor revisionDescriptor,
1052        NodeRevisionContent revisionContent)
1053        throws ServiceAccessException, RevisionAlreadyExistException {
1054        if (!storeRevisionContent(connection, uri, revisionDescriptor, revisionContent, true)) {
1055            throw new RevisionAlreadyExistException(uri.toString(), revisionDescriptor.getRevisionNumber());
1056        }
1057    }
1058
1059    public void storeRevisionContent(
1060        Connection JavaDoc connection,
1061        Uri uri,
1062        NodeRevisionDescriptor revisionDescriptor,
1063        NodeRevisionContent revisionContent)
1064        throws ServiceAccessException, RevisionNotFoundException {
1065        if (!storeRevisionContent(connection, uri, revisionDescriptor, revisionContent, false)) {
1066            throw new RevisionNotFoundException(uri.toString(), revisionDescriptor.getRevisionNumber());
1067        }
1068    }
1069
1070    public boolean storeRevisionContent(
1071        Connection JavaDoc connection,
1072        Uri uri,
1073        NodeRevisionDescriptor revisionDescriptor,
1074        NodeRevisionContent revisionContent,
1075        boolean create)
1076        throws ServiceAccessException {
1077        try {
1078            // check if revision already exists
1079
PreparedStatement JavaDoc statement = null;
1080            ResultSet JavaDoc res = null;
1081            try {
1082                statement =
1083                    connection.prepareStatement(
1084                        "select 1 from VERSION_CONTENT vc, VERSION_HISTORY vh, URI u where vc.VERSION_ID = vh.VERSION_ID and vh.URI_ID = u.URI_ID and u.URI_STRING = ? and vh.REVISION_NO = ?");
1085                statement.setString(1, uri.toString());
1086                statement.setString(2, revisionDescriptor.getRevisionNumber().toString());
1087                res = statement.executeQuery();
1088                if (res.next()) {
1089                    if (create)
1090                        return false;
1091                } else {
1092                    if (!create)
1093                        return false;
1094                }
1095            } finally {
1096                close(statement, res);
1097            }
1098            if (!create) {
1099                removeRevisionContent(connection, uri, revisionDescriptor);
1100            }
1101            storeContent(connection, uri, revisionDescriptor, revisionContent);
1102        } catch (SQLException JavaDoc e) {
1103            throw createException(e, uri.toString());
1104        } catch (IOException e) {
1105            getLogger().log(e, LOG_CHANNEL, Logger.ERROR);
1106            throw new ServiceAccessException(service, e);
1107        }
1108        return true;
1109    }
1110
1111    protected void assureVersionInfo(Connection JavaDoc connection, Uri uri, NodeRevisionDescriptor revisionDescriptor)
1112        throws SQLException JavaDoc {
1113        PreparedStatement JavaDoc statement = null;
1114        ResultSet JavaDoc res = null;
1115        boolean revisionExists;
1116        try {
1117            statement =
1118                connection.prepareStatement(
1119                    "select 1 from VERSION v, URI u where v.URI_ID = u.URI_ID and u.URI_STRING = ?");
1120            statement.setString(1, uri.toString());
1121            res = statement.executeQuery();
1122            revisionExists = res.next();
1123        } finally {
1124            close(statement, res);
1125        }
1126        // FIXME: Is it true, that the default for IS_VERSIONED is 0 ??
1127
if (!revisionExists) {
1128            try {
1129                statement =
1130                    connection.prepareStatement(
1131                        "insert into VERSION (URI_ID, IS_VERSIONED) select u.URI_ID, ? from URI u where u.URI_STRING = ?");
1132                statement.setInt(1, 0);
1133                statement.setString(2, uri.toString());
1134                statement.executeUpdate();
1135            } finally {
1136                close(statement);
1137            }
1138        }
1139        boolean versionHistoryExists;
1140        try {
1141            statement =
1142                connection.prepareStatement(
1143                    "select 1 from VERSION_HISTORY vh, URI u where vh.URI_ID = u.URI_ID and u.URI_STRING = ? and REVISION_NO = ?");
1144            statement.setString(1, uri.toString());
1145            statement.setString(2, revisionDescriptor.getRevisionNumber().toString());
1146            res = statement.executeQuery();
1147            versionHistoryExists = res.next();
1148        } finally {
1149            close(statement, res);
1150        }
1151        if (!versionHistoryExists) {
1152            long branchId = assureBranchId(connection, revisionDescriptor.getBranchName());
1153            try {
1154                statement =
1155                    connection.prepareStatement(
1156                        "insert into VERSION_HISTORY (URI_ID, BRANCH_ID, REVISION_NO) select u.URI_ID, ?, ? from URI u where u.URI_STRING = ?");
1157                statement.setLong(1, branchId);
1158                statement.setString(2, getRevisionNumberAsString(revisionDescriptor.getRevisionNumber()));
1159                statement.setString(3, uri.toString());
1160                statement.executeUpdate();
1161            } finally {
1162                close(statement);
1163            }
1164        }
1165    }
1166
1167    protected void storeContent(
1168        Connection JavaDoc connection,
1169        Uri uri,
1170        NodeRevisionDescriptor revisionDescriptor,
1171        NodeRevisionContent revisionContent)
1172        throws IOException, SQLException JavaDoc {
1173
1174        assureVersionInfo(connection, uri, revisionDescriptor);
1175
1176        PreparedStatement JavaDoc statement = null;
1177        InputStream is = null;
1178        is = revisionContent.streamContent();
1179        if (is != null) {
1180            long contentLength = 0;
1181            if (bcompress) {
1182                getLogger().log("Compressing the data", LOG_CHANNEL, Logger.DEBUG);
1183                StoreContentZip ziputil = new StoreContentZip();
1184                ziputil.Zip(is);
1185                is = ziputil.getInputStream();
1186                contentLength = ziputil.getContentLength();
1187            } else {
1188                contentLength = revisionDescriptor.getContentLength();
1189            }
1190            byte buffer[] = new byte[2048];
1191            File tempFile = null;
1192            if (contentLength == -1) {
1193                try {
1194                    tempFile = File.createTempFile("content", null);
1195                    FileOutputStream fos = new FileOutputStream(tempFile);
1196                    do {
1197                        int nChar = is.read(buffer);
1198                        if (nChar == -1)
1199                            break;
1200                        fos.write(buffer, 0, nChar);
1201                    } while (true);
1202                    fos.close();
1203                    is.close();
1204                    is = new FileInputStream(tempFile);
1205                    contentLength = tempFile.length();
1206                } catch (IOException ex) {
1207                    getLogger().log(
1208                        ex.toString() + " during the calculation of the content length.",
1209                        LOG_CHANNEL,
1210                        Logger.ERROR);
1211                    getLogger().log("tempFile: " + tempFile.getAbsolutePath(), LOG_CHANNEL, Logger.ERROR);
1212                    throw ex;
1213                }
1214            }
1215            // Changed (contentlength - 1) to (contentlength) as DB2 was complaining about
1216
// length mismatch for stream in the below method
1217
// insertStatement.setBinaryStream(2, is, (int)contentLength -1);
1218
try {
1219                statement =
1220                    connection.prepareStatement(
1221                        "insert into VERSION_CONTENT (VERSION_ID, CONTENT) select vh.VERSION_ID, ? from VERSION_HISTORY vh, URI u where vh.URI_ID = u.URI_ID and u.URI_STRING = ? and vh.REVISION_NO = ?");
1222                statement.setBinaryStream(1, is, (int) contentLength);
1223                statement.setString(2, uri.toString());
1224                statement.setString(3, revisionDescriptor.getRevisionNumber().toString());
1225                statement.executeUpdate();
1226                if (tempFile != null) {
1227                    is.close();
1228                    is = null;
1229                    tempFile.delete();
1230                }
1231            } finally {
1232                try {
1233                    close(statement);
1234                } finally {
1235                    if (is != null) {
1236                        // XXX some JDBC drivers seem to close the stream upon closing of
1237
// the statement; if so this will raise an IOException
1238
// silently ignore it...
1239
try {
1240                            is.close();
1241                        } catch (IOException ioe) {
1242                            logger.log("Could not close stream", ioe, LOG_CHANNEL, Logger.DEBUG);
1243                        }
1244                    }
1245                }
1246            }
1247        }
1248    }
1249
1250    public void storeRevisionDescriptor(Connection JavaDoc connection, Uri uri, NodeRevisionDescriptor revisionDescriptor)
1251        throws ServiceAccessException, RevisionDescriptorNotFoundException {
1252        removeRevisionDescriptor(connection, uri, revisionDescriptor.getRevisionNumber());
1253        createRevisionDescriptor(connection, uri, revisionDescriptor);
1254    }
1255
1256    public void storeRevisionDescriptors(Connection JavaDoc connection, Uri uri, NodeRevisionDescriptors revisionDescriptors)
1257        throws ServiceAccessException, RevisionDescriptorNotFoundException {
1258        removeRevisionDescriptors(connection, uri);
1259        createRevisionDescriptors(connection, uri, revisionDescriptors);
1260    }
1261
1262    protected long assureUriId(Connection JavaDoc connection, String JavaDoc uri) throws SQLException JavaDoc {
1263        PreparedStatement JavaDoc statement = null;
1264        ResultSet JavaDoc res = null;
1265        try {
1266            statement = connection.prepareStatement("select URI_ID from URI where URI_STRING=?");
1267            statement.setString(1, uri);
1268            res = statement.executeQuery();
1269            if (res.next()) {
1270                long id = res.getLong(1);
1271                return id;
1272            }
1273        } finally {
1274            close(statement, res);
1275        }
1276        try {
1277            statement = connection.prepareStatement("insert into URI (URI_STRING) values (?)");
1278            statement.setString(1, uri);
1279            statement.executeUpdate();
1280        } finally {
1281            close(statement);
1282        }
1283        return assureUriId(connection, uri);
1284    }
1285
1286    protected long assureBranchId(Connection JavaDoc connection, String JavaDoc branch) throws SQLException JavaDoc {
1287        PreparedStatement JavaDoc statement = null;
1288        ResultSet JavaDoc res = null;
1289        try {
1290            statement = connection.prepareStatement("select BRANCH_ID from BRANCH where BRANCH_STRING=?");
1291            statement.setString(1, branch);
1292            res = statement.executeQuery();
1293            if (res.next()) {
1294                long id = res.getLong(1);
1295                return id;
1296            }
1297        } finally {
1298            close(statement, res);
1299        }
1300        try {
1301            statement = connection.prepareStatement("insert into BRANCH (BRANCH_STRING) values (?)");
1302            statement.setString(1, branch);
1303            statement.executeUpdate();
1304        } finally {
1305            close(statement);
1306        }
1307        return assureBranchId(connection, branch);
1308    }
1309
1310    protected long assureLabelId(Connection JavaDoc connection, String JavaDoc label) throws SQLException JavaDoc {
1311        PreparedStatement JavaDoc statement = null;
1312        ResultSet JavaDoc res = null;
1313        try {
1314            statement = connection.prepareStatement("select LABEL_ID from LABEL where LABEL_STRING=?");
1315            statement.setString(1, label);
1316            res = statement.executeQuery();
1317            if (res.next()) {
1318                long id = res.getLong(1);
1319                return id;
1320            }
1321        } finally {
1322            close(statement, res);
1323        }
1324        try {
1325            statement = connection.prepareStatement("insert into LABEL (LABEL_STRING) values (?)");
1326            statement.setString(1, label);
1327            statement.executeUpdate();
1328        } finally {
1329            close(statement);
1330        }
1331        return assureLabelId(connection, label);
1332    }
1333
1334    protected void clearBinding(Connection JavaDoc connection, Uri uri)
1335        throws ServiceAccessException, ObjectNotFoundException, SQLException JavaDoc {
1336        PreparedStatement JavaDoc statement = null;
1337
1338        // clear this uri from having bindings and being bound
1339

1340        try {
1341            statement =
1342                connection.prepareStatement(
1343                    "delete BINDING from BINDING c, URI u where c.URI_ID = u.URI_ID and u.URI_STRING = ?");
1344            statement.setString(1, uri.toString());
1345            statement.executeUpdate();
1346        } finally {
1347            close(statement);
1348        }
1349
1350        try {
1351            statement =
1352                connection.prepareStatement(
1353                    "delete PARENT_BINDING from PARENT_BINDING c, URI u where c.URI_ID = u.URI_ID and u.URI_STRING = ?");
1354            statement.setString(1, uri.toString());
1355            statement.executeUpdate();
1356        } finally {
1357            close(statement);
1358        }
1359    }
1360
1361    // null means permission is valid for all revisions
1362
protected String JavaDoc getRevisionNumberAsString(NodeRevisionNumber revisionNumber) {
1363        return revisionNumber != null ? revisionNumber.toString() : null;
1364    }
1365
1366    protected String JavaDoc convertRevisionNumberToComparable(String JavaDoc revisioNumber) {
1367        return "convert(numeric, SUBSTRING("+revisioNumber+",1,charindex('.',"+revisioNumber+"))), convert(numeric, SUBSTRING("+revisioNumber+",charindex('.',"+revisioNumber+")+1,100))";
1368    }
1369
1370    protected void close(PreparedStatement JavaDoc statement) {
1371        try {
1372            if (statement != null) {
1373                statement.close();
1374            }
1375        } catch (SQLException JavaDoc e) {
1376            getLogger().log(e, LOG_CHANNEL, Logger.WARNING);
1377        }
1378    }
1379
1380    protected void close(PreparedStatement JavaDoc statement, ResultSet JavaDoc resultSet) {
1381        try {
1382            if (resultSet != null) {
1383                resultSet.close();
1384            }
1385        } catch (SQLException JavaDoc e) {
1386            getLogger().log(e, LOG_CHANNEL, Logger.WARNING);
1387        } finally {
1388            try {
1389                if (statement != null) {
1390                    statement.close();
1391                }
1392            } catch (SQLException JavaDoc e) {
1393                getLogger().log(e, LOG_CHANNEL, Logger.WARNING);
1394            }
1395        }
1396    }
1397
1398    // overload this method to have a more detailed error handling
1399
protected ServiceAccessException createException(SQLException JavaDoc e, String JavaDoc uri) {
1400        getLogger().log(
1401            "SQL error " + e.getErrorCode() + " on " + uri + ": " + e.getMessage(),
1402            LOG_CHANNEL,
1403            Logger.ERROR);
1404        return new ServiceAccessException(service, e);
1405    }
1406
1407}
1408
Popular Tags