KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > dav > server > managers > HarmoniseNamespaceManager


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

19
20 package org.openharmonise.dav.server.managers;
21
22
23 import java.io.*;
24 import java.net.*;
25 import java.util.*;
26 import java.util.logging.*;
27
28 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
29
30 import org.openharmonise.commons.dsi.AbstractDataStoreInterface;
31 import org.openharmonise.commons.net.MimeTypeMapping;
32 import org.openharmonise.commons.xml.XMLUtils;
33 import org.openharmonise.commons.xml.namespace.NamespaceType;
34 import org.openharmonise.dav.server.adapters.WebPageResourceAdapter;
35 import org.openharmonise.dav.server.apm.*;
36 import org.openharmonise.dav.server.utils.*;
37 import org.openharmonise.rm.*;
38 import org.openharmonise.rm.config.ConfigSettings;
39 import org.openharmonise.rm.dsi.DataStoreInterfaceFactory;
40 import org.openharmonise.rm.metadata.*;
41 import org.openharmonise.rm.resources.*;
42 import org.openharmonise.rm.resources.content.*;
43 import org.openharmonise.rm.resources.lifecycle.*;
44 import org.openharmonise.rm.resources.lifecycle.Status;
45 import org.openharmonise.rm.resources.metadata.properties.*;
46 import org.openharmonise.rm.resources.metadata.properties.ranges.*;
47 import org.openharmonise.rm.resources.metadata.values.Value;
48 import org.openharmonise.rm.resources.publishing.WebPage;
49 import org.openharmonise.rm.resources.users.User;
50 import org.openharmonise.rm.resources.xml.*;
51 import org.openharmonise.rm.security.authorization.*;
52 import org.w3c.dom.*;
53
54 import com.ibm.webdav.*;
55 import com.ibm.webdav.impl.*;
56 import com.ibm.webdav.protocol.http.*;
57
58 /**
59  * Open Harmonise implementation of <code>NamespaceManager</code>.
60  *
61  * @author Michael Bell
62  * @version $Revision: 1.4 $
63  *
64  */

65 /**
66  * FIXME - Michael Bell DIDN'T GIVE ME A DESCRIPTION!!
67  * @author Michael Bell
68  * @version $Revision: 1.4 $
69  *
70  */

