Salome HOME
app.root property is removed.
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / service / DocumentServiceImpl.java
1 /*****************************************************************************
2  * Company         OPEN CASCADE
3  * Application     SIMAN
4  * File            $Id$ 
5  * Creation date   06.10.2012
6  * @author         $Author$
7  * @version        $Revision$
8  *****************************************************************************/
9
10 package org.splat.service;
11
12 import java.text.DecimalFormat;
13 import java.text.SimpleDateFormat;
14 import java.util.Calendar;
15 import java.util.Iterator;
16 import java.util.List;
17
18 import org.hibernate.criterion.Criterion;
19 import org.hibernate.criterion.Restrictions;
20 import org.splat.dal.bo.kernel.Relation;
21 import org.splat.dal.bo.som.ConvertsRelation;
22 import org.splat.dal.bo.som.Document;
23 import org.splat.dal.bo.som.DocumentType;
24 import org.splat.dal.bo.som.File;
25 import org.splat.dal.bo.som.ProgressState;
26 import org.splat.dal.bo.som.ProjectElement;
27 import org.splat.dal.bo.som.Scenario;
28 import org.splat.dal.bo.som.StampRelation;
29 import org.splat.dal.bo.som.Study;
30 import org.splat.dal.bo.som.Timestamp;
31 import org.splat.dal.bo.som.ValidationStep;
32 import org.splat.dal.bo.som.VersionsRelation;
33 import org.splat.dal.bo.som.Document.Properties;
34 import org.splat.dal.dao.som.DocumentDAO;
35 import org.splat.dal.dao.som.DocumentTypeDAO;
36 import org.splat.dal.dao.som.FileDAO;
37 import org.splat.dal.dao.som.StudyDAO;
38 import org.splat.kernel.InvalidPropertyException;
39 import org.splat.kernel.MissedPropertyException;
40 import org.splat.kernel.NotApplicableException;
41 import org.splat.manox.Reader;
42 import org.splat.manox.Toolbox;
43 import org.splat.service.technical.ProjectSettingsService;
44 import org.splat.service.technical.ProjectSettingsServiceImpl;
45 import org.splat.service.technical.RepositoryService;
46 import org.splat.service.technical.ProjectSettingsServiceImpl.FileNaming;
47 import org.splat.som.Revision;
48 import org.springframework.transaction.annotation.Transactional;
49
50 /**
51  * Document service implementation.
52  * 
53  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
54  * 
55  */
56 public class DocumentServiceImpl implements DocumentService {
57
58         /**
59          * Injected study service.
60          */
61         private StudyService _studyService;
62         /**
63          * Injected project settings service.
64          */
65         private ProjectSettingsService _projectSettingsService;
66         /**
67          * Injected repository service.
68          */
69         private RepositoryService _repositoryService;
70         /**
71          * Injected document DAO.
72          */
73         private DocumentDAO _documentDAO;
74         /**
75          * Injected document type DAO.
76          */
77         private DocumentTypeDAO _documentTypeDAO;
78         /**
79          * Injected file DAO.
80          */
81         private FileDAO _fileDAO;
82         /**
83          * Injected study DAO.
84          */
85         private StudyDAO _studyDAO;
86
87         /**
88          * {@inheritDoc}
89          * 
90          * @see org.splat.service.DocumentService#selectDocument(long)
91          */
92         @Transactional(readOnly = true)
93         public Document selectDocument(long index) {
94                 return getDocumentDAO().get(index);
95         }
96
97         /**
98          * {@inheritDoc}
99          * 
100          * @see org.splat.service.DocumentService#selectDocument(java.lang.String, java.lang.String)
101          */
102         @Transactional(readOnly = true)
103         public Document selectDocument(String refid, String version) {
104                 Criterion aCondition = Restrictions.and(Restrictions.eq("did", refid),
105                                 Restrictions.eq("version", version));
106                 return getDocumentDAO().findByCriteria(aCondition);
107         }
108
109         /**
110          * {@inheritDoc}
111          * 
112          * @see org.splat.service.DocumentService#generateDocumentId(org.splat.dal.bo.som.Document, org.splat.dal.bo.som.Document.Properties)
113          */
114         @Transactional
115         public void generateDocumentId(Document aDoc, Properties dprop) {
116                 Study owner = null;
117                 if (dprop.getOwner() instanceof Study)
118                         owner = (Study) dprop.getOwner();
119                 else
120                         owner = ((Scenario) dprop.getOwner()).getOwnerStudy();
121
122                 // Synchronize the object with the current Hibernate session.
123                 owner = getStudyDAO().get(owner.getIndex());
124                 
125                 SimpleDateFormat tostring = new SimpleDateFormat("yyyy");
126                 String year = tostring.format(owner.getDate());
127                 String filename = generateEncodedName(aDoc, owner);
128                 String path = owner.getReference();
129                 ProjectSettingsService.Step step = ProjectSettingsServiceImpl
130                                 .getStep(aDoc.getStep());
131                 aDoc.setDid(new StringBuffer(path).append(".%")
132                                 .append(Document.suformat).toString()); // Document reference
133                 path = new StringBuffer(year).append("/").append(path).append("/")
134                                 .append(step.getPath())
135                                 // File path relative to the repository vault
136                                 .append(filename).append(".")
137                                 .append(aDoc.getFile().getFormat()) // File name and extension
138                                 .toString();
139                 aDoc.getFile().changePath(path);
140         }
141
142         /**
143          * Generate encoded document file name according to the naming scheme from project settings.
144          * 
145          * @param aDoc
146          *            the document
147          * @param scope
148          *            the study
149          * @return document reference name
150          */
151         private String generateEncodedName(Document aDoc, Study scope) {
152                 StringBuffer encoding = new StringBuffer();
153                 FileNaming scheme = getProjectSettings().getFileNamingScheme();
154                 DecimalFormat tostring = new DecimalFormat(Document.suformat);
155
156                 int number = getStudyService().generateLocalIndex(scope);
157
158                 if (scheme == FileNaming.encoded) {
159                         encoding.append(scope.getReference()).append(".")
160                                         .append(tostring.format(number));
161                 } else { // title and (temporarily) asis
162                         encoding.append(aDoc.getTitle()).append(".")
163                                         .append(tostring.format(number));
164                 }
165                 return encoding.toString();
166         }
167
168         /**
169          * Get encoded root name for a document file.
170          * 
171          * @param aDoc
172          *            the document
173          * @param scope
174          *            the study
175          * @return file name
176          */
177         private String getEncodedRootName(Document aDoc, Study scope) {
178                 FileNaming scheme = getProjectSettings().getFileNamingScheme();
179
180                 if (scheme == FileNaming.encoded)
181                         return scope.getReference();
182                 else
183                         return aDoc.getTitle();
184         }
185
186         /**
187          * {@inheritDoc}
188          * 
189          * @see org.splat.service.DocumentService#initialize(org.splat.dal.bo.som.Document, org.splat.dal.bo.som.Document.Properties)
190          */
191         @Transactional
192         public void initialize(Document aDoc, Properties dprop)
193                         throws MissedPropertyException, InvalidPropertyException,
194                         NotApplicableException {
195                 if (!aDoc.isUndefined())
196                         throw new NotApplicableException(
197                                         "Cannot initialize an existing Document");
198                 if (dprop.getName() == null)
199                         throw new MissedPropertyException("name");
200                 if (dprop.getName().length() == 0)
201                         throw new InvalidPropertyException("name");
202                 if (dprop.getOwner() == null)
203                         throw new MissedPropertyException("owner");
204                 // if (dprop.owner instanceof Study && !ProjectSettings.getStep(step).appliesTo(Study.class)) {
205                 // throw new InvalidPropertyException("step");
206                 // }
207                 aDoc.setTitle(dprop.getName());
208                 aDoc.getFile().changePath(
209                                 aDoc.getFile()
210                                                 .getRelativePath()
211                                                 .replace(
212                                                                 "%n",
213                                                                 getEncodedRootName(aDoc,
214                                                                                 (Study) dprop.getOwner())));
215                 if (aDoc.getHistory() == -1)
216                         aDoc.setHistory(0);
217                 if (dprop.getDate() == null) {
218                         Calendar current = Calendar.getInstance();
219                         aDoc.setLastModificationDate(current.getTime()); // Today
220                 } else {
221                         aDoc.setLastModificationDate(dprop.getDate());
222                 }
223                 getDocumentDAO().update(aDoc);
224         }
225
226         /**
227          * {@inheritDoc}
228          * 
229          * @see org.splat.service.DocumentService#getSaveDirectory(org.splat.dal.bo.som.Document)
230          */
231         public java.io.File getSaveDirectory(Document aDoc) {
232                 String mypath = getRepositoryService().getRepositoryVaultPath()
233                                 + aDoc.getSourceFile().getRelativePath();
234                 String[] table = mypath.split("/");
235
236                 // Cutting the filename
237                 StringBuffer path = new StringBuffer(table[0]);
238                 for (int i = 1; i < table.length - 1; i++)
239                         path = path.append("/").append(table[i]);
240                 return new java.io.File(path.append("/").toString());
241         }
242
243         /**
244          * Extract title and reference properties from the given file.
245          * 
246          * @param file
247          *            the file to parse
248          * @return the extracted properties
249          */
250         public Properties extractProperties(java.io.File file) {
251                 Properties fprop = new Properties();
252                 Reader tool = Toolbox.getReader(file);
253                 String value;
254                 if (tool != null)
255                         try {
256                                 value = tool.extractProperty("title");
257                                 if (value != null)
258                                         fprop.setName(value);
259
260                                 value = tool.extractProperty("reference");
261                                 if (value != null)
262                                         fprop.setReference(value);
263                         } catch (Exception e) {
264                         }
265                 return fprop;
266         }
267
268         /**
269          * Create "Converts" relation for the given document and the given format.
270          * 
271          * @param aDoc
272          *            the document
273          * @param format
274          *            the format
275          * @return the created "Converts" relation
276          */
277         public ConvertsRelation attach(Document aDoc, String format) {
278                 return attach(aDoc, format, null);
279         }
280
281         /**
282          * Create "Converts" relation for the given document, format and description.
283          * 
284          * @param aDoc
285          *            the document
286          * @param format
287          *            the format
288          * @param description
289          *            the description of the relation
290          * @return the created "Converts" relation
291          */
292         @Transactional
293         public ConvertsRelation attach(Document aDoc, String format,
294                         String description) {
295                 String path = aDoc.getRelativePath();
296                 File export = new File(path + "." + format);
297                 ConvertsRelation attach = new ConvertsRelation(aDoc, export,
298                                 description);
299
300                 // RKV session.save(export);
301                 // RKV session.save(attach);
302
303                 getFileDAO().create(export);
304
305                 // RKV aDoc.addRelation(attach); // Updates this
306                 aDoc.getAllRelations().add(attach); // Updates this //RKV
307
308                 return attach;
309         }
310
311         /**
312          * Build a reference (document id) for the given document in the given study basing on the given original document.
313          * 
314          * @param aDoc
315          *            the document to set set the new reference to
316          * @param scope
317          *            the study
318          * @param lineage
319          *            the original document
320          * @return true if the new reference is set
321          */
322         public boolean buildReferenceFrom(Document aDoc, ProjectElement scope,
323                         Document lineage) {
324                 if (aDoc.getProgressState() != ProgressState.inWORK)
325                         return false;
326                 Study owner = null;
327                 Scenario context = null;
328                 if (scope instanceof Study)
329                         owner = (Study) scope;
330                 else {
331                         context = ((Scenario) scope);
332                         owner = context.getOwnerStudy();
333                 }
334                 aDoc.setDid(lineage.getDid());
335                 if (context != null && (lineage.isVersioned() || owner.shares(lineage))) {
336                         aDoc.setVersion(new Revision(aDoc.getVersion()).setBranch(
337                                         context.getReference()).toString());
338                 }
339                 return true;
340         }
341
342         /**
343          * Build a reference (document id) for the given document in the given study.
344          * 
345          * @param aDoc
346          *            the document to set set the new reference to
347          * @param scope
348          *            the study
349          * @return true if the new reference is set
350          */
351         public boolean buildReferenceFrom(Document aDoc, Study scope) {
352                 if (aDoc.getProgressState() != ProgressState.inWORK
353                                 && aDoc.getProgressState() != ProgressState.EXTERN)
354                         return false;
355                 DecimalFormat tostring = new DecimalFormat(Document.suformat);
356
357                 aDoc.setDid(aDoc.getDid().replace("%" + Document.suformat,
358                                 tostring.format(scope.getLastLocalIndex())));
359                 return true;
360         }
361
362         /**
363          * Demote a document.
364          * 
365          * @param aDoc
366          *            the document to demote
367          * @return true if demoting succeeded
368          */
369         @Transactional
370         public boolean demote(Document aDoc) {
371                 ValidationStep torem;
372
373                 if (aDoc.getProgressState() == ProgressState.inCHECK) {
374                         aDoc.setProgressState(ProgressState.inDRAFT);
375                         torem = ValidationStep.REVIEW;
376                         // This operation must not change the version number of documents.
377                         // Consequently, inDRAFT documents may have a minor version number equal to zero.
378                 } else if (aDoc.getProgressState() == ProgressState.inDRAFT) {
379                         aDoc.setProgressState(ProgressState.inWORK);
380                         torem = ValidationStep.PROMOTION;
381                 } else {
382                         return false;
383                 }
384                 for (Iterator<Relation> i = aDoc.getAllRelations().iterator(); i
385                                 .hasNext();) {
386                         Relation link = i.next();
387                         if (!(link instanceof StampRelation))
388                                 continue;
389                         if (((StampRelation) link).getStampType() != torem)
390                                 continue;
391                         i.remove();
392                         break;
393                 }
394                 getDocumentDAO().update(aDoc);
395                 return true;
396         }
397
398         /**
399          * Promote a document.
400          * 
401          * @param aDoc
402          *            the document to promote
403          * @param stamp
404          *            the timestamp of the promotion
405          * @return true if promotion succeeded
406          */
407         @Transactional
408         public boolean promote(Document aDoc, Timestamp stamp) {
409                 ProgressState newstate = null;
410
411                 if (aDoc.getProgressState() == ProgressState.inWORK) {
412                         newstate = ProgressState.inDRAFT; // Promotion to being reviewed
413                 } else if (aDoc.getProgressState() == ProgressState.inDRAFT) {
414                         newstate = ProgressState.inCHECK; // Promotion to approval
415                         Revision myvers = new Revision(aDoc.getVersion());
416                         if (myvers.isMinor()) {
417                                 aDoc.setVersion(myvers.incrementAs(newstate).toString());
418                                 // TODO: If my physical file is programatically editable, update its (property) version number
419                                 // ISSUE: What about attached files such as PDF if exist, should we remove them ?
420                         }
421                 } else if (aDoc.getProgressState() == ProgressState.inCHECK) {
422                         newstate = ProgressState.APPROVED;
423                 }
424                 aDoc.setProgressState(newstate);
425                 if (stamp != null) {
426                         // RKV: aDoc.addRelation(stamp.getContext());
427                         aDoc.getAllRelations().add(stamp.getContext());
428                 }
429                 getDocumentDAO().update(aDoc);
430                 return true;
431         }
432
433         /**
434          * Increments the reference count of this document following its publication in a Study step.
435          * 
436          * @param aDoc
437          *            the document to hold
438          * @see #release()
439          */
440         @Transactional
441         public void hold(Document aDoc) {
442                 aDoc.setCountag(aDoc.getCountag() + 1);
443                 if (aDoc.isSaved()) {
444                         getDocumentDAO().update(aDoc);
445                 }
446         }
447
448         /**
449          * Decrements the reference count of this document following the removal of a Publication from a Study step.
450          * 
451          * @param aDoc
452          *            the document to release
453          * @see #hold()
454          */
455         @Transactional
456         public void release(Document aDoc) {
457                 aDoc.setCountag(aDoc.getCountag() - 1);
458                 if (aDoc.isSaved()) {
459                         getDocumentDAO().merge(aDoc);
460                 }
461         }
462
463         /**
464          * Rename a document.
465          * 
466          * @param aDoc
467          *            the document to rename
468          * @param title
469          *            the new document title
470          * @throws InvalidPropertyException
471          *             if the new title is empty
472          */
473         @Transactional
474         public void rename(Document aDoc, String title)
475                         throws InvalidPropertyException {
476                 if (title.length() == 0)
477                         throw new InvalidPropertyException("name");
478
479                 Calendar current = Calendar.getInstance();
480                 aDoc.setTitle(title);
481                 aDoc.setLastModificationDate(current.getTime()); // Today
482                 getDocumentDAO().update(aDoc);
483         }
484
485         /**
486          * Update a version of the given document.
487          * 
488          * @param aDoc
489          *            the document
490          * @param newvers
491          *            the new version
492          */
493         public void updateAs(Document aDoc, Revision newvers) {
494                 aDoc.setVersion(newvers.setBranch(aDoc.getVersion()).toString()); // Branch names are propagated by the versionning
495                 ProgressState newstate = ProgressState.inCHECK;
496                 if (newvers.isMinor())
497                         newstate = ProgressState.inWORK;
498                 aDoc.setProgressState(null); // Just to tell updateAs(state) to not increment the version number
499                 updateAs(aDoc, newstate);
500         }
501
502         /**
503          * Update a state of the given document.
504          * 
505          * @param aDoc
506          *            the document
507          * @param state
508          *            the new state
509          */
510         @Transactional
511         public void updateAs(Document aDoc, ProgressState state) {
512                 Document previous = null;
513
514                 // Set of version number
515                 if (state == ProgressState.EXTERN) {
516                         if (aDoc.getProgressState() != ProgressState.EXTERN)
517                                 aDoc.setVersion(null); // Strange use-case...
518                 } else {
519                         Revision myvers = new Revision(aDoc.getVersion());
520                         if (!myvers.isNull()) { // Versionning context
521                                 for (Iterator<Relation> i = aDoc.getAllRelations().iterator(); i
522                                                 .hasNext();) {
523                                         Relation link = i.next();
524                                         if (!link.getClass().equals(VersionsRelation.class))
525                                                 continue;
526                                         previous = (Document) link.getTo(); // Versioned document
527                                         break;
528                                 }
529                         }
530                         if (aDoc.getProgressState() != null)
531                                 myvers.incrementAs(state); // Incrementation if the reversion number is not imposed
532                         aDoc.setVersion(myvers.toString());
533                 }
534                 // Update this document and the previous version, if exit
535                 if (previous != null) {
536                         previous.setHistory(previous.getHistory() + 1);
537                         getDocumentDAO().merge(previous);
538                 }
539                 aDoc.setProgressState(state);
540                 getDocumentDAO().update(aDoc);
541         }
542
543         // protected void upgrade () {
544         // -------------------------
545         // if (this.state != ProgressState.inWORK) return;
546         //
547         // Calendar current = Calendar.getInstance();
548         // for (Iterator<Relation> i=getAllRelations().iterator(); i.hasNext();) {
549         // Relation link = i.next();
550         // if (!link.getClass().equals(UsesRelation.class)) continue;
551         //
552         // Document used = (Document)link.getTo();
553         // if (!used.isVersioned()) continue;
554         // TODO: Update the uses relation
555         // }
556         // this.promote();
557         // this.lasdate = current.getTime(); // Today
558         // Database.getSession().update(this);
559         //
560         // TODO: Promote documents using this one
561         // }
562
563         /**
564          * Checks if documents of this type are result of a study. A document is the result of a study when it is the result of the last step of
565          * the study.
566          * 
567          * @param aType
568          *            the document type
569          * @return true if documents of this type are result of a study.
570          * @see #isStepResult()
571          * @see #isResultOf(org.splat.service.technical.ProjectSettingsServiceImpl.Step)
572          */
573         public boolean isStudyResult(DocumentType aType) {
574                 // -------------------------------
575                 List<ProjectSettingsService.Step> step = getProjectSettings()
576                                 .getAllSteps();
577                 ProjectSettingsService.Step lastep = step.get(step.size() - 1);
578                 return (aType.isResultOf(lastep));
579         }
580
581         /**
582          * Get document by its path.
583          * @param path the document path
584          * @return the document if found or null
585          */
586         @Transactional(readOnly=true)
587         public Document getDocumentByPath(String path) {
588                 String[] parse = path.split("'");
589
590                 path = parse[0];
591                 for (int i = 1; i < parse.length; i++) {
592                         path = path + "''" + parse[i];
593                 }
594                 Criterion aCondition = Restrictions.eq("path", path);
595                 return getDocumentDAO().findByCriteria(aCondition);
596         }
597
598         /**
599          * Get the studyService.
600          * 
601          * @return the studyService
602          */
603         public StudyService getStudyService() {
604                 return _studyService;
605         }
606
607         /**
608          * Set the studyService.
609          * 
610          * @param studyService
611          *            the studyService to set
612          */
613         public void setStudyService(StudyService studyService) {
614                 _studyService = studyService;
615         }
616
617         /**
618          * Get project settings.
619          * 
620          * @return Project settings service
621          */
622         private ProjectSettingsService getProjectSettings() {
623                 return _projectSettingsService;
624         }
625
626         /**
627          * Set project settings service.
628          * 
629          * @param projectSettingsService
630          *            project settings service
631          */
632         public void setProjectSettings(ProjectSettingsService projectSettingsService) {
633                 _projectSettingsService = projectSettingsService;
634         }
635
636         /**
637          * Get the documentDAO.
638          * 
639          * @return the documentDAO
640          */
641         public DocumentDAO getDocumentDAO() {
642                 return _documentDAO;
643         }
644
645         /**
646          * Set the documentDAO.
647          * 
648          * @param documentDAO
649          *            the documentDAO to set
650          */
651         public void setDocumentDAO(DocumentDAO documentDAO) {
652                 _documentDAO = documentDAO;
653         }
654
655         /**
656          * Get the repositoryService.
657          * 
658          * @return the repositoryService
659          */
660         public RepositoryService getRepositoryService() {
661                 return _repositoryService;
662         }
663
664         /**
665          * Set the repositoryService.
666          * 
667          * @param repositoryService
668          *            the repositoryService to set
669          */
670         public void setRepositoryService(RepositoryService repositoryService) {
671                 _repositoryService = repositoryService;
672         }
673
674         /**
675          * Get the documentTypeDAO.
676          * 
677          * @return the documentTypeDAO
678          */
679         public DocumentTypeDAO getDocumentTypeDAO() {
680                 return _documentTypeDAO;
681         }
682
683         /**
684          * Set the documentTypeDAO.
685          * 
686          * @param documentTypeDAO
687          *            the documentTypeDAO to set
688          */
689         public void setDocumentTypeDAO(DocumentTypeDAO documentTypeDAO) {
690                 _documentTypeDAO = documentTypeDAO;
691         }
692
693         /**
694          * Get the fileDAO.
695          * 
696          * @return the fileDAO
697          */
698         public FileDAO getFileDAO() {
699                 return _fileDAO;
700         }
701
702         /**
703          * Set the fileDAO.
704          * 
705          * @param fileDAO
706          *            the fileDAO to set
707          */
708         public void setFileDAO(FileDAO fileDAO) {
709                 _fileDAO = fileDAO;
710         }
711
712         /**
713          * Get the studyDAO.
714          * @return the studyDAO
715          */
716         public StudyDAO getStudyDAO() {
717                 return _studyDAO;
718         }
719
720         /**
721          * Set the studyDAO.
722          * @param studyDAO the studyDAO to set
723          */
724         public void setStudyDAO(StudyDAO studyDAO) {
725                 _studyDAO = studyDAO;
726         }
727
728 }