KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > importexport > ImportExportBaseService


1 package org.jahia.services.importexport;
2
3 import org.apache.commons.id.IdentifierGenerator;
4 import org.apache.commons.id.IdentifierGeneratorFactory;
5 import org.apache.commons.lang.StringUtils;
6 import org.apache.xerces.dom.DocumentImpl;
7 import org.apache.xerces.util.XMLChar;
8 import org.apache.xml.utils.DOMBuilder;
9 import org.jahia.bin.Jahia;
10 import org.jahia.bin.JahiaInterface;
11 import org.jahia.content.*;
12 import org.jahia.data.applications.ApplicationBean;
13 import org.jahia.data.applications.ApplicationContext;
14 import org.jahia.data.containers.JahiaContainerDefinition;
15 import org.jahia.data.fields.JahiaApplicationField;
16 import org.jahia.data.fields.JahiaFieldDefinition;
17 import org.jahia.exceptions.JahiaException;
18 import org.jahia.exceptions.JahiaPageNotFoundException;
19 import org.jahia.params.ParamBean;
20 import org.jahia.registries.ServicesRegistry;
21 import org.jahia.services.JahiaService;
22 import org.jahia.services.acl.ACLNotFoundException;
23 import org.jahia.services.acl.JahiaACLEntry;
24 import org.jahia.services.acl.JahiaACLException;
25 import org.jahia.services.acl.JahiaBaseACL;
26 import org.jahia.services.categories.Category;
27 import org.jahia.services.categories.CategoryService;
28 import org.jahia.services.containers.ContentContainer;
29 import org.jahia.services.containers.ContentContainerList;
30 import org.jahia.services.fields.*;
31 import org.jahia.services.pages.ContentPage;
32 import org.jahia.services.pages.JahiaPage;
33 import org.jahia.services.pages.JahiaPageDefinition;
34 import org.jahia.services.pages.PageProperty;
35 import org.jahia.services.sites.JahiaSite;
36 import org.jahia.services.sites.JahiaSitesService;
37 import org.jahia.services.sites.SiteLanguageSettings;
38 import org.jahia.services.sites.SiteLanguageMapping;
39 import org.jahia.services.usermanager.*;
40 import org.jahia.services.version.ContentObjectEntryState;
41 import org.jahia.services.version.EntryLoadRequest;
42 import org.jahia.services.version.VersioningDifferenceStatus;
43 import org.jahia.services.webdav.DAVFileAccess;
44 import org.jahia.utils.LanguageCodeConverters;
45 import org.w3c.dom.Document JavaDoc;
46 import org.xml.sax.ContentHandler JavaDoc;
47 import org.xml.sax.SAXException JavaDoc;
48 import org.xml.sax.helpers.AttributesImpl JavaDoc;
49
50 import java.io.*;
51 import java.security.Principal JavaDoc;
52 import java.text.DateFormat JavaDoc;
53 import java.text.SimpleDateFormat JavaDoc;
54 import java.util.*;
55 import java.util.regex.Pattern JavaDoc;
56 import java.util.regex.Matcher JavaDoc;
57 import java.util.zip.ZipEntry JavaDoc;
58 import java.util.zip.ZipOutputStream JavaDoc;
59
60 /**
61  * Created by IntelliJ IDEA.
62  * User: toto
63  * Date: 9 d�c. 2004
64  * Time: 15:01:31
65  * To change this template use File | Settings | File Templates.
66  */