71 public class HarmoniseNamespaceManager
72     implements com.ibm.webdav.impl.NamespaceManager {
73     public static final String JavaDoc TAG_AFTER = "after";
74     public static final String JavaDoc TAG_BEFORE = "before";
75     public static final String JavaDoc TAG_LAST = "last";
76     public static final String JavaDoc TAG_FIRST = "first";
77     public static final String JavaDoc TAG_POSITION = "position";
78     public static final String JavaDoc TAG_SEGMENT = "segment";
79     public static final String JavaDoc TAG_ORDER_MEMBER = "order-member";
80     private static final int bufferSize = 8192;
81     protected AuxillaryProcessManager m_auxillary = null;
82     private static final String JavaDoc PNAME_WEBDAV_APM = "WEBDAV_APM";
83
84     private boolean m_bIsArchived = false;
85     protected ResourceImpl m_resource = null;
86     protected AbstractChildObject m_child = null;
87     private OutputStream m_openedOutputStream = null;
88     protected AbstractDataStoreInterface m_dsi = null;
89     static private List STD_ALLOWED_METHODS = new Vector();
90     static private List VIRTUAL_DIR_ALLOWED_METHODS = new Vector();
91     static private List ARCHIVE_ALLOWED_METHODS = new Vector();
92     static private Map DAV_HARMONISE_COMMAND_MAPPING = new Hashtable();
93     
94     private static Logger m_logger = Logger.getLogger(HarmoniseNamespaceManager.class.getName());
95
96     static {
97         STD_ALLOWED_METHODS.add("PUT");
98         STD_ALLOWED_METHODS.add("GET");
99         STD_ALLOWED_METHODS.add("PROPFIND");
100         STD_ALLOWED_METHODS.add("PROPPATCH");
101         STD_ALLOWED_METHODS.add("OPTIONS");
102         STD_ALLOWED_METHODS.add("SEARCH");
103         STD_ALLOWED_METHODS.add("COPY");
104         STD_ALLOWED_METHODS.add("DELETE");
105         STD_ALLOWED_METHODS.add("MOVE");
106         STD_ALLOWED_METHODS.add("BIND");
107         STD_ALLOWED_METHODS.add("HEAD");
108         STD_ALLOWED_METHODS.add("LOCK");
109         STD_ALLOWED_METHODS.add("UNLOCK");
110
111         VIRTUAL_DIR_ALLOWED_METHODS.add("PROPFIND");
112         VIRTUAL_DIR_ALLOWED_METHODS.add("OPTIONS");
113         VIRTUAL_DIR_ALLOWED_METHODS.add("SEARCH");
114
115         ARCHIVE_ALLOWED_METHODS.addAll(VIRTUAL_DIR_ALLOWED_METHODS);
116         ARCHIVE_ALLOWED_METHODS.add("GET");
117
118         DAV_HARMONISE_COMMAND_MAPPING.put("PUT", "Save");
119         DAV_HARMONISE_COMMAND_MAPPING.put("PROPPATCH", "Save");
120         DAV_HARMONISE_COMMAND_MAPPING.put("COPY", "Save");
121         DAV_HARMONISE_COMMAND_MAPPING.put("MOVE", "Save");
122         DAV_HARMONISE_COMMAND_MAPPING.put("MKCOL", "Save");
123         DAV_HARMONISE_COMMAND_MAPPING.put("BIND", "Save");
124         DAV_HARMONISE_COMMAND_MAPPING.put("LOCK", "Lock");
125         DAV_HARMONISE_COMMAND_MAPPING.put("UNLOCK", "Unlock");
126         DAV_HARMONISE_COMMAND_MAPPING.put("GET", "View");
127         DAV_HARMONISE_COMMAND_MAPPING.put("PROPFIND", "View");
128         DAV_HARMONISE_COMMAND_MAPPING.put("DELETE", "Archive");
129         DAV_HARMONISE_COMMAND_MAPPING.put("CHECKIN", "ChangeStatus");
130         DAV_HARMONISE_COMMAND_MAPPING.put("VERSION-CONTROL", "ChangeStatus");
131         DAV_HARMONISE_COMMAND_MAPPING.put("CHECKOUT", "Save");
132     }
133
134     /** Create a NamespaceManager for creating resources. (This is necessary because
135     * createResource can't be static and declared in the NamespaceManager interface.)
136     */

137     public HarmoniseNamespaceManager() {
138     }
139
140     /** Create a NamesapceManager for a given resource.
141     * @param resource the resource to manage
142     */

143     public HarmoniseNamespaceManager(ResourceImpl resource) {
144         initialize(resource);
145     }
146
147     public void closeContentsOutputStream() throws WebDAVException {
148         closeContentsOutputStream(null);
149     }
150
151     /**
152      * @see com.ibm.webdav.impl.NamespaceManager#closeContentsOutputStream()
153      */

154     public void closeContentsOutputStream(String JavaDoc sContentType)
155         throws WebDAVException {
156         
157         if(m_logger.isLoggable(Level.FINE)) {
158             m_logger.logp(Level.FINE, this.getClass().getName(), "closeContentsOutputStream", "Closing output stream");
159         }
160         
161
162         // close any opened output stream
163
if (m_openedOutputStream == null) {
164             throw new WebDAVException(
165                 WebDAVStatus.SC_BAD_REQUEST,
166                 "No output stream is opened");
167         }
168
169         try {
170             m_openedOutputStream.close();
171         } catch (WebDAVException exc) {
172             throw exc;
173         } catch (java.io.IOException JavaDoc exc) {
174             throw new WebDAVException(
175                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
176                 "IO Error");
177         }
178
179         try {
180             String JavaDoc contentType = sContentType;
181
182             if (contentType == null) {
183                 contentType =
184                     m_resource.getContext().getRequestContext().contentType();
185             }
186
187             String JavaDoc fileName = HarmoniseNameResolver.getFilePath(m_resource.getURL());
188
189             if ((contentType == null)
190                 || (contentType.equals("application/octet-stream") == true)) {
191                 String JavaDoc decodedFileName =
192                     java.net.URLDecoder.decode(fileName, HarmoniseNameResolver.UTF_8);
193
194                 
195                 if(m_logger.isLoggable(Level.FINE)) {
196                     String JavaDoc sMsg =
197                             "DAV: Getting extension from ["
198                                 + decodedFileName
199                                 + "]";
200                     m_logger.logp(Level.FINE, this.getClass().getName(), "closeContentsOutputStream", sMsg);
201                 }
202                 
203
204                 int dotIndex = decodedFileName.lastIndexOf(".");
205                 if (dotIndex > 0) {
206                     String JavaDoc ext = decodedFileName.substring(dotIndex + 1);
207
208                     contentType = MimeTypeMapping.getMimeTypeFromExtension(ext);
209                 }
210             }
211
212             User usr =
213                 ((HarmoniseSessionManager) m_resource.getUserAuthenticator())
214                     .getUser(m_resource);
215
216             //if this is an existing child object
217
if (m_child != null) {
218                 //if this is a live resource make sure that we remove the 'START' prop
219
if (m_child.isLiveVersion() == true) {
220                     Profile prof = m_child.getProfile();
221                     Property startProp =
222                         PropertyFactory.getPropertyFromName(
223                             m_dsi,
224                             HarmoniseNameResolver.START_PROP_NAME);
225                     prof.removeProperty(startProp);
226                 }
227
228                 if (m_child instanceof Asset) {
229                     if(m_logger.isLoggable(Level.FINE)) {
230                         m_logger.logp(Level.FINE, this.getClass().getName(), "closeContentsOutputStream", "Saving existng asset");
231                     }
232
233                     Asset asset = (Asset) m_child;
234
235                     if (isAssetSavedAsText(contentType) == true) {
236
237                         asset.setURI(getOutputStreamAsString());
238                     } else {
239                         File file = new File(fileName);
240                         asset.setContentFile(file);
241
242                         if(m_logger.isLoggable(Level.FINE)) {
243                             m_logger.logp(Level.FINE, this.getClass().getName(), "closeContentsOutputStream", "Guessed content type - "
244                                     + asset.getContentType());
245                         }
246                         
247                     }
248
249                     if (contentType != null) {
250                         asset.setContentType(contentType);
251                     }
252                 } else if (m_child instanceof TextResource) {
253                     if(m_logger.isLoggable(Level.FINE)) {
254                         m_logger.logp(Level.FINE, this.getClass().getName(), "closeContentsOutputStream", "saving existing document");
255                     }
256                     
257                     TextResource txt = (TextResource) m_child;
258
259                     txt.setContent(getOutputStreamAsString());
260                     if (contentType != null) {
261
262                         if (m_child instanceof XMLResource
263                             && contentType.equals("application/octet-stream")) {
264                             txt.setContentType(
265                                 MimeTypeMapping.XML.getMimeType());
266                         } else {
267                             txt.setContentType(contentType);
268                         }
269
270                     }
271
272                 } else if (m_child instanceof WebPage) {
273                     WebPageResourceAdapter page =
274                         new WebPageResourceAdapter((WebPage) m_child);
275                     page.populate(getOutputStreamAsString());
276                 }
277
278                 m_child =
279                     (AbstractChildObject) CommandWrapper.save(
280                         m_dsi,
281                         m_child,
282                         usr);
283
284             } else {
285                 // if this is a new child object
286

287                 String JavaDoc sResourcePath =
288                     URLDecoder.decode(
289                         m_resource.getURL().getPath(),
290                         HarmoniseNameResolver.UTF_8);
291
292                 String JavaDoc sResourceName =
293                     HarmoniseNameResolver.getLastSegment(sResourcePath);
294
295                 String JavaDoc parentPath =
296                     HarmoniseNameResolver.getPathParent(sResourcePath);
297
298                 AbstractParentObject parentObj =
299                     (AbstractParentObject) HarmoniseNameResolver.getObjectFromURL(
300                         m_dsi,
301                         parentPath);
302                 
303                 //now we have the parent, check that it's live
304
if(parentObj.isLiveVersion() == false) {
305                     throw new WebDAVException(WebDAVStatus.SC_FORBIDDEN,"Collection must be live to add a child");
306                 }
307
308                 if(m_logger.isLoggable(Level.FINE)) {
309                     m_logger.logp(Level.FINE, this.getClass().getName(), "closeContentsOutputStream", "child's parent's name:" + parentPath);
310                 }
311
312                 m_child =
313                     (AbstractChildObject) Class
314                         .forName(
315                             HarmoniseNameResolver.getChildTypeFromURL(sResourcePath))
316                         .newInstance();
317                 m_child.setDataStoreInterface(m_dsi);
318
319                 m_child.setName(sResourceName);
320
321                 Profile prof = new Profile(this.m_dsi, m_child);
322                 prof.setName(sResourceName);
323                 m_child.setProfile(prof);
324
325                 //set content
326
if (m_child instanceof Asset) {
327                     Asset asset = (Asset) m_child;
328
329                     if (isAssetSavedAsText(contentType) == true) {
330
331                         asset.setURI(getOutputStreamAsString());
332                     } else {
333                         File file = new File(fileName);
334                         asset.setContentFile(file);
335                     }
336
337                     if (contentType != null) {
338                         asset.setContentType(contentType);
339                     }
340                 } else if (m_child instanceof TextResource) {
341                     TextResource doc = (TextResource) m_child;
342
343                     doc.setContent(getOutputStreamAsString());
344
345                     if (m_child instanceof XMLResource
346                         && (contentType == null
347                             || contentType.equals("application/octet-stream"))) {
348                         doc.setContentType(MimeTypeMapping.XML.getMimeType());
349                     } else {
350                         doc.setContentType(contentType);
351                     }
352                 } else if (m_child instanceof Property) {
353                     //new prop gets String range as default
354
try {
355                         ((Property) m_child).setRange(new StringRange());
356                      } catch(InvalidRangeException e) {
357                         //ignore as if it's not allowed it's not allowed
358
}
359                      
360                 } else if (m_child instanceof WebPage) {
361                     WebPageResourceAdapter page =
362                         new WebPageResourceAdapter((WebPage) m_child);
363                     page.populate(getOutputStreamAsString());
364                 }
365
366                 m_child =
367                     (AbstractChildObject) CommandWrapper.save(
368                         m_dsi,
369                         m_child,
370                         usr);
371
372                 parentObj.acquireEditWriteLock();
373                 try {
374                     parentObj.addChild(m_child);
375
376                     //bypass RBS as we're not interested for this operation
377
parentObj.save();
378                 } finally {
379                     parentObj.releaseEditWriteLock();
380                 }
381
382                 //have to do this after the child has a parent so that
383
//role can be attached
384
if (m_child instanceof User) {
385                     //new users get BROWSER role
386
AuthorityProfile secProf = new AuthorityProfile(m_dsi);
387                     m_child.addProfile(secProf);
388
389                     Property roleProp =
390                         PropertyFactory.getPropertyFromName(
391                             m_dsi,
392                             AuthorizationValidator.PROP_ROLE);
393                     ChildObjectPropertyInstance roleInst =
394                         new ChildObjectPropertyInstance(m_dsi, roleProp);
395
396                     List vals =
397                         ((AbsoluteChildObjectRange) roleProp.getRange())
398                             .getAvailableValues();
399
400                     boolean bFound = false;
401
402                     Iterator iter = vals.iterator();
403
404                     while (iter.hasNext() && bFound == false) {
405                         Value tmpVal = (Value) iter.next();
406
407                         if (tmpVal.getName().equals("BROWSER")) {
408                             roleInst.addValue(tmpVal);
409                             secProf.addPropertyInstance(roleInst);
410                             bFound = true;
411                         }
412                     }
413
414                 }
415
416                 if(m_logger.isLoggable(Level.FINE)) {
417                     m_logger.logp(Level.FINE, this.getClass().getName(), "closeContentsOutputStream", "Adding new document or asset:" + sResourceName);
418                 }
419
420             }
421
422             if (m_auxillary != null) {
423                 m_auxillary.save(usr, m_child);
424             }
425         } catch(WebDAVException e) {
426             //ensure WEBDAVExceptions get thrown up - be warned WebDAVException is a subclass of IOException!
427
throw e;
428         } catch (ClassCastException JavaDoc e) {
429             m_logger.log(Level.WARNING, "closeContentsOutputStream", e);
430             throw new WebDAVException(
431                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
432                 e.getLocalizedMessage());
433         } catch (APMException e) {
434             throw new WebDAVException(
435                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
436                 e.getLocalizedMessage());
437         } catch (NameResolverException e) {
438             throw new WebDAVException(
439                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
440                 e.getLocalizedMessage());
441         } catch (InstantiationException JavaDoc e) {
442             throw new WebDAVException(
443                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
444                 e.getLocalizedMessage());
445         } catch (IllegalAccessException JavaDoc e) {
446             throw new WebDAVException(
447                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
448                 e.getLocalizedMessage());
449         } catch (ClassNotFoundException JavaDoc e) {
450             throw new WebDAVException(
451                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
452                 e.getLocalizedMessage());
453         } catch (IOException e) {
454             m_logger.log(Level.WARNING, "closeContentsOutputStream", e);
455             throw new WebDAVException(
456                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
457                 e.getLocalizedMessage());
458         } catch (InvalidChildException e) {
459             m_logger.log(Level.WARNING, "closeContentsOutputStream", e);
460             
461             throw new WebDAVException(
462                 WebDAVStatus.SC_FORBIDDEN,
463                 e.getLocalizedMessage());
464         }catch (InvalidNameException e) {
465             throw new WebDAVException(
466                 WebDAVStatus.SC_FORBIDDEN,
467                 e.getLocalizedMessage());
468         } catch (InvalidXMLContentException e) {
469             m_logger.log(Level.WARNING, "closeContentsOutputStream", e);
470             throw new WebDAVException(
471                 WebDAVStatus.SC_BAD_REQUEST,
472                 e.getLocalizedMessage());
473         } catch (HarmoniseException e) {
474             m_logger.log(Level.WARNING, "closeContentsOutputStream", e);
475             throw new WebDAVException(
476                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
477                 e.getLocalizedMessage());
478         }
479
480         m_openedOutputStream = null;
481     }
482
483     /**
484      * @see com.ibm.webdav.impl.NamespaceManager#createBinding(java.net.URL)
485      */

486     public void createBinding(String JavaDoc bindName, URL sourceURL)
487         throws WebDAVException {
488         try {
489
490             if ((m_child instanceof AbstractParentObject) == false) {
491                 throw new WebDAVException(
492                     WebDAVStatus.SC_BAD_REQUEST,
493                     "Resource not collection");
494             }
495
496             AbstractParentObject parentObj = (AbstractParentObject) m_child;
497
498             AbstractChildObject child =
499                 HarmoniseNameResolver.getObjectFromURL(m_dsi, sourceURL);
500
501             if (child.getName().equals(bindName) == false) {
502                 throw new WebDAVException(
503                     WebDAVStatus.SC_FORBIDDEN,
504                     "Server doesn't support changing the name of the resource for the binding");
505             }
506
507             parentObj.acquireEditWriteLock();
508             try {
509                 parentObj.addChild(child, true);
510     
511                 if (parentObj == null) {
512                     throw new WebDAVException(
513                         WebDAVStatus.SC_BAD_REQUEST,
514                         "Parent not found");
515                 }
516     
517                 CommandWrapper.save(
518                     m_dsi,
519                     parentObj,
520                     ((HarmoniseSessionManager) m_resource.getUserAuthenticator())
521                         .getUser(m_resource));
522             } finally {
523                 parentObj.releaseEditWriteLock();
524             }
525             
526
527         } catch (NameResolverException e) {
528             throw new WebDAVException(
529                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
530                 e.getLocalizedMessage());
531         } catch (InvalidChildException e) {
532             throw new WebDAVException(
533                 WebDAVStatus.SC_BAD_REQUEST,
534                 e.getLocalizedMessage());
535         } catch (PopulateException e) {
536             throw new WebDAVException(
537                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
538                 e.getLocalizedMessage());
539         } catch (DataAccessException e) {
540             throw new WebDAVException(
541                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
542                 e.getLocalizedMessage());
543         } catch (EditException e) {
544             throw new WebDAVException(
545                     WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
546                     e.getLocalizedMessage());
547         }
548     }
549
550     /**
551      * @see com.ibm.webdav.impl.NamespaceManager#createCollection(java.lang.String)
552      */

553     public void createCollection(String JavaDoc localName) throws WebDAVException {
554         
555             try {
556                 String JavaDoc newURL = localName.replace(File.separatorChar, '/');
557
558                 newURL = new URL(m_resource.getURL(), newURL).getPath();
559
560                 if(m_logger.isLoggable(Level.FINE)) {
561                     m_logger.logp(Level.FINE, this.getClass().getName(), "createCollection", "========== local name - " + localName);
562                     m_logger.logp(Level.FINE, this.getClass().getName(), "createCollection", "Creating collection:" + newURL);
563                 }
564
565                 String JavaDoc parentURL = HarmoniseNameResolver.getPathParent(newURL);
566
567                 if(m_logger.isLoggable(Level.FINE)) {
568                     m_logger.logp(Level.FINE, this.getClass().getName(), "createCollection", "New collection parent:" + parentURL);
569                 }
570
571                 AbstractParentObject parent =
572                     (AbstractParentObject) HarmoniseNameResolver.getObjectFromURL(
573                         m_dsi,
574                         parentURL);
575
576                 if (parent != null) {
577                     List childClassnames = parent.getChildClassNames();
578                     Class JavaDoc clss = parent.getClass();
579                     
580                     Iterator iter = childClassnames.iterator();
581                     boolean bFound = false;
582                     
583                     while (iter.hasNext() && bFound == false) {
584                         String JavaDoc sClassname = (String JavaDoc) iter.next();
585                         Class JavaDoc tmpClass = Class.forName(sClassname);
586                         if(AbstractParentObject.class.isAssignableFrom(tmpClass)) {
587                             clss = tmpClass;
588                             bFound = true;
589                         }
590                     }
591                     
592                     AbstractParentObject newObj =
593                         (AbstractParentObject) clss.newInstance();
594                     newObj.setDataStoreInterface(m_dsi);
595
596                     String JavaDoc newName = HarmoniseNameResolver.getLastSegment(newURL);
597
598                     newObj.setName(newName);
599
600                     Profile parentPro = parent.getProfile();
601
602                     Profile pro = null;
603
604                     if (parentPro != null) {
605                         pro = (Profile) parentPro.clone();
606                     }
607
608                     if (pro == null) {
609                         pro = new Profile(this.m_dsi);
610                     }
611
612                     pro.setName(newName);
613                     newObj.setProfile(pro);
614
615                     User usr =
616                         ((HarmoniseSessionManager) m_resource.getUserAuthenticator())
617                             .getUser(m_resource);
618
619                     newObj =
620                         (AbstractParentObject) CommandWrapper.save(
621                             m_dsi,
622                             newObj,
623                             usr);
624
625                     parent.acquireEditWriteLock();
626                     try {
627                         parent.addChild(newObj);
628
629                         //save parent
630
CommandWrapper.save(m_dsi, parent, usr);
631                     } finally {
632                         parent.releaseEditWriteLock();
633                     }
634                     
635                     
636                     if (ConfigSettings
637                         .getBoolProperty(
638                             HarmoniseNameResolver.PNAME_AUTO_APPROVE_COLLECTIONS,
639                             "true")
640                         == true) {
641
642                         //change status on newObj
643
CommandWrapper.changeStatus(
644                             m_dsi,
645                             newObj,
646                             usr,
647                             Status.APPROVED);
648
649                         if (m_auxillary != null) {
650                             m_auxillary.changeStatus(
651                                 usr,
652                                 newObj,
653                                 Status.UNAPPROVED,
654                                 Status.APPROVED);
655                         }
656                     }
657                 } else {
658                     m_logger.logp(Level.WARNING, this.getClass().getName(), "createCollection", "Parent section not found:" + parentURL);
659                     throw new WebDAVException(
660                         WebDAVStatus.SC_BAD_REQUEST,
661                         "problem creating new section");
662                 }
663             
664             } catch (Exception JavaDoc e) {
665                 throw ExceptionTransformer.transform(e);
666             }
667         
668     }
669
670     /**
671      * @see com.ibm.webdav.impl.NamespaceManager#createLockNullResource()
672      */

673     public void createLockNullResource() throws WebDAVException {
674         org.w3c.dom.Document JavaDoc document = m_resource.loadProperties();
675         m_resource.saveProperties(document);
676     }
677
678     /**
679      * @see com.ibm.webdav.impl.NamespaceManager#move(java.lang.String)
680      */

681     public void move(String JavaDoc destLocation) throws WebDAVException {
682         try {
683             destLocation = destLocation.replace(File.separatorChar, '/');
684             destLocation = new URL(m_resource.getURL(), destLocation).getPath();
685
686             String JavaDoc oldParentURL =
687                 HarmoniseNameResolver.getPathParent(
688                     URLDecoder.decode(
689                         m_resource.getURL().getPath(),
690                         HarmoniseNameResolver.UTF_8));
691
692             AbstractParentObject oldParentObj =
693                 (AbstractParentObject) HarmoniseNameResolver.getObjectFromURL(
694                     this.m_dsi,
695                     oldParentURL);
696
697             AbstractParentObject newParent =
698                 (AbstractParentObject) HarmoniseNameResolver.getObjectFromURL(
699                     this.m_dsi,
700                     HarmoniseNameResolver.getPathParent(destLocation));
701
702             if (newParent == null) {
703                 throw new WebDAVException(
704                     WebDAVStatus.SC_NOT_FOUND,
705                     "Destination not found");
706             }
707
708             //modify resource
709
if(m_logger.isLoggable(Level.FINE)) {
710                 m_logger.logp(Level.FINE, this.getClass().getName(), "move", "Saving " + m_child.getClass().getName());
711             }
712             
713             String JavaDoc sCurrentName = m_child.getName();
714             String JavaDoc sNewName = HarmoniseNameResolver.getLastSegment(destLocation);
715
716             if (sCurrentName.equals(sNewName) == false) {
717                 if (m_child.getStatus() != Status.APPROVED
718                     || m_child.getPendingVersions().size() > 0) {
719                     throw new WebDAVException(
720                         WebDAVStatus.SC_FORBIDDEN,
721                         "Resource must be published before name change and can't have any pending versions");
722                 } else {
723                     m_child.setName(sNewName);
724                 }
725             }
726
727             User usr =
728                 ((HarmoniseSessionManager) m_resource.getUserAuthenticator())
729                     .getUser(m_resource);
730
731             if (oldParentObj.equals(newParent) == false) {
732                 boolean bIsDefault = false;
733
734                 if (oldParentObj.equals(m_child.getRealParent())) {
735                     bIsDefault = true;
736                 }
737
738                 oldParentObj.removeChild(m_child);
739
740                 CommandWrapper.save(m_dsi, oldParentObj, usr);
741
742                 newParent.acquireEditWriteLock();
743                 try {
744                     if (bIsDefault == true) {
745                         if(m_logger.isLoggable(Level.FINE)) {
746                             m_logger.logp(Level.FINE, this.getClass().getName(), "move", "Setting as default group " + newParent.getName());
747                         }
748                         
749                         newParent.addChild(m_child);
750                     } else {
751                         newParent.addChild(m_child, true);
752                     }
753
754                     CommandWrapper.save(m_dsi, newParent, usr);
755                 } finally {
756                     newParent.releaseEditWriteLock();
757                 }
758                 
759                 if(m_logger.isLoggable(Level.FINE)) {
760                     m_logger.logp(Level.FINE, this.getClass().getName(), "move", "new mapping - "
761                             + destLocation
762                             + ":"
763                             + m_child.getId());
764                 }
765
766             }
767
768             // in case child name has changed
769
if (m_child.isChanged() == true) {
770                 m_child = CommandWrapper.save(m_dsi, m_child, usr);
771                 m_child =
772                     CommandWrapper.changeStatus(
773                         m_dsi,
774                         m_child,
775                         usr,
776                         Status.APPROVED);
777             }
778
779         } catch (DataAccessException e) {
780             throw new WebDAVException(
781                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
782                 e.getLocalizedMessage());
783         } catch (UnsupportedEncodingException e) {
784             throw new WebDAVException(
785                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
786                 e.getLocalizedMessage());
787         } catch (MalformedURLException e) {
788             throw new WebDAVException(
789                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
790                 e.getLocalizedMessage());
791         } catch (NameResolverException e) {
792             throw new WebDAVException(
793                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
794                 e.getLocalizedMessage());
795         } catch (PopulateException e) {
796             throw new WebDAVException(
797                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
798                 e.getLocalizedMessage());
799         } catch (InvalidChildException e) {
800             m_logger.log(Level.INFO, "move", e);
801             
802             throw new WebDAVException(
803                 WebDAVStatus.SC_FORBIDDEN,
804                 e.getLocalizedMessage());
805         } catch (InvalidNameException e) {
806             throw new WebDAVException(
807                 WebDAVStatus.SC_FORBIDDEN,
808                 e.getLocalizedMessage());
809         } catch (EditException e) {
810             throw new WebDAVException(
811                     WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
812                     e.getLocalizedMessage());
813         }
814     }
815
816     /**
817      * @see com.ibm.webdav.impl.NamespaceManager#delete()
818      */

819     public void delete() throws WebDAVException {
820         try {
821             if(m_logger.isLoggable(Level.FINE)) {
822                 m_logger.logp(Level.FINE, this.getClass().getName(), "delete", "Deleting " + m_child.getName());
823             }
824
825             //enforce rule about not deleting collections with members
826
if (m_child instanceof AbstractParentObject) {
827
828                 if (((AbstractParentObject) m_child).getChildren().size()
829                     > 0) {
830                     throw new WebDAVException(
831                         WebDAVStatus.SC_FORBIDDEN,
832                         "Can't delete collection with members");
833                 }
834
835             }
836
837             String JavaDoc sResourcePath = m_resource.getURL().getPath();
838
839             boolean bArchive = true;
840             AbstractParentObject parentObj = null;
841
842             if (HarmoniseNameResolver.isVersionPath(sResourcePath) == false) {
843                 AbstractParentObject defaultParentObj = m_child.getRealParent();
844
845                 String JavaDoc parentPath =
846                     HarmoniseNameResolver.getPathParent(
847                         URLDecoder.decode(
848                             sResourcePath,
849                             HarmoniseNameResolver.UTF_8));
850
851                 if(m_logger.isLoggable(Level.FINE)) {
852                     m_logger.logp(Level.FINE, this.getClass().getName(), "delete", "Going to look for " + parentPath);
853                 }
854
855                 parentObj =
856                     (AbstractParentObject) HarmoniseNameResolver.getObjectFromURL(
857                         this.m_dsi,
858                         parentPath);
859
860                 if(m_logger.isLoggable(Level.FINE)) {
861                     m_logger.logp(Level.FINE, this.getClass().getName(), "delete", "default parent - " + defaultParentObj.getName());
862     
863                     m_logger.logp(Level.FINE, this.getClass().getName(), "delete"," current parent - " + parentObj.getName());
864                 }
865
866                 bArchive =
867                     parentObj.getFullPath().equals(
868                         defaultParentObj.getFullPath());
869             }
870
871             if (bArchive == true) {
872                 if(m_logger.isLoggable(Level.FINE)) {
873                     m_logger.logp(Level.FINE, this.getClass().getName(), "delete","Deleting " + m_child.getName());
874                 }
875                 
876                 User usr =
877                     ((HarmoniseSessionManager) m_resource.getUserAuthenticator())
878                         .getUser(m_resource);
879
880                 //do any auxilliary processing before deletion
881
if (m_auxillary != null) {
882                     m_auxillary.delete(usr, m_child);
883                 }
884
885                 CommandWrapper.archive(m_dsi, m_child, usr);
886
887             } else {
888                 if(m_logger.isLoggable(Level.FINE)) {
889                     m_logger.logp(Level.FINE, this.getClass().getName(), "delete","Removing child " + m_child.getName());
890                 }
891
892                 parentObj.removeChild(m_child);
893                 parentObj.save();
894             }
895
896             if(m_logger.isLoggable(Level.FINE)) {
897                 m_logger.logp(Level.FINE, this.getClass().getName(), "delete","Deleted");
898             }
899         } catch (Exception JavaDoc e) {
900             m_logger.log(Level.WARNING, "delete", e);
901             
902             throw new WebDAVException(
903                 WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
904                 e.getMessage());
905         }
906     }
907
908     /**
909      * @see com.ibm.webdav.impl.NamespaceManager#exists()
910      */

911     public boolean exists() throws WebDAVException {
912         boolean bExists = false;
913
914         if (m_child != null) {
915             if(m_logger.isLoggable(Level.FINE)) {
916                 m_logger.logp(Level.FINE, this.getClass().getName(), "exists","Checking " + m_child.getClass() + " " + m_child.getId());
917             }
918             
919             bExists = m_child.exists();
920         } else {
921             URL url = m_resource.getURL();
922             bExists = HarmoniseNameResolver.isVirtualCollection(url)
923                         || HarmoniseNameResolver.isArchivedVirtualCollection(url)
924                         || HarmoniseNameResolver.isVirtualResource(url);
925         }
926
927         if(m_logger.isLoggable(Level.FINE)) {
928             m_logger.logp(Level.FINE, this.getClass().getName(), "exists",m_resource.getURL().getPath() + " exists:" + bExists);
929         }
930
931         return bExists;
932     }
933
934     /**
935      * @see com.ibm.webdav.impl.NamespaceManager#getContentsInputStream()
936      */

937     public InputStream getContentsInputStream() throws WebDAVException {
938         InputStream is = null;
939
940         if (m_child == null) {
941             throw new WebDAVException(
942                 WebDAVStatus.SC_NOT_FOUND,
943                 "Resource does not exist");
944         }
945
946         long nResLength = 0;
947
948         if (m_child instanceof Asset) {
949             try {
950                 if(m_logger.isLoggable(Level.FINE)) {
951                     m_logger.logp(Level.FINE, this.getClass().getName(), "getContentsInputStream","Getting inputstream for Asset");
952                 }
953
954                 Asset asset = (Asset) m_child;
955
956                 if (isAssetSavedAsText(asset.getContentType()) == true) {
957                     String JavaDoc sContent = asset.getURI();
958                     is =
959                         new BufferedInputStream(
960                             new ByteArrayInputStream(sContent.getBytes(HarmoniseNameResolver.UTF_8)));
961
962                     nResLength = sContent.getBytes().length;
963                 } else {
964                     File file = asset.getContentFile();
965                     
966                     if(m_logger.isLoggable(Level.FINE)) {
967                         m_logger.logp(Level.FINE, this.getClass().getName(), "getContentsInputStream","Asset file name - " + file.getAbsolutePath());
968                     }
969
970                     is =
971                         new BufferedInputStream(
972                             new FileInputStream(file),
973                             bufferSize);
974
975                     nResLength = file.length();
976                 }
977
978                 m_resource.getResponseContext().contentType(
979                     asset.getContentType());
980
981                 String JavaDoc cdstring =
982                     new SimpleRFC1123DateFormat().format(new Date());
983                 m_resource.getResponseContext().lastModified(cdstring);
984                 m_resource.getResponseContext().contentLength(nResLength);
985             } catch (Exception JavaDoc e) {
986                 m_logger.log(Level.WARNING, "getContentsInputStream", e);
987             
988                 throw new WebDAVException(
989                     WebDAVStatus.SC_SERVICE_UNAVAILABLE,
990                     "Had problem creating asset input stream");
991             }
992         } else if (m_child instanceof TextResource) {
993             try {
994                 if(m_logger.isLoggable(Level.FINE)) {
995                     m_logger.logp(Level.FINE, this.getClass().getName(), "getContentsInputStream","Getting inputstream for Document");
996                 }
997                 
998                 TextResource textResource = (TextResource) m_child;
999                 User usr =
1000                    ((HarmoniseSessionManager) m_resource.getUserAuthenticator())
1001                        .getUser(m_resource);
1002
1003                String JavaDoc sContent = null;
1004                if(m_auxillary != null) {
1005                    // get the content by calling the auxiliary process manager
1006
// it will only pre-process the content if the status is
1007
// approved and the textResource is either a
1008
// Template or XMLResource
1009

1010                    sContent = m_auxillary.getContent(
1011                             usr,
1012                             textResource,
1013                             textResource.getStatus());
1014                } else {
1015                    sContent = textResource.getContent();
1016                }
1017                
1018                if(sContent != null) {
1019                    is =
1020                        new BufferedInputStream(
1021                            new ByteArrayInputStream(
1022                                sContent.getBytes(HarmoniseNameResolver.UTF_8),
1023                                0,
1024                                sContent.getBytes(HarmoniseNameResolver.UTF_8).length),
1025                                bufferSize);
1026                } else {
1027                    //return an input stream for the empty string
1028
is = new ByteArrayInputStream("".getBytes());
1029                }
1030                
1031
1032                // get the content type. Default to text/plain
1033
//String contentType = doc.GetDocumentType();
1034
String JavaDoc sContentType = textResource.getContentType();
1035
1036                if (sContentType == null
1037                    && textResource instanceof XMLResource) {
1038                    sContentType = MimeTypeMapping.XML.getMimeType();
1039                }
1040
1041                m_resource.getResponseContext().contentType(sContentType);
1042
1043                String JavaDoc cdstring =
1044                    new SimpleRFC1123DateFormat().format(
1045                        textResource.getVersionDate());
1046                m_resource.getResponseContext().lastModified(cdstring);
1047            } catch (Exception JavaDoc e) {
1048                m_logger.log(Level.WARNING, "getContentsInputStream", e);
1049            
1050                throw new WebDAVException(
1051                    WebDAVStatus.SC_SERVICE_UNAVAILABLE,
1052                    "Had problem creating document input stream");
1053            }
1054        } else if (m_child instanceof WebPage) {
1055            WebPageResourceAdapter page = new WebPageResourceAdapter((WebPage) m_child);
1056
1057            String JavaDoc sXML = page.asString();
1058
1059            is =
1060                new BufferedInputStream(
1061                    new ByteArrayInputStream(sXML.getBytes(), 0, sXML.length()),
1062                    bufferSize);
1063
1064            m_resource.getResponseContext().contentType(
1065                MimeTypeMapping.XML.getMimeType());
1066
1067        } else if (m_child instanceof AbstractParentObject) {
1068            AbstractParentObject parent = (AbstractParentObject) m_child;
1069
1070            if (parent != null) {
1071                m_resource.getResponseContext().contentType(
1072                    MimeTypeMapping.XML.getMimeType());
1073                is = parentToXMLStream(parent);
1074            }
1075        }
1076
1077        return is;
1078    }
1079
1080    /**
1081     * @see com.ibm.webdav.impl.NamespaceManager#getContentsOutputStream()
1082     */

1083    public OutputStream getContentsOutputStream() throws WebDAVException {
1084        OutputStream os = null;
1085        
1086        User usr =
1087            ((HarmoniseSessionManager) m_resource.getUserAuthenticator())
1088                .getUser(m_resource);
1089        
1090        try {
1091            String JavaDoc sPath = m_resource.getURL().getPath();
1092            String JavaDoc sChildClass = null;
1093
1094            if (HarmoniseNameResolver.isVersionPath(sPath) == true) {
1095                sChildClass = HarmoniseNameResolver.getTypeFromVersionURL(sPath);
1096            } else {
1097                sChildClass = HarmoniseNameResolver.getChildTypeFromURL(sPath);
1098            }
1099
1100            Class JavaDoc clss = Class.forName(sChildClass);
1101            
1102            if((m_child != null && CommandWrapper.isSaveAllowed(usr,m_child) == false)
1103                || (m_child == null && CommandWrapper.isSaveAllowed(usr,clss) == false)) {
1104                throw new WebDAVException(WebDAVStatus.SC_FORBIDDEN, "User is not allowed to save resource");
1105            }
1106            
1107            //ensure that if this is a new property it's name doesn't start
1108
//with a numeric character
1109
if(m_child == null && Property.class.isAssignableFrom(clss)) {
1110                String JavaDoc sName = null;
1111                try {
1112                    sName = HarmoniseNameResolver.getResourceName(m_resource.getURL());
1113                } catch (UnsupportedEncodingException e) {
1114                    throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR,e.getLocalizedMessage());
1115                }
1116                
1117                if(Character.isDigit(sName.charAt(0)) == true) {
1118                    throw new WebDAVException(WebDAVStatus.SC_BAD_REQUEST, "Invalid property name - not allowed digit as first character");
1119                }
1120            }
1121
1122            String JavaDoc contentType =
1123                m_resource.getContext().getRequestContext().contentType();
1124
1125            if (Asset.class.isAssignableFrom(clss)) {
1126                if (isAssetSavedAsText(contentType) == true) {
1127                    os = new ByteArrayOutputStream();
1128                } else {
1129                    try {
1130                        String JavaDoc fileName =
1131                            HarmoniseNameResolver.getFilePath(m_resource.getURL());
1132
1133                        if(m_logger.isLoggable(Level.FINE)) {
1134                            m_logger.logp(Level.FINE, this.getClass().getName(), "getContentsOutputStream", "Returning buffered FileOutputStream for file: "
1135                                    + fileName);
1136                        }
1137
1138                        File file = new File(fileName);
1139                        os =
1140                            new BufferedOutputStream(
1141                                new FileOutputStream(file),
1142                                bufferSize);
1143                    } catch (NameResolverException e) {
1144                        m_logger.log(Level.WARNING, "getContentsOutputStream", e);
1145            
1146                        throw new WebDAVException(
1147                            WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1148                            "problem opening outputstream");
1149                    } catch (FileNotFoundException e) {
1150                        m_logger.log(Level.WARNING, "getContentsOutputStream", e);
1151            
1152                        throw new WebDAVException(
1153                            WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1154                            "problem opening outputstream");
1155                    }
1156                }
1157            } else if (TextResource.class.isAssignableFrom(clss)) {
1158                if(m_logger.isLoggable(Level.FINE)) {
1159                    m_logger.logp(Level.FINE, this.getClass().getName(), "getContentsOutputStream", "Returning buffered ByteArrayOutputStream");
1160                }
1161                
1162                os = new ByteArrayOutputStream();
1163            } else {
1164                os = new ByteArrayOutputStream();
1165            }
1166        } catch (NameResolverException e) {
1167            throw new WebDAVException(
1168                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1169                e.getLocalizedMessage());
1170        } catch (ClassNotFoundException JavaDoc e) {
1171            throw new WebDAVException(
1172                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1173                e.getLocalizedMessage());
1174        }
1175
1176        m_openedOutputStream = os;
1177
1178        return os;
1179    }
1180
1181    /**
1182     * @see com.ibm.webdav.impl.NamespaceManager#getMembers()
1183     */

1184    public Vector getMembers() throws WebDAVException {
1185        Vector members = new Vector();
1186        String JavaDoc parentName =
1187            m_resource.getName().replace(File.separatorChar, '/');
1188
1189        if (HarmoniseNameResolver.isVersionPath(parentName) == true
1190            && m_child != null) {
1191            try {
1192                parentName = HarmoniseNameResolver.getDAVPath(m_child);
1193            } catch (NameResolverException e) {
1194                throw new WebDAVException(
1195                    WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1196                    e.getLocalizedMessage());
1197            }
1198        }
1199
1200        if ((parentName != null) && !parentName.endsWith("/")) {
1201            parentName = parentName + "/";
1202        }
1203
1204        if (parentName == null) {
1205            parentName = "";
1206        }
1207
1208        AbstractParentObject grpObj = null;
1209
1210        try {
1211            grpObj = (AbstractParentObject) m_child;
1212        } catch (ClassCastException JavaDoc e) {
1213            throw new WebDAVException(
1214                WebDAVStatus.SC_BAD_REQUEST,
1215                "resource not a collection");
1216        }
1217
1218        URL resourceURL = m_resource.getURL();
1219
1220        try {
1221            if (grpObj == null) {
1222
1223                if (HarmoniseNameResolver.isDAVRoot(resourceURL) == true) {
1224
1225                    List rootParents = HarmoniseNameResolver.getRootCollections();
1226
1227                    Iterator iter = rootParents.iterator();
1228
1229                    while (iter.hasNext()) {
1230                        members.addElement(
1231                            createNewVirtualCollection(
1232                                parentName,
1233                                (String JavaDoc) iter.next()));
1234                    }
1235                    members.addElement(
1236                        createNewVirtualCollection(
1237                            parentName,
1238                            HarmoniseNameResolver.ARCHIVE_NAME));
1239
1240                } else if (
1241                    HarmoniseNameResolver.isArchiveRoot(resourceURL) == true) {
1242                    List rootParents = HarmoniseNameResolver.getRootCollections();
1243
1244                    Iterator iter = rootParents.iterator();
1245
1246                    while (iter.hasNext()) {
1247                        members.addElement(
1248                            createNewVirtualCollection(
1249                                parentName,
1250                                (String JavaDoc) iter.next()));
1251                    }
1252                } else if (
1253                    HarmoniseNameResolver.isVirtualCollection(resourceURL) == true) {
1254                    List vmembers = null;
1255
1256                    if (HarmoniseNameResolver.isArchiveURL(resourceURL) == true) {
1257                        vmembers =
1258                            HarmoniseNameResolver
1259                                .getArchivedVirtualCollectionMemberNames(
1260                                resourceURL);
1261                    } else {
1262                        vmembers =
1263                            HarmoniseNameResolver.getVirtualCollectionMemberNames(
1264                                resourceURL);
1265                    }
1266
1267                    Iterator iter = vmembers.iterator();
1268
1269                    while (iter.hasNext()) {
1270                        members.addElement(
1271                            createNewVirtualCollection(
1272                                parentName,
1273                                (String JavaDoc) iter.next()));
1274                    }
1275                } else if (
1276                    HarmoniseNameResolver.isArchivedVirtualCollection(resourceURL)
1277                        == true) {
1278                    List vmembers =
1279                        HarmoniseNameResolver
1280                            .getArchivedVirtualCollectionMemberNames(
1281                            resourceURL);
1282
1283                    Iterator iter = vmembers.iterator();
1284
1285                    while (iter.hasNext()) {
1286                        members.addElement(
1287                            createNewVirtualCollection(
1288                                parentName,
1289                                (String JavaDoc) iter.next()));
1290                    }
1291                }
1292
1293            } else {
1294                List children = null;
1295                Vector subgroups = new Vector();
1296
1297                if (HarmoniseNameResolver.isArchiveURL(resourceURL) == true) {
1298                    children = grpObj.getArchivedChildren();
1299
1300                    children.addAll(
1301                        grpObj.getChildrenByType(
1302                            AbstractParentObject.BRANCH_NODES));
1303
1304                    if(m_logger.isLoggable(Level.FINE)) {
1305                        m_logger.logp(Level.FINE, this.getClass().getName(), "getMembers", "Got " + children.size() + " archived children");
1306                    }
1307                } else {
1308                    children = grpObj.getChildren();
1309                }
1310
1311                Iterator iter = children.iterator();
1312
1313                while (iter.hasNext()) {
1314                    AbstractChildObject child =
1315                        (AbstractChildObject) iter.next();
1316
1317                    StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc();
1318                    sbuf.append(child.getName());
1319
1320                    String JavaDoc sMemberName = sbuf.toString();
1321
1322                    // add resources and lock-null resources
1323
String JavaDoc childName = parentName + sMemberName;
1324                    
1325                    if(m_logger.isLoggable(Level.FINE)) {
1326                        m_logger.logp(Level.FINE, this.getClass().getName(), "getMembers", "adding document:"
1327                                + childName
1328                                + "("
1329                                + child.hashCode()
1330                                + ")");
1331                    }
1332
1333                    ResourceImpl member = null;
1334
1335                    if (child instanceof AbstractParentObject) {
1336                        member =
1337                            new CollectionImpl(
1338                                getChildURL(sMemberName),
1339                                childName,
1340                                null);
1341
1342                    } else {
1343                        member =
1344                            new ResourceImpl(
1345                                getChildURL(sMemberName),
1346                                childName);
1347                    }
1348
1349                    member.setRequestContext(m_resource.getContext());
1350                    members.addElement(member);
1351                }
1352            }
1353        } catch (DataAccessException e) {
1354            m_logger.log(Level.WARNING, "getMembers", e);
1355            
1356            throw new WebDAVException(
1357                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1358                e.getLocalizedMessage());
1359        }
1360
1361        return members;
1362    }
1363
1364    /**
1365     *
1366     */