67 public class ImportExportBaseService extends JahiaService implements ImportExportService {
68
69     private static org.apache.log4j.Logger logger =
70             org.apache.log4j.Logger.getLogger(ImportExportBaseService.class);
71
72     private static ImportExportBaseService instance;
73
74     private static IdentifierGenerator idGen;
75     public static final SimpleDateFormat JavaDoc DATE_FORMAT = new SimpleDateFormat JavaDoc("yyyyMMddHHmm");
76     private static final String JavaDoc GHOST = "GHOST";
77
78     private JahiaSitesService sitesService;
79     private JahiaUserManagerService userManagerService;
80     private JahiaGroupManagerService groupManagerService;
81     private CategoryService categoryService;
82
83     private List structRelations;
84
85     private Map uuids = new HashMap();
86
87     public static synchronized ImportExportBaseService getInstance() {
88         if (instance == null) {
89             instance = new ImportExportBaseService();
90         }
91         return instance;
92     }
93
94     protected ImportExportBaseService() {
95         idGen = IdentifierGeneratorFactory.newInstance().uuidVersionFourGenerator();
96         sitesService = ServicesRegistry.getInstance().getJahiaSitesService();
97         userManagerService = ServicesRegistry.getInstance().getJahiaUserManagerService();
98         groupManagerService = ServicesRegistry.getInstance().getJahiaGroupManagerService();
99         categoryService = ServicesRegistry.getInstance().getCategoryService();
100
101         structRelations = new ArrayList();
102         structRelations.add("category");
103         structRelations.add("reference");
104         structRelations.add("hardcodedLink");
105     }
106
107     public Document JavaDoc exportDocument(ContentObject object, String JavaDoc languageCodes, ParamBean jParams, Map params) throws JahiaException, SAXException JavaDoc {
108         DocumentImpl doc = new DocumentImpl();
109         DOMBuilder db = new DOMBuilder(doc, doc);
110         export(object, languageCodes, db, new HashSet(), jParams, params);
111         return doc;
112     }
113
114     public void exportFile(ContentObject object, String JavaDoc languageCode, OutputStream JavaDoc out, ParamBean jParams, Map params) throws JahiaException, SAXException JavaDoc, IOException {
115         DataWriter dw = new DataWriter(new OutputStreamWriter(out, "UTF-8"));
116         export(object, languageCode, dw, new HashSet(), jParams, params);
117     }
118
119     private void getAllFiles(DAVFileAccess file, Set files) {
120         if (!file.isCollection()) {
121             files.add(file);
122         } else {
123             try {
124                 List children = file.getChildren();
125                 if (children != null && !children.isEmpty()) {
126                     Iterator iterator = children.iterator();
127                     while (iterator.hasNext()) {
128                         DAVFileAccess child = (DAVFileAccess) iterator.next();
129                         // avoid aliases
130
if (child.getPath().startsWith(file.getPath())) {
131                             getAllFiles(child, files);
132                         }
133                     }
134                 }
135             } catch (Exception JavaDoc e) {
136                 logger.warn("Cannot get "+file.getPath());
137             }
138         }
139     }
140
141     public void exportAll(OutputStream JavaDoc outputStream, Map params, ParamBean jParams) throws JahiaException, IOException, SAXException JavaDoc {
142         Enumeration en = ServicesRegistry.getInstance().getJahiaSitesService().getSites();
143
144         ZipOutputStream JavaDoc zout = new ZipOutputStream JavaDoc(outputStream);
145
146         ZipEntry JavaDoc anEntry = new ZipEntry JavaDoc("export.properties");
147         zout.putNextEntry(anEntry);
148         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(zout));
149         bw.write("JahiaRelease = " + JahiaInterface.RELEASE_NUMBER+"\n");
150         bw.write("ServicePack = " + JahiaInterface.SERVICE_PACK_NUMBER+"\n");
151         bw.write("Patch = " + JahiaInterface.PATCH_STRING+"\n");
152         bw.write("BuildNumber = " + JahiaInterface.BUILD_NUMBER+"\n");
153         bw.write("ExportDate = " + new SimpleDateFormat JavaDoc("yyyy-MM-DD HH:mm:ss").format(new Date())+"\n");
154         bw.flush();
155         
156         JahiaSite s = jParams.getSite();
157         while (en.hasMoreElements()) {
158             JahiaSite jahiaSite = (JahiaSite) en.nextElement();
159             anEntry = new ZipEntry JavaDoc(jahiaSite.getSiteKey()+".zip");
160             zout.putNextEntry(anEntry);
161             exportSite(jahiaSite, zout, jParams, params);
162         }
163
164         jParams.setSite(s);
165
166         zout.finish();
167     }
168
169     public void exportSite(JahiaSite jahiaSite, OutputStream JavaDoc out, ParamBean jParams, Map params) throws JahiaException, IOException, SAXException JavaDoc {
170         ContentPage home = jahiaSite.getHomeContentPage();
171         List locs = jahiaSite.getLanguageSettingsAsLocales(false);
172         Set langs = new HashSet();
173         for (Iterator iterator = locs.iterator(); iterator.hasNext();) {
174             Locale locale = (Locale) iterator.next();
175             langs.add(locale.toString());
176         }
177
178         jParams.setSite(jahiaSite);
179
180         exportZip(home, langs, out, jParams, params);
181     }
182
183     public void exportAllFilesAcl(OutputStream JavaDoc out, ParamBean jParams) throws JahiaException, SAXException JavaDoc, IOException {
184         DataWriter dw = new DataWriter(new OutputStreamWriter(out, "UTF-8"));
185         exportAllFilesAcl(dw, jParams);
186     }
187
188     public void exportZip(ContentObject object, Set languageCodes, OutputStream JavaDoc out, ParamBean jParams, Map params) throws JahiaException, SAXException JavaDoc, IOException {
189         Set files = new HashSet();
190
191         byte[] buffer = new byte[4096];
192         int bytesIn = 0;
193
194         ZipOutputStream JavaDoc zout = new ZipOutputStream JavaDoc(out);
195
196         for (Iterator iterator = languageCodes.iterator(); iterator.hasNext();) {
197             String JavaDoc l = (String JavaDoc) iterator.next();
198
199             ZipEntry JavaDoc anEntry = new ZipEntry JavaDoc("export_" + l + ".xml");
200             zout.putNextEntry(anEntry);
201
202             DataWriter dw = new DataWriter(new OutputStreamWriter(zout, "UTF-8"));
203             export(object, l, dw, files, jParams, params);
204         }
205
206         if (params != null && Boolean.TRUE.equals(params.get(INCLUDE_ALL_FILES))) {
207             files.clear();
208             getAllFiles(new DAVFileAccess(jParams, jParams.getSite(), jParams.getUser(), "/"),files);
209             params.put(INCLUDE_FILES, Boolean.TRUE);
210         }
211
212         if (params != null && Boolean.TRUE.equals(params.get(INCLUDE_FILES))) {
213             DataWriter dw = new DataWriter(new OutputStreamWriter(zout, "UTF-8"));
214
215             zout.putNextEntry(new ZipEntry JavaDoc("filesacl.xml"));
216
217             if (Boolean.TRUE.equals(params.get(INCLUDE_ALL_FILES))) {
218                 exportAllFilesAcl(dw, jParams);
219             } else {
220                 exportFilesAcl(dw, files, jParams);
221             }
222             dw.flush();
223
224             if (object.getParent(null, null, null) == null) {
225                 // site export
226
if (params.containsKey(INCLUDE_SITE_INFOS)) {
227                     zout.putNextEntry(new ZipEntry JavaDoc("site.properties"));
228                     exportSiteInfos(zout, jParams, jParams.getSite());
229                 }
230
231                 if (params.containsKey(INCLUDE_TEMPLATES)) {
232                     zout.putNextEntry(new ZipEntry JavaDoc("templates.jar"));
233                     exportTpl(zout, jParams, jParams.getSite());
234                 }
235
236                 zout.putNextEntry(new ZipEntry JavaDoc("categories.xml"));
237                 exportCategories(dw, jParams.getUser());
238                 dw.flush();
239
240                 zout.putNextEntry(new ZipEntry JavaDoc("users.xml"));
241                 exportUsers(dw, jParams.getSite());
242                 dw.flush();
243             }
244
245             for (Iterator iterator = files.iterator(); iterator.hasNext();) {
246                 DAVFileAccess file = (DAVFileAccess) iterator.next();
247                 if (file.isValid()) {
248                     try {
249                         InputStream is = file.downloadFile();
250                         if (is != null) {
251                             zout.putNextEntry(new ZipEntry JavaDoc(file.getPath().substring(1)));
252                             while ((bytesIn = is.read(buffer)) != -1) {
253                                 zout.write(buffer, 0, bytesIn);
254                             }
255                             is.close();
256                         }
257                     } catch (Exception JavaDoc e) {
258                         logger.error("Error when getting file "+file.getPath(), e);
259                     }
260                 }
261             }
262         }
263         zout.finish();
264     }
265
266     private void exportSiteInfos(OutputStream JavaDoc out, ParamBean jParams, JahiaSite s) throws IOException {
267         Properties p = new Properties();
268         p.setProperty("sitetitle",s.getTitle());
269         p.setProperty("siteservername",s.getServerName());
270         p.setProperty("sitekey",s.getSiteKey());
271         p.setProperty("description",s.getDescr());
272         p.setProperty("mixLanguage",Boolean.toString(s.isMixLanguagesActive()));
273         try {
274             Vector v = s.getLanguageSettings();
275             for (Iterator iterator = v.iterator(); iterator.hasNext();) {
276                 SiteLanguageSettings sls = (SiteLanguageSettings) iterator.next();
277                 p.setProperty("language."+sls.getCode()+".activated", ""+sls.isActivated());
278                 p.setProperty("language."+sls.getCode()+".mandatory", ""+sls.isMandatory());
279                 p.setProperty("language."+sls.getCode()+".rank", ""+sls.getRank());
280             }
281             v = s.getLanguageMappings();
282             for (Iterator iterator = v.iterator(); iterator.hasNext();) {
283                 SiteLanguageMapping slm = (SiteLanguageMapping) iterator.next();
284                 p.setProperty("languageMapping."+slm.getFromLanguageCode(), slm.getToLanguageCode());
285             }
286         } catch (JahiaException e) {
287         }
288         p.store(out, "");
289     }
290
291     private void addFiles(File dir, String JavaDoc path, Set excludes, ZipOutputStream JavaDoc zout) throws IOException {
292         if (excludes.contains(path)) {
293             return;
294         }
295
296         File[] f = dir.listFiles();
297
298         byte[] buffer = new byte[4096];
299         int bytesIn;
300
301         for (int i = 0; i < f.length; i++) {
302             File file = f[i];
303             String JavaDoc entryPath = path + "/" + file.getName();
304             if (file.isDirectory()) {
305                 addFiles(file, entryPath, excludes, zout);
306             } else if (!excludes.contains(entryPath)) {
307                 zout.putNextEntry(new ZipEntry JavaDoc(entryPath.substring(1)));
308                 InputStream is = new FileInputStream(file);
309                 while ((bytesIn = is.read(buffer)) != -1) {
310                     zout.write(buffer, 0, bytesIn);
311                 }
312                 is.close();
313             }
314         }
315     }
316
317     public void exportClasses(OutputStream JavaDoc out, ParamBean jParams) throws IOException {
318         String JavaDoc path = Jahia.getSettings().getClassDiskPath();
319
320         ZipOutputStream JavaDoc zout = new ZipOutputStream JavaDoc(out);
321         Set excludes = new HashSet();
322         excludes.add("/org/jahia");
323         excludes.add("/org/apache");
324
325         File[] rb = new File(path).listFiles(new FilenameFilter() {
326             public boolean accept(File dir, String JavaDoc name) {
327                 return name.startsWith("JahiaAdministrationResources") ||
328                         name.startsWith("JahiaEnginesResources") ||
329                         name.startsWith("JahiaMessageResources");
330             }
331         });
332         for (int i = 0; i < rb.length; i++) {
333             File file = rb[i];
334             excludes.add("/"+file.getName());
335         }
336
337         excludes.add("/mbeans-descriptors.xml");
338         excludes.add("/jahiapublickeystore");
339         addFiles(new File(path), "", excludes, zout);
340         zout.finish();
341     }
342
343     private void exportTpl(OutputStream JavaDoc out, ParamBean jParams, JahiaSite s) throws IOException {
344         ZipOutputStream JavaDoc zout = new ZipOutputStream JavaDoc(out);
345
346         String JavaDoc path = Jahia.getSettings().getJahiaTemplatesDiskPath() + File.separator + s.getSiteKey();
347
348         int homeId = s.getHomeContentPage().getPageTemplateID(jParams);
349
350         File f = new File(path);
351         HashSet excludes = new HashSet();
352         excludes.add("/templates.xml");
353         addFiles(f, "", excludes, zout);
354
355         zout.putNextEntry(new ZipEntry JavaDoc("classes.jar"));
356         exportClasses(zout, jParams);
357
358         try {
359             zout.putNextEntry(new ZipEntry JavaDoc("templates.xml"));
360             DataWriter h = new DataWriter(new OutputStreamWriter(zout, "UTF-8"));
361             Enumeration en = ServicesRegistry.getInstance().getJahiaPageTemplateService().getPageTemplates(s.getID(), false);
362
363             h.startElement("", "tpml", "tpml", new AttributesImpl JavaDoc());
364
365             AttributesImpl JavaDoc atts = new AttributesImpl JavaDoc();
366             atts.addAttribute("","name", "name", "CDATA", "package-name");
367             h.startElement("", "parameter", "parameter", atts);
368             h.characters(s.getSiteKey().toCharArray(),0,s.getSiteKey().length());
369             h.endElement("", "parameter", "parameter");
370
371             atts = new AttributesImpl JavaDoc();
372             atts.addAttribute("","name", "name", "CDATA", "root-folder");
373             h.startElement("", "parameter", "parameter", atts);
374             h.endElement("", "parameter", "parameter");
375
376             atts = new AttributesImpl JavaDoc();
377             atts.addAttribute("","name", "name", "CDATA", "classes-file");
378             h.startElement("", "parameter", "parameter", atts);
379             h.characters("classes.jar");
380             h.endElement("", "parameter", "parameter");
381
382             atts = new AttributesImpl JavaDoc();
383             atts.addAttribute("","name", "name", "CDATA", "classes-root");
384             h.startElement("", "parameter", "parameter", atts);
385             h.endElement("", "parameter", "parameter");
386
387             boolean homeFound = false;
388
389             while (en.hasMoreElements()) {
390                 JahiaPageDefinition jpd = (JahiaPageDefinition) en.nextElement();
391                 atts = new AttributesImpl JavaDoc();
392                 atts.addAttribute("","browsable", "browsable", "CDATA", "1");
393                 atts.addAttribute("","visible", "visible", "CDATA", "1");
394
395                 if (!homeFound && (jpd.getID() == homeId || !en.hasMoreElements())) {
396                     atts.addAttribute("","homepage", "homepage", "CDATA", "1");
397                     homeFound = true;
398                 }
399
400                 if (s.getDefaultTemplateID() == jpd.getID()) {
401                     atts.addAttribute("","default", "default", "CDATA", "1");
402                 }
403                 h.startElement("", "template", "template", atts);
404
405                 atts = new AttributesImpl JavaDoc();
406                 atts.addAttribute("","name", "name", "CDATA", "name");
407                 h.startElement("", "parameter", "parameter", atts);
408                 h.characters(jpd.getName().toCharArray(),0,jpd.getName().length());
409                 h.endElement("", "parameter", "parameter");
410
411                 atts = new AttributesImpl JavaDoc();
412                 atts.addAttribute("","name", "name", "CDATA", "filename");
413                 h.startElement("", "parameter", "parameter", atts);
414                 String JavaDoc sourcePath = jpd.getSourcePath();
415                 sourcePath = sourcePath.substring(sourcePath.indexOf(s.getSiteKey())+s.getSiteKey().length()+1);
416                 h.characters(sourcePath.toCharArray(),0,sourcePath.length());
417                 h.endElement("", "parameter", "parameter");
418
419                 atts = new AttributesImpl JavaDoc();
420                 atts.addAttribute("","name", "name", "CDATA", "display-name");
421                 h.startElement("", "parameter", "parameter", atts);
422                 h.characters(jpd.getName().toCharArray(),0,jpd.getName().length());
423                 h.endElement("", "parameter", "parameter");
424
425                 h.endElement("", "template", "template");
426             }
427
428             h.endElement("", "tpml", "tpml");
429             h.flush();
430         } catch (JahiaException e) {
431             logger.error("Cannot export templates",e);
432         } catch (SAXException JavaDoc e) {
433             logger.error("Cannot export templates",e);
434         }
435
436         zout.finish();
437     }
438
439     public void export(ContentObject object, String JavaDoc languageCode, ContentHandler JavaDoc h, Set files, ParamBean jParams, Map params) throws JahiaException, SAXException JavaDoc {
440         if (params == null) {
441             params = new HashMap();
442         }
443         EntryLoadRequest toLoadRequest = (EntryLoadRequest) params.get(TO);
444         if (toLoadRequest == null) {
445             toLoadRequest = new EntryLoadRequest(EntryLoadRequest.CURRENT);
446         } else {
447             ArrayList locales = new ArrayList();
448             locales.add(LanguageCodeConverters.languageCodeToLocale(ContentField.SHARED_LANGUAGE));
449             locales.add(LanguageCodeConverters.languageCodeToLocale(languageCode));
450             toLoadRequest = new EntryLoadRequest(toLoadRequest.getWorkflowState(), toLoadRequest.getVersionID(),
451                 locales, toLoadRequest.isWithMarkedForDeletion());
452         }
453
454         params.put(TO, toLoadRequest);
455
456         Object JavaDoc from = params.get(FROM);
457         Map froms;
458         if (from instanceof Map) {
459             froms = (Map) from;
460             if (froms.containsKey(languageCode)) {
461                 froms = (Map) froms.get(languageCode);
462             }
463         } else {
464             froms = new HashMap();
465             if (from != null) {
466                 froms.put(null, from);
467             }
468         }
469
470         for (Iterator iterator = new HashSet(froms.keySet()).iterator(); iterator.hasNext();) {
471             String JavaDoc key = (String JavaDoc) iterator.next();
472             EntryLoadRequest fromLoadRequest = (EntryLoadRequest) froms.get(key);
473             if (fromLoadRequest != null) {
474                 fromLoadRequest = new EntryLoadRequest(fromLoadRequest);
475                 fromLoadRequest.setFirstLocale(languageCode);
476                 froms.put(key, fromLoadRequest);
477             }
478         }
479         params.put(FROM, froms);
480         params.put(GHOST, new HashSet());
481         h.startDocument();
482
483         h.startPrefixMapping("jahia", JAHIA_URI);
484         h.endPrefixMapping("jahia");
485         h.startPrefixMapping("jcr", JCR_URI);
486         h.endPrefixMapping("jcr");
487         h.startPrefixMapping(jParams.getSiteKey(), JAHIA_URI + jParams.getSiteKey());
488         h.endPrefixMapping(jParams.getSiteKey());
489         h.startPrefixMapping(jParams.getSiteKey() + "nt", JAHIA_URI + jParams.getSiteKey() + "/nt");
490         h.endPrefixMapping(jParams.getSiteKey() + "nt");
491
492         Stack elementStack = new Stack();
493         elementStack.add(new Siblings());
494         export(object, languageCode, h, files, jParams, params, true, false, elementStack);
495
496         h.endDocument();
497     }
498
499     private void export(ContentObject object, String JavaDoc languageCode, ContentHandler JavaDoc h, Set files, ParamBean jParams, Map params, boolean top, boolean parentAdded, Stack elementStack) throws JahiaException, SAXException JavaDoc {
500         try {
501             AttributesImpl JavaDoc attr = new AttributesImpl JavaDoc();
502             if (top) {
503                 attr.addAttribute(NS_URI, "jahia", "xmlns:jahia", "CDATA", JAHIA_URI);
504                 attr.addAttribute(NS_URI, "jcr", "xmlns:jcr", "CDATA", JCR_URI);
505                 attr.addAttribute(NS_URI, jParams.getSiteKey(), "xmlns:" + jParams.getSiteKey(), "CDATA", JAHIA_URI + jParams.getSiteKey());
506                 attr.addAttribute(NS_URI, jParams.getSiteKey() + "nt", "xmlns:" + jParams.getSiteKey() + "nt", "CDATA", JAHIA_URI + jParams.getSiteKey() + "/nt");
507             }
508
509             String JavaDoc uri = JAHIA_URI + jParams.getSite().getSiteKey();
510             String JavaDoc prefix = jParams.getSite().getSiteKey();
511             String JavaDoc elementName = null;
512             Element currentElement = null;
513             Siblings mySiblings = (Siblings) elementStack.peek();
514
515             String JavaDoc changedStatus = null;
516
517             boolean view = !Boolean.FALSE.equals(params.get(VIEW_CONTENT));
518             boolean viewVersionNumbers = Boolean.TRUE.equals(params.get(VIEW_VERSION));
519             boolean viewAcl = !Boolean.FALSE.equals(params.get(VIEW_ACL));
520             boolean viewMetadata = !Boolean.FALSE.equals(params.get(VIEW_METADATA));
521             boolean viewLinks = !Boolean.FALSE.equals(params.get(VIEW_JAHIALINKS));
522             Set ghost = (Set) params.get(GHOST);
523
524             String JavaDoc link = (String JavaDoc) params.get(LINK);
525
526             if (link != null) {
527                 viewAcl = false;
528                 viewVersionNumbers = true;
529             }
530
531             EntryLoadRequest toLoadRequest = (EntryLoadRequest) params.get(TO);
532             Map froms = (Map) params.get(FROM);
533
534             if (toLoadRequest.getWorkflowState() > 1 && !object.checkWriteAccess(jParams.getUser())) {
535                 checkEmptiness(top, h, attr);
536                 return;
537             }
538
539             ContentObjectEntryState entryState = getEntryState(object, languageCode, toLoadRequest);
540
541             String JavaDoc uuid = getUuid(object);
542
543             EntryLoadRequest fromLoadRequest = (EntryLoadRequest) froms.get(uuid);
544
545             boolean access = object.checkReadAccess(jParams.getUser());
546
547             if (fromLoadRequest == null) {
548                 fromLoadRequest = (EntryLoadRequest) froms.get(null);
549             }
550
551             if (fromLoadRequest != null) {
552                 int stat = getDiffStatus(object, languageCode, fromLoadRequest, toLoadRequest);
553                 if (parentAdded) {
554                     if (stat == VersioningDifferenceStatus.TO_BE_REMOVED) {
555                         checkEmptiness(top, h, attr);
556                         return;
557                     } else {
558                         stat = VersioningDifferenceStatus.ADDED;
559                     }
560                 }
561                 switch (stat) {
562                     case VersioningDifferenceStatus.UNCHANGED:
563                         if (!access && froms.containsKey(uuid)) {
564                             changedStatus = "removed";
565                             access = true;
566                         } else {
567                             changedStatus = "unchanged";
568                         }
569                         view = false;
570                         if (object instanceof ContentPage && getEntryState(object, languageCode, fromLoadRequest) == null) {
571                             return;
572                         }
573                         break;
574                     case VersioningDifferenceStatus.ADDED:
575                         changedStatus = "added";
576                         break;
577                     case VersioningDifferenceStatus.TO_BE_UPDATED:
578                         if (object instanceof ContentPage && ((ContentPage)object).getParentID(fromLoadRequest) != ((ContentPage)object).getParentID(toLoadRequest)) {
579                             parentAdded = true;
580                             changedStatus = "added";
581                         } else {
582                             if (!access && froms.containsKey(uuid)) {
583                                 changedStatus = "removed";
584                                 access = true;
585                             } else {
586                                 changedStatus = "updated";
587                             }
588                         }
589                         break;
590                     case VersioningDifferenceStatus.TO_BE_REMOVED:
591                         changedStatus = "removed";
592                         view = false;
593                         break;
594                 }
595             } else if (entryState == null || entryState.getWorkflowState() == EntryLoadRequest.DELETED_WORKFLOW_STATE) {
596                 if (object instanceof ContentPage && ((ContentPage)object).getPageType(toLoadRequest) == JahiaPage.TYPE_DIRECT) {
597                     boolean found = false;
598                     List locs = jParams.getSite().getLanguageSettingsAsLocales(false);
599                     for (Iterator iterator = locs.iterator(); iterator.hasNext() && !found;) {
600                         Locale locale = (Locale) iterator.next();
601                         if (getEntryState(object, locale.toString(), toLoadRequest) != null) {
602                             ghost.add(object.getObjectKey().toString());
603                             found = true;
604                         }
605                     }
606                     if (!found) {
607                         checkEmptiness(top, h, attr);
608                         return;
609                     }
610                 } else {
611                     checkEmptiness(top, h, attr);
612                     return;
613                 }
614             } else if (!froms.isEmpty()) {
615                 changedStatus = "added";
616             }
617
618             if (!access) {
619                 checkEmptiness(top, h, attr);
620                 return;
621             }
622
623             ContentPage currentPage = null;
624
625             if (object instanceof ContentPage) {
626                 uri = JAHIA_URI;
627                 prefix = "jahia";
628                 elementName = "page";
629
630                 ContentPage cp = ((ContentPage) object);
631                 String JavaDoc title = cp.getTitle(toLoadRequest, false);
632                 switch (cp.getPageType(toLoadRequest)) {
633                     case JahiaPage.TYPE_DIRECT:
634                         currentPage = cp;
635                         if (view) {
636                             attr.addAttribute(JAHIA_URI, "template", "jahia:template", "CDATA", ((ContentPage) object).getPageTemplate(toLoadRequest).getName());
637
638                             PageProperty prop = ((ContentPage) object).getPageLocalProperty(PageProperty.PAGE_URL_KEY_PROPNAME);
639                             if (prop != null) {
640                                 attr.addAttribute(JAHIA_URI, "pageKey", "jahia:pageKey", "CDATA", prop.getValue());
641                             }
642
643                             if (title != null) {
644                                 attr.addAttribute(JAHIA_URI, "title", "jahia:title", "CDATA", title);
645                             }
646                         }
647                         break;
648                     case JahiaPage.TYPE_LINK:
649                         currentPage = ContentPage.getPage(cp.getParentID(toLoadRequest));
650                         elementName = "link";
651                         attr.addAttribute(JAHIA_URI, "reference", "jahia:reference", "CDATA", getUuid(ContentPage.getPage(cp.getPageLinkID(toLoadRequest))));
652                         if (view) {
653                             if (title != null) {
654                                 attr.addAttribute(JAHIA_URI, "title", "jahia:title", "CDATA", title);
655                             }
656                         }
657                         break;
658                     case JahiaPage.TYPE_URL:
659                         currentPage = ContentPage.getPage(cp.getParentID(toLoadRequest));
660                         elementName = "url";
661                         if (view) {
662                             attr.addAttribute(JAHIA_URI, "value", "jahia:value", "CDATA", cp.getURL(jParams, languageCode));
663                             if (title != null) {
664                                 attr.addAttribute(JAHIA_URI, "title", "jahia:title", "CDATA", title);
665                             }
666                         }
667                         break;
668                 }
669             } else if (object instanceof ContentContainerList) {
670                 ContentContainerList cc = (ContentContainerList) object;
671                 ContainerDefinitionKey cdk = (ContainerDefinitionKey) cc.getDefinitionKey(toLoadRequest);
672                 JahiaContainerDefinition jcd = (JahiaContainerDefinition) JahiaContainerDefinition.getInstance(cdk);
673                 currentPage = cc.getPage();
674                 elementName = jcd.getName() + "List";
675
676                 Properties p = cc.getJahiaContainerList(jParams, toLoadRequest).getProperties();
677                 Enumeration en = p.keys();
678                 if (viewAcl) {
679                     while (en.hasMoreElements()) {
680                         String JavaDoc s = (String JavaDoc) en.nextElement();
681                         if (s.startsWith("view_field_acl_")) {
682                             String JavaDoc prop = p.getProperty(s);
683                             if (prop != null) {
684                                 try {
685                                     int aclID = Integer.parseInt(prop);
686                                     JahiaBaseACL theACL = null;
687                                     try {
688                                         theACL = new JahiaBaseACL(aclID);
689                                         exportAcl(theACL, s, attr, top);
690                                     }
691                                     catch (ACLNotFoundException ex) {
692                                     }
693                                     catch (JahiaException ex) {
694                                     }
695                                 } catch (Throwable JavaDoc t) {
696                                 }
697                             }
698                         }
699                     }
700                 }
701             } else if (object instanceof ContentContainer) {
702                 ContentContainer cc = (ContentContainer) object;
703                 ContainerDefinitionKey cdk = (ContainerDefinitionKey) cc.getDefinitionKey(toLoadRequest);
704                 JahiaContainerDefinition jcd = (JahiaContainerDefinition) JahiaContainerDefinition.getInstance(cdk);
705                 currentPage = cc.getPage();
706
707                 elementName = jcd.getName();
708             } else if (object instanceof ContentField) {
709                 ContentField cf = (ContentField) object;
710                 FieldDefinitionKey fdk = (FieldDefinitionKey) cf.getDefinitionKey(toLoadRequest);
711                 JahiaFieldDefinition jcd = (JahiaFieldDefinition) JahiaFieldDefinition.getInstance(fdk);
712                 currentPage = cf.getPage();
713
714                 elementName = jcd.getName();
715
716                 if (view) {
717                     String JavaDoc fieldValue = getFieldValue(cf, files, jParams, entryState, attr);
718                     if (fieldValue != null && !(object instanceof ContentPageField)) {
719                         attr.addAttribute(JAHIA_URI, "value", "jahia:value", "CDATA", fieldValue);
720                     }
721                 }
722             }
723             attr.addAttribute(JCR_URI, "uuid", "jcr:uuid", "CDATA", uuid);
724
725             if (view && viewMetadata) {
726                 // add meta data as properties or nodes ?
727
String JavaDoc catString = "";
728                 Set cats = categoryService.getObjectCategories(object.getObjectKey());
729                 for (Iterator iterator = cats.iterator(); iterator.hasNext();) {
730                     Category cat = (Category) iterator.next();
731                     catString += "$$$" + cat.getKey();
732                 }
733                 if (catString.length() > 0) {
734                     catString = catString.substring(1);
735                     attr.addAttribute(JAHIA_URI, "categories", "jahia:categories", "CDATA", catString);
736                 }
737                 if (viewLinks) {
738                     List links = ObjectLink.findByRightObjectKey(object.getObjectKey());
739                     Map linkAttributes = new HashMap();
740                     for (Iterator iterator = links.iterator(); iterator.hasNext();) {
741                         ObjectLink objectLink = (ObjectLink) iterator.next();
742                         if (!structRelations.contains(objectLink.getType())) {
743                             String JavaDoc localName = "jahiaLink" + StringUtils.capitalize(objectLink.getType());
744                             ObjectKey k = objectLink.getLeftObjectKey();
745                             JahiaObject o = JahiaObject.getInstance(k);
746                             if (o instanceof ContentObject) {
747                                 String JavaDoc s = (String JavaDoc) linkAttributes.get(localName);
748                                 if (s == null) {
749                                     s = getUuid((ContentObject) o);
750                                     linkAttributes.put(localName, s);
751                                 } else {
752                                     s += "," + getUuid((ContentObject) o);
753                                 }
754                             }
755                         }
756                     }
757                     for (Iterator iterator = linkAttributes.keySet().iterator(); iterator.hasNext();) {
758                         String JavaDoc s = (String JavaDoc) iterator.next();
759                         attr.addAttribute(JAHIA_URI, s, "jahia:"+s, "CDATA", (String JavaDoc) linkAttributes.get(s));
760                     }
761                 }
762             }
763
764             if (changedStatus != null) {
765                 attr.addAttribute(JAHIA_URI, "diff", "jahia:diff", "CDATA", changedStatus);
766             }
767
768             if (viewAcl) {
769                 JahiaBaseACL acl = object.getACL();
770                 exportAcl(acl, "acl", attr, top);
771             }
772
773             if (link != null) {
774                 attr.addAttribute(JAHIA_URI, "linkkey", "jahia:linkkey", "CDATA", object.getObjectKey().toString());
775                 attr.addAttribute(JAHIA_URI, "linktype", "jahia:linktype", "CDATA", link);
776             }
777
778             if (viewVersionNumbers) {
779                 if (entryState != null && entryState.getVersionID() > 0) {
780                     attr.addAttribute(JAHIA_URI, "version", "jahia:version", "CDATA", Integer.toString(entryState.getVersionID()));
781                 }
782             }
783
784             currentElement = new Element(uri, elementName, prefix + ":" + elementName, attr);
785             mySiblings.elements.add(currentElement);
786
787             if (!"unchanged".equals(changedStatus) && !ghost.contains(currentPage.getObjectKey().toString())|| top) {
788                 for (Iterator iterator = elementStack.iterator(); iterator.hasNext();) {
789                     Siblings siblings = (Siblings) iterator.next();
790                     if (siblings != mySiblings || !(object instanceof ContentContainer)) {
791                         // only print last element (current ancestor)
792
Element element = (Element) (siblings.elements.get(siblings.elements.size() - 1));
793                         if (!element.started) {
794                             h.startElement(element.uri, element.elementName, element.qName, element.attr);
795                             element.started = true;
796                         }
797                     } else {
798                         // print all previous siblings
799
siblings.printall = true;
800                         for (Iterator iterator1 = siblings.elements.iterator(); iterator1.hasNext();) {
801                             Element element = (Element) iterator1.next();
802                             if (!element.started) {
803                                 h.startElement(element.uri, element.elementName, element.qName, element.attr);
804                                 element.started = true;
805                                 if (element != currentElement) {
806                                     h.endElement(element.uri, element.elementName, element.qName);
807                                 }
808                             }
809                         }
810                     }
811                 }
812             }
813
814             // Recurse on children
815
if (!"removed".equals(changedStatus)) {
816                 EntryLoadRequest withDeleted = new EntryLoadRequest(toLoadRequest);
817                 withDeleted.setWithMarkedForDeletion(true);
818                 List l = object.getChilds(jParams.getUser(), withDeleted);
819
820                 if (object instanceof ContentContainerList) {
821                     ImportExportUtils.orderContainerList(l, jParams);
822                 }
823                 Siblings siblings = new Siblings();
824                 elementStack.add(siblings);
825                 Set included = (Set) params.get(INCLUDED);
826                 for (Iterator iterator = l.iterator(); iterator.hasNext();) {
827                     ContentObject child = (ContentObject) iterator.next();
828
829                     if (included == null || included.contains(child.getObjectKey())) {
830                         export(child, languageCode, h, files, jParams, params, false, parentAdded, elementStack);
831                     } else if (object instanceof ContentContainerList && fromLoadRequest != null) {
832                         if (((ContentContainer) child).getJahiaContainer(jParams, fromLoadRequest) != null) {
833                             export(child, languageCode, h, files, jParams, params, false, parentAdded, elementStack);
834                         }
835                     }
836                 }
837                 elementStack.pop();
838
839                 if (siblings.printall) {
840                     for (Iterator iterator1 = siblings.elements.iterator(); iterator1.hasNext();) {
841                         Element element = (Element) iterator1.next();
842                         if (!element.started) {
843                             h.startElement(element.uri, element.elementName, element.qName, element.attr);
844                             element.started = true;
845                             h.endElement(element.uri, element.elementName, element.qName);
846                         }
847                     }
848                 }
849             }
850
851             if (currentElement != null && currentElement.started) {
852                 h.endElement(uri, currentElement.elementName, currentElement.qName);
853             }
854 // elementStack.remove(currentElement);
855
} catch (ClassNotFoundException JavaDoc e) {
856             throw new JahiaException("Invalid objectKey",
857                     "Invalid objectKey",
858                     JahiaException.SERVICE_ERROR,
859                     JahiaException.ERROR_SEVERITY,
860                     e);
861         }
862     }
863
864     private void checkEmptiness(boolean top, ContentHandler JavaDoc h, AttributesImpl JavaDoc attr) throws SAXException JavaDoc {
865         if (top) {
866             h.startElement(JAHIA_URI,"empty", "jahia:empty", attr);
867             h.endElement(JAHIA_URI,"empty", "jahia:empty");
868         }
869     }
870
871     private void getFiles(ContentObject object, String JavaDoc language, Set files, ParamBean jParams, Set included, EntryLoadRequest toLoadRequest) throws JahiaException {
872         if (!object.checkReadAccess(jParams.getUser())) {
873             return;
874         }
875
876         getFilesForField(object, jParams, language, toLoadRequest, files);
877
878         // Recurse on children
879
EntryLoadRequest withDeleted = new EntryLoadRequest(toLoadRequest);
880         withDeleted.setWithMarkedForDeletion(true);
881         List l = object.getChilds(jParams.getUser(), withDeleted);
882
883         if (object instanceof ContentContainerList) {
884             ImportExportUtils.orderContainerList(l, jParams);
885         }
886
887         for (Iterator iterator = l.iterator(); iterator.hasNext();) {
888             ContentObject child = (ContentObject) iterator.next();
889             if (included == null || included.contains(child.getObjectKey())) {
890                 getFiles(child, language, files, jParams, included, toLoadRequest);
891             }
892         }
893     }
894
895     public void getFilesForField(ContentObject object, ParamBean jParams, String JavaDoc language, EntryLoadRequest loadRequest, Set files) throws JahiaException {
896         ContentObjectEntryState entryState = getEntryState(object, language, loadRequest);
897
898         if (entryState == null) {
899             return;
900         }
901
902         if (object instanceof ContentFileField) {
903             ContentField contentField = (ContentField) object;
904             String JavaDoc value = contentField.getValue(jParams, entryState);
905
906             DAVFileAccess file = new DAVFileAccess(jParams, sitesService.getSite(contentField.getSiteID()), jParams.getUser(), value);
907             if (file.isValid() && !files.contains(file)) {
908                 files.add(file);
909             }
910         } else if (object instanceof ContentBigTextField) {
911             String JavaDoc value = ((ContentBigTextField)object).getValue(jParams, entryState);
912             Set f = new HashSet();
913             parseBigtextFiles(value, f, jParams);
914             for (Iterator iterator = f.iterator(); iterator.hasNext();) {
915                 String JavaDoc s = (String JavaDoc) iterator.next();
916                 DAVFileAccess file = new DAVFileAccess(jParams, sitesService.getSite(object.getSiteID()), jParams.getUser(), s);
917                 if (file.isValid() && !files.contains(file)) {
918                     files.add(file);
919                 }
920             }
921         }
922     }
923
924     private void exportAcl(JahiaBaseACL acl, String JavaDoc attrName, AttributesImpl JavaDoc attr, boolean top) throws JahiaACLException {
925         String JavaDoc perms = "";
926         Vector users = acl.getUsernameList(null);
927         for (Iterator iterator = users.iterator(); iterator.hasNext();) {
928             String JavaDoc username = (String JavaDoc) iterator.next();
929             JahiaUser user = userManagerService.lookupUser(username);
930             if (user != null) {
931                 JahiaACLEntry ace = acl.getUserEntry(user);
932                 if (ace != null) {
933                     perms += "|u:" + user.getUsername() + ":" + ((ace.getPermission(JahiaBaseACL.READ_RIGHTS) == JahiaACLEntry.ACL_YES) ? "r" : "-") +
934                             ((ace.getPermission(JahiaBaseACL.WRITE_RIGHTS) == JahiaACLEntry.ACL_YES) ? "w" : "-") +
935                             ((ace.getPermission(JahiaBaseACL.ADMIN_RIGHTS) == JahiaACLEntry.ACL_YES) ? "a" : "-");
936                 } else if (top) {
937                     perms += "|u:" + user.getUsername() + ":" + ((acl.getPermission(user, JahiaBaseACL.READ_RIGHTS)) ? "r" : "-") +
938                             ((acl.getPermission(user, JahiaBaseACL.WRITE_RIGHTS)) ? "w" : "-") +
939                             ((acl.getPermission(user, JahiaBaseACL.ADMIN_RIGHTS)) ? "a" : "-");
940                 }
941             }
942         }
943         Vector groups = acl.getGroupnameListNoAdmin(null);
944         for (Iterator iterator = groups.iterator(); iterator.hasNext();) {
945             String JavaDoc groupname = (String JavaDoc) iterator.next();
946             JahiaGroup group = groupManagerService.lookupGroup(groupname);
947             if (group != null) {
948                 JahiaACLEntry ace = acl.getGroupEntry(group);
949                 if (ace != null) {
950                     perms += "|g:" + group.getGroupname() + ":" + ((ace.getPermission(JahiaBaseACL.READ_RIGHTS) == JahiaACLEntry.ACL_YES) ? "r" : "-") +
951                             ((ace.getPermission(JahiaBaseACL.WRITE_RIGHTS) == JahiaACLEntry.ACL_YES) ? "w" : "-") +
952                             ((ace.getPermission(JahiaBaseACL.ADMIN_RIGHTS) == JahiaACLEntry.ACL_YES) ? "a" : "-");
953                 } else if (top) {
954                     perms += "|g:" + group.getGroupname() + ":" + ((acl.getPermission(group, JahiaBaseACL.READ_RIGHTS)) ? "r" : "-") +
955                             ((acl.getPermission(group, JahiaBaseACL.WRITE_RIGHTS)) ? "w" : "-") +
956                             ((acl.getPermission(group, JahiaBaseACL.ADMIN_RIGHTS)) ? "a" : "-");
957                 }
958             }
959         }
960         if (acl.getInheritance() == 1) {
961             perms += "|break";
962         }
963         if (perms.length() > 0) {
964             perms = perms.substring(1);
965             attr.addAttribute(JAHIA_URI, attrName, "jahia:" + attrName, "CDATA", perms);
966         }
967     }
968
969     private String JavaDoc getFieldValue(ContentField contentField, Set files, ParamBean jParams, ContentObjectEntryState entryState, AttributesImpl JavaDoc attr) throws JahiaException {
970         String JavaDoc value = contentField.getValue(entryState);
971         if ("<empty>".equals(value) || value == null) {
972             return null;
973         }
974         switch (contentField.getType()) {
975             case ContentFieldTypes.APPLICATION:
976                 try {
977                     JahiaApplicationField theField = (JahiaApplicationField) contentField.getJahiaField(jParams.getEntryLoadRequest());
978                     Integer JavaDoc appID = new Integer JavaDoc( (String JavaDoc) theField.getValue());
979                     ApplicationBean appBean = ServicesRegistry.getInstance().getJahiaApplicationsManagerService().getApplication(appID.intValue());
980                     ApplicationContext appContext = null;
981                     try {
982                         appContext = ServicesRegistry.getInstance()
983                                 .getJahiaApplicationContextService()
984                                 .getApplicationContext(appID.intValue());
985                         Vector roles = appContext.getRoles();
986                         if (roles != null) {
987                             JahiaGroupManagerService gMgr = ServicesRegistry.getInstance()
988                                 .getJahiaGroupManagerService();
989                             for (Iterator iterator = roles.iterator(); iterator.hasNext();) {
990                                 String JavaDoc perms = "";
991                                 String JavaDoc role = (String JavaDoc) iterator.next();
992                                 String JavaDoc gName = appID + "_" + theField.getID() + "_" + role;
993                                 JahiaGroup grp = gMgr.lookupGroup(0, gName);
994                                 List m = grp.memberList();
995                                 for (Iterator iterator1 = m.iterator(); iterator1.hasNext();) {
996                                     Object JavaDoc o = iterator1.next();
997                                     if (o instanceof JahiaUser) {
998                                         perms += "|u:" + ((JahiaUser)o).getUsername();
999                                     } else if (o instanceof JahiaGroup) {
1000                                        perms += "|g:" + ((JahiaGroup)o).getGroupname();
1001                                    }
1002                                }
1003                                if (perms.length() > 0) {
1004                                    String JavaDoc attrName = role + "Role";
1005                                    perms = perms.substring(1);
1006                                    attr.addAttribute(JAHIA_URI, attrName, "jahia:" + attrName, "CDATA", perms);
1007                                }
1008                            }
1009                        }
1010                    } catch ( Throwable JavaDoc t ){
1011                        logger.error("Cannot retrieve application roles",t);
1012                    }
1013                    return appBean.getName() + "[context="+contentField.getID()+"]";
1014                } catch (Exception JavaDoc e) {
1015                    return null;
1016                }
1017            case ContentFieldTypes.BIGTEXT:
1018                return parseBigtextLinks(parseBigtextFiles(value, files, jParams));
1019            case ContentFieldTypes.DATE:
1020                try {
1021                    DateFormat JavaDoc df = new SimpleDateFormat JavaDoc("yyyy-MM-dd'T'HH:mm:ss");
1022                    return df.format(new Date(Long.parseLong(value)));
1023                } catch (NumberFormatException JavaDoc e) {
1024                    return null;
1025                }
1026            case ContentFieldTypes.FILE:
1027                if (files != null) {
1028                    DAVFileAccess file = new DAVFileAccess(jParams, sitesService.getSite(contentField.getSiteID()), jParams.getUser(), value);
1029                    if (file.isValid() && !files.contains(file)) {
1030                        files.add(file);
1031                    }
1032                }
1033                return value;
1034            case ContentFieldTypes.SMALLTEXT:
1035            case ContentFieldTypes.SMALLTEXT_SHARED_LANG:
1036                if (value.startsWith("<jahia-expression") && value.endsWith("/>")) {
1037                    try {
1038                        Pattern JavaDoc p = Pattern.compile("(.*)getContainerByID\\(([0-9]+)\\)(.*)");
1039                        Matcher JavaDoc m = p.matcher(value);
1040                        while (m.matches()) {
1041                            String JavaDoc replacement = m.group(1) + "getContainerByUUID(\"" +
1042                                    getUuid(ContentContainer.getChildInstance(m.group(2))) +
1043                                    "\")" + m.group(3);
1044                            m.reset();
1045                            value = m.replaceFirst(replacement);
1046                            m = p.matcher(value);
1047                        }
1048                    } catch (Exception JavaDoc e) {
1049                        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
1050
}
1051                }
1052                return value;
1053            default:
1054                return value;
1055        }
1056    }
1057
1058    private int getDiffStatus(ContentObject object, String JavaDoc languageCode, EntryLoadRequest fromLoadRequest, EntryLoadRequest toLoadRequest)
1059            throws JahiaException {
1060
1061        int status = VersioningDifferenceStatus.UNCHANGED;
1062
1063        // resolve active entry state
1064
ContentObjectEntryState fromEntryState = getEntryState(object, languageCode, fromLoadRequest);
1065        ContentObjectEntryState toEntryState = getEntryState(object, languageCode, toLoadRequest);
1066
1067        if (toEntryState != null) {
1068            if (toEntryState.getVersionID() == ContentObjectEntryState.WORKFLOW_STATE_VERSIONING_DELETED ||
1069                    toEntryState.getWorkflowState() == ContentObjectEntryState.WORKFLOW_STATE_VERSIONING_DELETED) {
1070                if (fromEntryState != null && !fromEntryState.equals(toEntryState))
1071                    status = VersioningDifferenceStatus.TO_BE_REMOVED;
1072            } else {
1073                if (fromEntryState == null) {
1074                    status = VersioningDifferenceStatus.ADDED;
1075                } else if (fromEntryState.compareTo(toEntryState) != 0) {
1076                    status = VersioningDifferenceStatus.TO_BE_UPDATED;
1077                }
1078            }
1079        }
1080        return status;
1081    }
1082
1083    private ContentObjectEntryState getEntryState(ContentObject object, String JavaDoc languageCode, EntryLoadRequest loadRequest) throws JahiaException {
1084        ContentObjectEntryState entryState = null;
1085        int vID = loadRequest.getVersionID();
1086        if (vID == 0 && loadRequest.getWorkflowState() == EntryLoadRequest.ACTIVE_WORKFLOW_STATE) {
1087            vID = 1;
1088        }
1089        if (object.isShared()) {
1090            languageCode = ContentField.SHARED_LANGUAGE;
1091        }
1092        entryState =
1093                ContentObjectEntryState.getEntryState(vID,
1094                        languageCode);
1095        entryState = object.getEntryState(entryState, false, true);
1096
1097        return entryState;
1098    }
1099
1100    public String JavaDoc getUuid(ContentObject object) throws JahiaException {
1101        String JavaDoc uuid = (String JavaDoc) uuids.get(object.getObjectKey().toString());
1102        if (uuid == null) {
1103            uuid = idGen.nextIdentifier().toString();
1104            uuids.put(object.getObjectKey().toString(), uuid);
1105        }
1106        return uuid;
1107    }
1108
1109    private void exportFilesAcl(ContentHandler JavaDoc ch, Set files, ParamBean jParams) throws SAXException JavaDoc {
1110        ch.startDocument();
1111        ch.startPrefixMapping("jahia", JAHIA_URI);
1112        ch.endPrefixMapping("jahia");
1113        AttributesImpl JavaDoc attr = new AttributesImpl JavaDoc();
1114
1115        attr.addAttribute(NS_URI, "jahia", "xmlns:jahia", "CDATA", JAHIA_URI);
1116
1117        ch.startElement(JAHIA_URI, "filesacl", "jahia:filesacl", attr);
1118
1119        for (Iterator iterator = files.iterator(); iterator.hasNext();) {
1120            DAVFileAccess file = (DAVFileAccess) iterator.next();
1121            attr = new AttributesImpl JavaDoc();
1122
1123            attr.addAttribute(JAHIA_URI, "path", "jahia:path", "CDATA", file.getPath());
1124
1125            Map read = file.getPermissions(DAVFileAccess.READ);
1126            Map write = file.getPermissions(DAVFileAccess.WRITE);
1127            Map admin = file.getPermissions(DAVFileAccess.MANAGE);
1128            Set users = new HashSet();
1129
1130            users.addAll(read.keySet());
1131            users.addAll(write.keySet());
1132            users.addAll(admin.keySet());
1133            String JavaDoc perms = "";
1134            for (Iterator iterator1 = users.iterator(); iterator1.hasNext();) {
1135                String JavaDoc key = (String JavaDoc) iterator1.next();
1136                String JavaDoc name = getUserForFileAcl(jParams, key);
1137                if (name != null && name.length() > 0) {
1138                    perms += "|" + name + ":" +
1139                            (((((Integer JavaDoc) read.get(key)).intValue() & DAVFileAccess.GRANTED) == 0) ? '-' : 'r') +
1140                            (((((Integer JavaDoc) write.get(key)).intValue() & DAVFileAccess.GRANTED) == 0) ? '-' : 'w') +
1141                            (((((Integer JavaDoc) admin.get(key)).intValue() & DAVFileAccess.GRANTED) == 0) ? '-' : 'a');
1142                }
1143            }
1144            if (perms.length() > 0) {
1145                perms = perms.substring(1);
1146                attr.addAttribute(JAHIA_URI, "fileacl", "jahia:fileacl", "CDATA", perms);
1147            }
1148            ch.startElement(JAHIA_URI, "file", "jahia:file", attr);
1149            ch.endElement(JAHIA_URI, "file", "jahia:file");
1150        }
1151        ch.endElement(JAHIA_URI, "filesacl", "jahia:fileacl");
1152        ch.endDocument();
1153    }
1154
1155    private void exportAllFilesAcl(ContentHandler JavaDoc ch, ParamBean jParams) throws SAXException JavaDoc {
1156        ch.startDocument();
1157        ch.startPrefixMapping("jahia", JAHIA_URI);
1158        ch.endPrefixMapping("jahia");
1159        AttributesImpl JavaDoc attr = new AttributesImpl JavaDoc();
1160
1161        attr.addAttribute(NS_URI, "jahia", "xmlns:jahia", "CDATA", JAHIA_URI);
1162
1163        ch.startElement(JAHIA_URI, "filesacl", "jahia:filesacl", attr);
1164
1165        attr = new AttributesImpl JavaDoc();
1166        attr.addAttribute(NS_URI, "jahia", "xmlns:jahia", "CDATA", JAHIA_URI);
1167        exportAllFilesAcl(ch,new DAVFileAccess(jParams, jParams.getSite(), jParams.getUser(), "/shared"), jParams);
1168        exportAllFilesAcl(ch,new DAVFileAccess(jParams, jParams.getSite(), jParams.getUser(), "/users"), jParams);
1169        exportAllFilesAcl(ch,new DAVFileAccess(jParams, jParams.getSite(), jParams.getUser(), "/groups"), jParams);
1170        attr.addAttribute(NS_URI, "jahia", "xmlns:jahia", "CDATA", JAHIA_URI);
1171
1172        ch.endElement(JAHIA_URI, "filesacl", "jahia:fileacl");
1173        ch.endDocument();
1174    }
1175
1176    private void exportAllFilesAcl(ContentHandler JavaDoc ch, DAVFileAccess file, ParamBean jParams) throws SAXException JavaDoc {
1177        AttributesImpl JavaDoc attr = new AttributesImpl JavaDoc();
1178
1179        String JavaDoc path = file.getPath();
1180
1181        boolean showAcls = true;
1182        StringTokenizer st = new StringTokenizer(path,"/");
1183        String JavaDoc first = st.nextToken();
1184        if ("users".equals(first) || "groups".equals(first)) {
1185            if (st.hasMoreTokens()) {
1186                String JavaDoc sec = st.nextToken();
1187                if (st.hasMoreTokens()) {
1188                    String JavaDoc third = st.nextToken();
1189                    if (!st.hasMoreTokens()) {
1190                        if ("members".equals(third) || "mygroups".equals(third)) {
1191                            //users/root/mygroups
1192
return;
1193                        } else {
1194                            //users/root/private
1195
showAcls = false;
1196                        }
1197                    }
1198                } else {
1199                    // /users/root
1200
showAcls = false;
1201                }
1202            } else {
1203                // /users or /groups
1204
showAcls = false;
1205            }
1206        }
1207
1208        if (showAcls) {
1209        attr.addAttribute(JAHIA_URI, "path", "jahia:path", "CDATA", path);
1210
1211        Map read = file.getPermissions(DAVFileAccess.READ);
1212        Map write = file.getPermissions(DAVFileAccess.WRITE);
1213        Map admin = file.getPermissions(DAVFileAccess.MANAGE);
1214        Set users = new HashSet();
1215
1216        users.addAll(read.keySet());
1217        users.addAll(write.keySet());
1218        users.addAll(admin.keySet());
1219        String JavaDoc perms= "";
1220        for (final Iterator iterator = users.iterator(); iterator.hasNext();) {
1221            String JavaDoc key = (String JavaDoc) iterator.next();
1222            String JavaDoc name = getUserForFileAcl(jParams, key);
1223            if (name != null && name.length() > 0) {
1224                Integer JavaDoc r = (Integer JavaDoc) read.get(key);
1225                if ((r.intValue() & DAVFileAccess.INHERITED) == 0) {
1226                    Integer JavaDoc w = (Integer JavaDoc) write.get(key);
1227                    Integer JavaDoc a = (Integer JavaDoc) admin.get(key);
1228                    perms += "|" + name + ":" +
1229                            (r==null||((r.intValue() & DAVFileAccess.GRANTED) == 0) ? '-' : 'r') +
1230                            (w==null||((w.intValue() & DAVFileAccess.GRANTED) == 0) ? '-' : 'w') +
1231                            (a==null||((a.intValue() & DAVFileAccess.GRANTED) == 0) ? '-' : 'a');
1232                }
1233            }
1234        }
1235        if (perms.length() > 0) {
1236            perms = perms.substring(1);
1237            attr.addAttribute(JAHIA_URI, "fileacl", "jahia:fileacl", "CDATA", perms);
1238            ch.startElement(JAHIA_URI, "file", "jahia:file", attr);
1239            ch.endElement(JAHIA_URI, "file", "jahia:file");
1240        }
1241        }
1242
1243        List children = file.getChildren();
1244        for (Iterator iterator = children.iterator(); iterator.hasNext();) {
1245            DAVFileAccess child = (DAVFileAccess) iterator.next();
1246
1247            exportAllFilesAcl(ch, child, jParams);
1248        }
1249
1250    }
1251
1252    private String JavaDoc getUserForFileAcl(ParamBean jParams, String JavaDoc s) {
1253        if (s.equals("nobody") || s.equals("all")) {
1254            s = "+/groups/" + JahiaGroupManagerService.GUEST_GROUPNAME + "/members";
1255        } else if (s.equals("root")) {
1256            s = "+/groups/" + JahiaGroupManagerService.ADMINISTRATORS_GROUPNAME +
1257                    "/members";
1258        } else if (s.equals("user") || s.equals("authenticated")) {
1259            s = "+/groups/" + JahiaGroupManagerService.USERS_GROUPNAME + "/members";
1260        } else if (s.equals("guest") || s.equals("unauthenticated")) {
1261            s = "/users/" + JahiaUserManagerService.GUEST_USERNAME + "/members";
1262        }
1263        if (s.startsWith("+/groups/")) {
1264            JahiaGroup group = ServicesRegistry.getInstance().getJahiaGroupManagerService()
1265                    .lookupGroup(jParams.getSiteID(), s.substring(9, s.lastIndexOf('/')));
1266            if (group == null) {
1267                return null;
1268            }
1269            return "g:"+group.getGroupname();
1270        } else if (s.startsWith("/users/")) {
1271            String JavaDoc name = s.substring(7);
1272            if (name.indexOf('/') > -1) {
1273                name = name.substring(0, name.indexOf('/'));
1274            }
1275            JahiaUser jahiaUser;
1276            try {
1277                jahiaUser = ServicesRegistry.getInstance().getJahiaSiteUserManagerService()
1278                        .getMember(jParams.getSiteID(), name);
1279            } catch (JahiaException e) {
1280                return null;
1281            }
1282            if (jahiaUser == null) {
1283                return null;
1284            }
1285            return "u:"+jahiaUser.getUsername();
1286        }
1287        return null;
1288    }
1289
1290    private void exportCategories(ContentHandler JavaDoc ch, JahiaUser user) throws JahiaException, SAXException JavaDoc {
1291        ch.startDocument();
1292        ch.startPrefixMapping("jahia", JAHIA_URI);
1293        ch.endPrefixMapping("jahia");
1294        AttributesImpl JavaDoc attr = new AttributesImpl JavaDoc();
1295
1296        attr.addAttribute(NS_URI, "jahia", "xmlns:jahia", "CDATA", JAHIA_URI);
1297        ch.startElement(JAHIA_URI, "categories", "jahia:categories", attr);
1298
1299        Category c = categoryService.getRootCategory();
1300        exportCategories(ch, c, user);
1301
1302        ch.endElement(JAHIA_URI, "categories", "jahia:categories");
1303        ch.endDocument();
1304    }
1305
1306    private void exportCategories(ContentHandler JavaDoc ch, Category c, JahiaUser user) throws JahiaException, SAXException JavaDoc {
1307        AttributesImpl JavaDoc attr = new AttributesImpl JavaDoc();
1308        attr.addAttribute(JAHIA_URI, "key", "jahia:key", "CDATA", c.getKey());
1309        Map titles = categoryService.getTitlesForCategory(c);
1310        for (Iterator iterator = titles.keySet().iterator(); iterator.hasNext();) {
1311            String JavaDoc lang = (String JavaDoc) iterator.next();
1312            String JavaDoc value = (String JavaDoc) titles.get(lang);
1313            if (value != null) {
1314                attr.addAttribute(JAHIA_URI, "title_"+lang, "jahia:title_"+lang, "CDATA", value);
1315            }
1316        }
1317
1318        Properties p = c.getProperties();
1319// for (Iterator iterator = p.keySet().iterator(); iterator.hasNext();) {
1320
// String k = (String) iterator.next();
1321
// String property = p.getProperty(k);
1322
// if (XMLChar.isValidNCName(k)) {
1323
// if (property != null) {
1324
// attr.addAttribute(JAHIA_URI, k, "jahia:"+k, "CDATA", property);
1325
// }
1326
// }
1327
// }
1328

1329        ch.startElement(JAHIA_URI, "category", "jahia:category", attr);
1330
1331        for (Iterator iterator = p.keySet().iterator(); iterator.hasNext();) {
1332            String JavaDoc k = (String JavaDoc) iterator.next();
1333            String JavaDoc property = p.getProperty(k);
1334            if (property != null) {
1335                AttributesImpl JavaDoc attrProp = new AttributesImpl JavaDoc();
1336                attrProp.addAttribute(JAHIA_URI, "key", "jahia:key", "CDATA", k);
1337                attrProp.addAttribute(JAHIA_URI, "value", "jahia:key", "CDATA", property);
1338                ch.startElement(JAHIA_URI, "property", "jahia:property", attrProp);
1339                ch.endElement(JAHIA_URI, "property", "jahia:property");
1340            }
1341        }
1342
1343        List children = c.getChildCategories();
1344        for (Iterator iterator = children.iterator(); iterator.hasNext();) {
1345            Category child = (Category) iterator.next();
1346            exportCategories(ch,child,user);
1347        }
1348        ch.endElement(JAHIA_URI, "category", "jahia:category");
1349    }
1350
1351    public void exportUsersFile(OutputStream JavaDoc out, JahiaSite site) throws JahiaException, SAXException JavaDoc, IOException {
1352        DataWriter dw = new DataWriter(new OutputStreamWriter(out, "UTF-8"));
1353        exportUsers(dw, site);
1354    }
1355
1356    private void exportUsers(ContentHandler JavaDoc ch, JahiaSite site) throws JahiaException, SAXException JavaDoc {
1357        ch.startDocument();
1358        ch.startPrefixMapping("jahia", JAHIA_URI);
1359        ch.endPrefixMapping("jahia");
1360        AttributesImpl JavaDoc attr = new AttributesImpl JavaDoc();
1361
1362        attr.addAttribute(NS_URI, "jahia", "xmlns:jahia", "CDATA", JAHIA_URI);
1363
1364        ch.startElement(JAHIA_URI, "users", "jahia:users", attr);
1365
1366        List l = ServicesRegistry.getInstance().getJahiaSiteUserManagerService().getMembers(site.getID());
1367        for (Iterator iterator = l.iterator(); iterator.hasNext();) {
1368            JahiaDBUser jahiaUser = (JahiaDBUser) iterator.next();
1369            jahiaUser = (JahiaDBUser) userManagerService.lookupUser(jahiaUser.getUserKey());
1370            if (jahiaUser.getSiteID() != 0 && !jahiaUser.getUsername().equals(JahiaUserManagerService.GUEST_USERNAME)) {
1371                Properties p = jahiaUser.getUserProperties().getProperties();
1372                attr = new AttributesImpl JavaDoc();
1373                for (Iterator iterator1 = p.keySet().iterator(); iterator1.hasNext();) {
1374                    String JavaDoc k = (String JavaDoc) iterator1.next();
1375                    if (XMLChar.isValidNCName(k)) {
1376                        attr.addAttribute(JAHIA_URI, k, "jahia:"+k, "CDATA",(String JavaDoc) p.get(k));
1377                    }
1378                }
1379                attr.addAttribute(JAHIA_URI, "name", "jahia:name", "CDATA", jahiaUser.getUsername());
1380                attr.addAttribute(JAHIA_URI, "password", "jahia:password", "CDATA", "SHA-1:"+jahiaUser.getPassword());
1381                ch.startElement(JAHIA_URI, "user", "jahia:user", attr);
1382                ch.endElement(JAHIA_URI, "user", "jahia:user");
1383            }
1384        }
1385        Collection c = ServicesRegistry.getInstance().getJahiaSiteGroupManagerService().getGroups(site.getID()).values();
1386        for (Iterator iterator = c.iterator(); iterator.hasNext();) {
1387            String JavaDoc n = (String JavaDoc) iterator.next();
1388            JahiaGroup g = ServicesRegistry.getInstance().getJahiaGroupManagerService().lookupGroup(n);
1389            if (g.getSiteID() != 0 && !g.getGroupname().equals(JahiaGroupManagerService.GUEST_GROUPNAME)&&
1390                    !g.getGroupname().equals(JahiaGroupManagerService.USERS_GROUPNAME)) {
1391                Properties p = g.getProperties();
1392                attr = new AttributesImpl JavaDoc();
1393                for (Iterator iterator1 = p.keySet().iterator(); iterator1.hasNext();) {
1394                    String JavaDoc k = (String JavaDoc) iterator1.next();
1395                    if (XMLChar.isValidNCName(k)) {
1396                        attr.addAttribute(JAHIA_URI, k, "jahia:"+k, "CDATA",(String JavaDoc) p.get(k));
1397                    }
1398                }
1399                attr.addAttribute(JAHIA_URI, "name", "jahia:name", "CDATA", g.getGroupname());
1400                ch.startElement(JAHIA_URI, "group", "jahia:group", attr);
1401
1402                Enumeration en = g.members();
1403                while (en.hasMoreElements()) {
1404                    Principal JavaDoc principal = (Principal JavaDoc) en.nextElement();
1405                    attr = new AttributesImpl JavaDoc();
1406                    if (principal instanceof JahiaUser) {
1407                        attr.addAttribute(JAHIA_URI, "name", "jahia:name", "CDATA", ((JahiaUser)principal).getUsername());
1408                        ch.startElement(JAHIA_URI, "user", "jahia:user", attr);
1409                        ch.endElement(JAHIA_URI, "user", "jahia:user");
1410                    } else {
1411                        attr.addAttribute(JAHIA_URI, "name", "jahia:name", "CDATA", ((JahiaGroup)principal).getGroupname());
1412                        ch.startElement(JAHIA_URI, "group", "jahia:group", attr);
1413                        ch.endElement(JAHIA_URI, "group", "jahia:group");
1414                    }
1415                }
1416
1417                ch.endElement(JAHIA_URI, "group", "jahia:group");
1418            }
1419        }
1420
1421        ch.endElement(JAHIA_URI, "users", "jahia:users");
1422    }
1423
1424
1425    private Set getSiteLanguages(JahiaSite site) throws JahiaException {
1426        Set languages = new HashSet();
1427        Vector v = site.getLanguageSettings(true);
1428        for (Iterator iterator = v.iterator(); iterator.hasNext();) {
1429            SiteLanguageSettings sls = (SiteLanguageSettings) iterator.next();
1430            languages.add(sls.getCode());
1431        }
1432
1433        return languages;
1434    }
1435
1436    public String JavaDoc parseBigtextFiles(String JavaDoc rawValue, Set files, ParamBean jParams) throws JahiaException {
1437        String JavaDoc str = " SRC=\"###/webdav";
1438        if (rawValue == null || rawValue.length() == 0 ||
1439                rawValue.toLowerCase().indexOf(str) < 0) {
1440            return rawValue;
1441        }
1442
1443        StringBuffer JavaDoc b = new StringBuffer JavaDoc(rawValue);
1444        int i = -1;
1445        while ((i = b.indexOf(str, i+1)) > -1) {
1446            int from = i + str.length();
1447            int to = b.indexOf("\"", from);
1448            String JavaDoc l = b.substring(from,to);
1449            StringTokenizer st = new StringTokenizer(l,"/");
1450            String JavaDoc fname = "";
1451            while (st.hasMoreTokens()) {
1452                String JavaDoc t = st.nextToken();
1453                fname += "/" + t;
1454                if ("site".equals(t)) {
1455                    String JavaDoc site = st.nextToken();
1456                    fname = "";
1457                }
1458            }
1459            b.replace(from,to,fname);
1460            try {
1461                DAVFileAccess f = new DAVFileAccess(jParams, jParams.getSite(), jParams.getUser(), fname);
1462                if (f.isValid()) {
1463                    files.add(f);
1464                }
1465            } catch (Exception JavaDoc e) {
1466                logger.warn("Invalid link to file "+l);
1467            }
1468
1469        }
1470        return b.toString();
1471    }
1472
1473    public String JavaDoc parseBigtextLinks(String JavaDoc rawValue) throws JahiaException {
1474        if (rawValue == null || rawValue.length() == 0 ||
1475                rawValue.toLowerCase().indexOf(" href") < 0) {
1476            return rawValue;
1477        }
1478
1479        StringBuffer JavaDoc b = new StringBuffer JavaDoc(rawValue);
1480        int i = -1;
1481        while ((i = b.indexOf(" HREF=", i+1)) > -1) {
1482            int j = b.indexOf("/pid/", i);
1483            int l = b.indexOf(" ", i+2);
1484            if (j!=-1 && (l==-1 || j<l)) {
1485                StringBuffer JavaDoc pidb = new StringBuffer JavaDoc();
1486                int k = j+5;
1487                for (; i < b.length() && Character.isDigit(b.charAt(k)); k++) {
1488                    pidb.append(b.charAt(k));
1489                }
1490                try {
1491                    int pid = Integer.parseInt(pidb.toString());
1492                    try {
1493                        String JavaDoc uuid = getUuid(ContentPage.getPage(pid));
1494                        b.replace(j,k,"/ref/"+uuid);
1495                    } catch (JahiaPageNotFoundException e) {
1496                        logger.warn("Invalid link to page "+pid);
1497                    }
1498                } catch (NumberFormatException JavaDoc e) {
1499                    logger.warn("Invalid pid "+pidb);
1500                }
1501            }
1502        }
1503        return b.toString();
1504    }
1505
1506    class Siblings {
1507        List elements = new ArrayList();
1508        boolean printall = false;
1509    }
1510
1511    class Element {
1512        String JavaDoc uri;
1513        String JavaDoc elementName;
1514        String JavaDoc qName;
1515        AttributesImpl JavaDoc attr;
1516        boolean started = false;
1517
1518        public Element(String JavaDoc uri, String JavaDoc elementName, String JavaDoc qName, AttributesImpl JavaDoc attr) {
1519            this.uri = uri;
1520            this.elementName = elementName.replace(' ' , '_');
1521            this.qName = qName;
1522            this.attr = attr;
1523        }
1524    }
1525
1526}
Popular Tags