1367    private URL getChildURL(String JavaDoc sChildName) throws WebDAVException {
1368        URL childURL = null;
1369
1370        String JavaDoc parentName =
1371            m_resource.getName().replace(File.separatorChar, '/');
1372
1373        try {
1374            if (HarmoniseNameResolver.isVersionPath(parentName) == true
1375                && m_child != null) {
1376                URL resourceURL = m_resource.getURL();
1377                StringBuffer JavaDoc sParentURL = new StringBuffer JavaDoc();
1378                sParentURL.append(resourceURL.getProtocol());
1379                sParentURL.append("://");
1380                sParentURL.append(resourceURL.getHost());
1381                sParentURL.append(":");
1382                sParentURL.append(resourceURL.getPort());
1383                sParentURL.append("/");
1384                sParentURL.append(HarmoniseNameResolver.getDAVPath(m_child));
1385                if (sParentURL.toString().endsWith("/") == false) {
1386                    sParentURL.append("/");
1387                }
1388
1389                childURL = new URL(sParentURL.append(sChildName).toString());
1390
1391            } else {
1392                childURL =
1393                    ((CollectionImpl) m_resource).getChildURL(
1394                        URLEncoder.encode(sChildName, HarmoniseNameResolver.UTF_8));
1395            }
1396        } catch (MalformedURLException e) {
1397            throw new WebDAVException(
1398                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1399                e.getLocalizedMessage());
1400        } catch (NameResolverException e) {
1401            throw new WebDAVException(
1402                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1403                e.getLocalizedMessage());
1404        } catch (UnsupportedEncodingException e) {
1405            throw new WebDAVException(
1406                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1407                e.getLocalizedMessage());
1408        }
1409
1410        return childURL;
1411
1412    }
1413
1414    /**
1415     * Creates new virtual collection, i.e. a collection represented in the DAV hierarchy
1416     * that does not have an equivalent Harmonise parent object
1417     *
1418     * @param parentName
1419     * @param sColName
1420     * @return
1421     * @throws WebDAVException
1422     */

1423    private CollectionImpl createNewVirtualCollection(
1424        String JavaDoc parentName,
1425        String JavaDoc sColName)
1426        throws WebDAVException {
1427        CollectionImpl collection = null;
1428
1429        collection =
1430            new CollectionImpl(
1431                ((CollectionImpl) m_resource).getChildURL(sColName),
1432                parentName + sColName,
1433                null);
1434
1435        collection.setRequestContext(m_resource.getContext());
1436
1437        return collection;
1438    }
1439
1440    /**
1441     * @see com.ibm.webdav.impl.NamespaceManager#initialize(com.ibm.webdav.impl.ResourceImpl)
1442     */

1443    public void initialize(ResourceImpl resource) {
1444        this.m_resource = resource;
1445
1446        try {
1447            this.m_dsi = DataStoreInterfaceFactory.getDataStoreInterface();
1448
1449            URL resourceURL = m_resource.getURL();
1450
1451            if (HarmoniseNameResolver.isDAVRoot(resourceURL) == false
1452                && HarmoniseNameResolver.isVirtualCollection(resourceURL) == false) {
1453                m_child = HarmoniseNameResolver.getObjectFromURL(m_dsi, resourceURL);
1454            }
1455
1456            if (m_auxillary == null) {
1457                m_auxillary = APMFactory.getAPM();
1458            }
1459        } catch (Exception JavaDoc e) {
1460            m_logger.log(Level.WARNING, "initialize", e);
1461        }
1462    }
1463
1464    /**
1465     * @see com.ibm.webdav.impl.NamespaceManager#isCollection()
1466     */

1467    public boolean isCollection() throws WebDAVException {
1468        boolean bRtn = false;
1469
1470        if (m_child != null) {
1471            bRtn = m_child instanceof AbstractParentObject;
1472        } else {
1473            URL resourceURL = m_resource.getURL();
1474            bRtn = HarmoniseNameResolver.isVirtualCollection(resourceURL) || HarmoniseNameResolver.isArchivedVirtualCollection(resourceURL);
1475        }
1476
1477        if(m_logger.isLoggable(Level.FINE)) {
1478            m_logger.logp(Level.FINE, this.getClass().getName(), "isCollection","Is collection - " + bRtn);
1479        }
1480
1481        return bRtn;
1482    }
1483
1484    /**
1485     * @see com.ibm.webdav.impl.NamespaceManager#isLockNull()
1486     */

1487    public boolean isLockNull() throws WebDAVException {
1488        return false;
1489    }
1490
1491    /**
1492     * @see com.ibm.webdav.impl.NamespaceManager#performWith(java.lang.String)
1493     */

1494    public byte[] performWith(String JavaDoc args) throws WebDAVException {
1495        StringWriter buf = new StringWriter();
1496
1497        try {
1498            Runtime JavaDoc runtime = Runtime.getRuntime();
1499            Process JavaDoc p = runtime.exec(m_resource.getName() + " " + args);
1500            BufferedReader inputStream =
1501                new BufferedReader(new InputStreamReader(p.getInputStream()));
1502            int ch = -1;
1503
1504            while ((ch = inputStream.read()) != -1) {
1505                buf.write(ch);
1506            }
1507        } catch (Exception JavaDoc e) {
1508            m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
1509        }
1510
1511        return buf.toString().getBytes();
1512    }
1513
1514    /** Create an XML file containing the contents of a collection.
1515    * @param file the directory to read
1516    * @return an InputStream on the resulting XML file.
1517    * @exception com.ibm.webdav.WebDAVException
1518    */

1519    private InputStream parentToXMLStream(AbstractParentObject parent)
1520        throws WebDAVException {
1521        org.w3c.dom.Document JavaDoc document = null;
1522
1523        try {
1524            document =
1525                DocumentBuilderFactory
1526                    .newInstance()
1527                    .newDocumentBuilder()
1528                    .newDocument();
1529        } catch (Exception JavaDoc e) {
1530            throw new WebDAVException(
1531                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1532                e.getMessage());
1533        }
1534
1535        Element collection = document.createElement("D:collection");
1536        collection.setAttribute("xmlns:D", "DAV:");
1537        document.appendChild(collection);
1538
1539        try {
1540            List children = parent.getChildren();
1541
1542            Iterator iter = children.iterator();
1543
1544            while (iter.hasNext()) {
1545                AbstractChildObject child = (AbstractChildObject) iter.next();
1546                String JavaDoc docName = child.getName();
1547
1548                // add resources and lock-null resources
1549
Element uri = document.createElement("D:member");
1550                uri.appendChild(document.createTextNode(docName));
1551                collection.appendChild(uri);
1552            }
1553        } catch (DataAccessException e) {
1554            throw new WebDAVException(
1555                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1556                e.getLocalizedMessage());
1557        }
1558
1559        ByteArrayOutputStream os = new ByteArrayOutputStream();
1560
1561        try {
1562            PrintWriter pout =
1563                    new PrintWriter(
1564                        new OutputStreamWriter(os, Resource.defaultCharEncoding),
1565                        false);
1566            pout.print(XMLUtility.printNode(document.getDocumentElement()));
1567        } catch (UnsupportedEncodingException e) {
1568            m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
1569            throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR,e.getMessage());
1570        }
1571
1572        m_resource.getResponseContext().contentType("text/xml");
1573
1574        return new ByteArrayInputStream(os.toByteArray());
1575    }
1576
1577
1578    /**
1579     * @see com.ibm.webdav.impl.NamespaceManager#isVersionable()
1580     */

1581    public boolean isVersionable() throws WebDAVException {
1582        return false;
1583    }
1584
1585
1586    /**
1587     * @see com.ibm.webdav.impl.NamespaceManager#getAllowedMethods()
1588     */

1589    public List getAllowedMethods() throws WebDAVException {
1590        List allowedMethods = null;
1591
1592        if (HarmoniseNameResolver.isVirtualCollection(m_resource.getURL()) == true) {
1593            allowedMethods = new ArrayList(VIRTUAL_DIR_ALLOWED_METHODS);
1594        }
1595        if (HarmoniseNameResolver.isArchivedVirtualCollection(m_resource.getURL())
1596            == true) {
1597            allowedMethods = new ArrayList(VIRTUAL_DIR_ALLOWED_METHODS);
1598        } else if (
1599            HarmoniseNameResolver.isArchiveURL(m_resource.getURL()) == true
1600                || (m_child != null && m_child.isHistorical())) {
1601            allowedMethods = new ArrayList(ARCHIVE_ALLOWED_METHODS);
1602            try {
1603                AbstractChildObject liveChild =
1604                    (AbstractChildObject) m_child.getLiveVersion();
1605                if ((m_child instanceof AbstractParentObject) == false) {
1606                    if (liveChild == null
1607                        || liveChild.getPendingVersions().size() == 0) {
1608                        allowedMethods.add(CheckOutMethod.METHOD_NAME);
1609                    }
1610                }
1611            } catch (DataAccessException e) {
1612                throw new WebDAVException(
1613                    WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1614                    e.getLocalizedMessage());
1615            }
1616        } else {
1617
1618            allowedMethods = new Vector(STD_ALLOWED_METHODS);
1619
1620            if (m_child instanceof AbstractParentObject) {
1621                allowedMethods.add(OrderPatchMethod.METHOD_NAME);
1622                allowedMethods.add(MkcolMethod.METHOD_NAME);
1623            }
1624
1625            allowedMethods = filterAllowedMethods(allowedMethods);
1626        }
1627
1628        return allowedMethods;
1629    }
1630
1631    /**
1632     * Filters the list of methods allowed given the state of the resource by the
1633     * permissions given by role based security
1634     *
1635     * @param allowedMethods
1636     * @return
1637     */

1638    protected List filterAllowedMethods(List allowedMethods)
1639        throws WebDAVException {
1640        List filteredList = new Vector();
1641
1642        User usr =
1643            ((HarmoniseSessionManager) m_resource.getUserAuthenticator()).getUser(m_resource);
1644
1645        Iterator iter = allowedMethods.iterator();
1646
1647        while (iter.hasNext()) {
1648            String JavaDoc sMethod = (String JavaDoc) iter.next();
1649
1650            if (VIRTUAL_DIR_ALLOWED_METHODS.contains(sMethod)) {
1651                filteredList.add(sMethod);
1652            } else {
1653                String JavaDoc sCmd = (String JavaDoc) DAV_HARMONISE_COMMAND_MAPPING.get(sMethod);
1654
1655                if (sCmd != null) {
1656                    try {
1657                        if (AuthorizationValidator
1658                            .isCommandAvailable(usr, m_child, sCmd)
1659                            == true) {
1660                            filteredList.add(sMethod);
1661                        }
1662                    } catch (AuthorizationException e) {
1663                        //assume that we're not allowing the method and move on
1664
m_logger.log(Level.WARNING, "filterAllowedMethods", e);
1665                    }
1666                }
1667
1668            }
1669
1670        }
1671
1672        return filteredList;
1673    }
1674
1675    /**
1676     * @see com.ibm.webdav.impl.NamespaceManager#setOrdering(org.w3c.dom.Document)
1677     */

1678    public void setOrdering(org.w3c.dom.Document JavaDoc orderPatch)
1679        throws WebDAVException {
1680
1681        if (m_child == null) {
1682            throw new WebDAVException(
1683                WebDAVStatus.SC_NOT_FOUND,
1684                "Resource not a collection");
1685        }
1686
1687        if ((m_child instanceof AbstractParentObject) == false) {
1688            throw new WebDAVException(
1689                WebDAVStatus.SC_BAD_REQUEST,
1690                "Resource not a collection");
1691        }
1692
1693        try {
1694            AbstractParentObject parent = (AbstractParentObject) m_child;
1695
1696            Element orderEl = orderPatch.getDocumentElement();
1697
1698            NodeList nodes =
1699                orderEl.getElementsByTagNameNS(
1700                    NamespaceType.DAV.getURI(),
1701                    TAG_ORDER_MEMBER);
1702
1703            LinkedList children = new LinkedList(parent.getChildren());
1704
1705            for (int i = 0; i < nodes.getLength(); i++) {
1706                Element tmpEl = (Element) nodes.item(i);
1707
1708                Element segmentEl =
1709                    (Element) tmpEl
1710                        .getElementsByTagNameNS(
1711                            NamespaceType.DAV.getURI(),
1712                            TAG_SEGMENT)
1713                        .item(0);
1714                Element positionEl =
1715                    (Element) tmpEl
1716                        .getElementsByTagNameNS(
1717                            NamespaceType.DAV.getURI(),
1718                            TAG_POSITION)
1719                        .item(0);
1720
1721                String JavaDoc sChildName =
1722                    segmentEl.getChildNodes().item(0).getNodeValue();
1723
1724                sChildName = HarmoniseNameResolver.stripExtension(sChildName);
1725
1726                AbstractChildObject child = parent.getChildByName(sChildName);
1727
1728                if (child == null) {
1729                    throw new WebDAVException(
1730                        WebDAVStatus.SC_FORBIDDEN,
1731                        sChildName + " is not a collection member");
1732                }
1733
1734                Element specEl = XMLUtils.getFirstElementChild(positionEl);
1735
1736                String JavaDoc sSpecifier = specEl.getLocalName();
1737
1738                //remove child before adding again in new position
1739
children.remove(child);
1740                if (sSpecifier.equals(TAG_FIRST)) {
1741                    children.addFirst(child);
1742                } else if (sSpecifier.equals(TAG_LAST)) {
1743                    children.addLast(child);
1744                } else if (sSpecifier.equals(TAG_BEFORE)) {
1745                    String JavaDoc sBeforeChildName =
1746                        specEl
1747                            .getElementsByTagNameNS(
1748                                NamespaceType.DAV.getURI(),
1749                                TAG_SEGMENT)
1750                            .item(0)
1751                            .getChildNodes()
1752                            .item(0)
1753                            .getNodeValue();
1754                    sBeforeChildName =
1755                        HarmoniseNameResolver.stripExtension(sBeforeChildName);
1756
1757                    AbstractChildObject sBeforeChild =
1758                        parent.getChildByName(sBeforeChildName);
1759
1760                    int nIndex = children.indexOf(sBeforeChild);
1761                    children.add(nIndex, child);
1762
1763                } else if (sSpecifier.equals(TAG_AFTER)) {
1764                    String JavaDoc sAfterChildName =
1765                        specEl
1766                            .getElementsByTagNameNS(
1767                                NamespaceType.DAV.getURI(),
1768                                TAG_SEGMENT)
1769                            .item(0)
1770                            .getChildNodes()
1771                            .item(0)
1772                            .getNodeValue();
1773                    sAfterChildName =
1774                        HarmoniseNameResolver.stripExtension(sAfterChildName);
1775
1776                    AbstractChildObject sAfterChild =
1777                        parent.getChildByName(sAfterChildName);
1778
1779                    int nIndex = children.indexOf(sAfterChild);
1780                    children.add(nIndex + 1, child);
1781                }
1782
1783            }
1784
1785            if(m_logger.isLoggable(Level.FINE)) {
1786                m_logger.logp(Level.FINE, this.getClass().getName(), "setOrdering", "New order - " + children);
1787            }
1788
1789            //now save changes to parent
1790
parent.setChildren(children);
1791
1792            CommandWrapper.save(
1793                m_dsi,
1794                parent,
1795                ((HarmoniseSessionManager) m_resource.getUserAuthenticator())
1796                    .getUser(m_resource));
1797
1798        } catch (DataAccessException e) {
1799            throw new WebDAVException(
1800                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1801                e.getLocalizedMessage());
1802        } catch (InvalidChildException e) {
1803            throw new WebDAVException(
1804                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1805                e.getLocalizedMessage());
1806        } catch (PopulateException e) {
1807            throw new WebDAVException(
1808                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1809                e.getLocalizedMessage());
1810        }
1811
1812    }
1813
1814    /**
1815     * @see com.ibm.webdav.impl.VersionedNamespaceManager#isVersionURL(java.lang.String)
1816     */

1817    public boolean isVersionURL(String JavaDoc url) {
1818
1819        return HarmoniseNameResolver.isVersionPath(url);
1820    }
1821
1822    /**
1823     * @see com.ibm.webdav.impl.VersionedNamespaceManager#getResourceURL()
1824     */

1825    public String JavaDoc getResourceURL() throws WebDAVException {
1826        String JavaDoc sPath = null;
1827
1828        try {
1829            sPath = HarmoniseNameResolver.getDAVPath(m_child);
1830        } catch (NameResolverException e) {
1831            throw new WebDAVException(
1832                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1833                e.getLocalizedMessage());
1834        }
1835
1836        return sPath;
1837    }
1838
1839    /**
1840     * @see com.ibm.webdav.impl.NamespaceManager#getContentType()
1841     */

1842    public String JavaDoc getContentType() throws WebDAVException {
1843        String JavaDoc sContentType = null;
1844
1845        try {
1846            if (m_child instanceof Asset) {
1847                sContentType = ((Asset) m_child).getContentType();
1848            } else if (m_child instanceof TextResource) {
1849                sContentType = ((TextResource) m_child).getContentType();
1850            }
1851        } catch (DataAccessException e) {
1852            throw new WebDAVException(
1853                WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
1854                e.getLocalizedMessage());
1855        }
1856
1857        return sContentType;
1858    }
1859
1860    private String JavaDoc getOutputStreamAsString() throws IOException {
1861        byte[] byteArray =
1862            ((ByteArrayOutputStream) m_openedOutputStream).toByteArray();
1863        int length = byteArray.length;
1864
1865        ByteArrayInputStream byteInputStream =
1866            new ByteArrayInputStream(byteArray);
1867        BufferedReader reader =
1868            new BufferedReader(new InputStreamReader(byteInputStream, HarmoniseNameResolver.UTF_8));
1869
1870        char[] cbuf = new char[bufferSize];
1871        String JavaDoc sNewContents = "";
1872        StringWriter writer = new StringWriter();
1873
1874        String JavaDoc temp = "";
1875        while ((temp = reader.readLine()) != null) {
1876            writer.write(temp);
1877        }
1878
1879        String JavaDoc sResult = writer.toString();
1880        
1881        if(m_logger.isLoggable(Level.FINE)) {
1882            m_logger.logp(Level.FINE, this.getClass().getName(), "getOutputStreamAsString", "New doc contents: " + sResult);
1883        }
1884        
1885        return sResult;
1886    }
1887
1888    /**
1889     * Returns <code>true</code> if asset is to be saved as text in database rather
1890     * than file, given content type
1891     *
1892     * @param sContentType
1893     * @return
1894     */

1895    private boolean isAssetSavedAsText(String JavaDoc sContentType) {
1896        boolean bIsFile = false;
1897
1898        bIsFile =
1899            (sContentType != null
1900                && MimeTypeMapping.XSLT.getMimeTypes().contains(sContentType)
1901                    == false
1902                && (sContentType.startsWith("link")
1903                    || sContentType.startsWith("text")));
1904
1905        return bIsFile;
1906    }
1907
1908}
Popular Tags