1 /*****************************************************************************
5 * Creation date 06.10.2012
8 *****************************************************************************/
10 package org.splat.service;
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;
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;
51 * Document service implementation.
53 * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
56 public class DocumentServiceImpl implements DocumentService {
59 * Injected study service.
61 private StudyService _studyService;
63 * Injected project settings service.
65 private ProjectSettingsService _projectSettingsService;
67 * Injected repository service.
69 private RepositoryService _repositoryService;
71 * Injected document DAO.
73 private DocumentDAO _documentDAO;
75 * Injected document type DAO.
77 private DocumentTypeDAO _documentTypeDAO;
81 private FileDAO _fileDAO;
85 private StudyDAO _studyDAO;
90 * @see org.splat.service.DocumentService#selectDocument(long)
92 @Transactional(readOnly = true)
93 public Document selectDocument(long index) {
94 return getDocumentDAO().get(index);
100 * @see org.splat.service.DocumentService#selectDocument(java.lang.String, java.lang.String)
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);
112 * @see org.splat.service.DocumentService#generateDocumentId(org.splat.dal.bo.som.Document, org.splat.dal.bo.som.Document.Properties)
115 public void generateDocumentId(Document aDoc, Properties dprop) {
117 if (dprop.getOwner() instanceof Study)
118 owner = (Study) dprop.getOwner();
120 owner = ((Scenario) dprop.getOwner()).getOwnerStudy();
122 // Synchronize the object with the current Hibernate session.
123 owner = getStudyDAO().get(owner.getIndex());
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
139 aDoc.getFile().changePath(path);
143 * Generate encoded document file name according to the naming scheme from project settings.
149 * @return document reference name
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);
156 int number = getStudyService().generateLocalIndex(scope);
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));
165 return encoding.toString();
169 * Get encoded root name for a document file.
177 private String getEncodedRootName(Document aDoc, Study scope) {
178 FileNaming scheme = getProjectSettings().getFileNamingScheme();
180 if (scheme == FileNaming.encoded)
181 return scope.getReference();
183 return aDoc.getTitle();
189 * @see org.splat.service.DocumentService#initialize(org.splat.dal.bo.som.Document, org.splat.dal.bo.som.Document.Properties)
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");
207 aDoc.setTitle(dprop.getName());
208 aDoc.getFile().changePath(
213 getEncodedRootName(aDoc,
214 (Study) dprop.getOwner())));
215 if (aDoc.getHistory() == -1)
217 if (dprop.getDate() == null) {
218 Calendar current = Calendar.getInstance();
219 aDoc.setLastModificationDate(current.getTime()); // Today
221 aDoc.setLastModificationDate(dprop.getDate());
223 getDocumentDAO().update(aDoc);
229 * @see org.splat.service.DocumentService#getSaveDirectory(org.splat.dal.bo.som.Document)
231 public java.io.File getSaveDirectory(Document aDoc) {
232 String mypath = getRepositoryService().getRepositoryVaultPath()
233 + aDoc.getSourceFile().getRelativePath();
234 String[] table = mypath.split("/");
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());
244 * Extract title and reference properties from the given file.
248 * @return the extracted properties
250 public Properties extractProperties(java.io.File file) {
251 Properties fprop = new Properties();
252 Reader tool = Toolbox.getReader(file);
256 value = tool.extractProperty("title");
258 fprop.setName(value);
260 value = tool.extractProperty("reference");
262 fprop.setReference(value);
263 } catch (Exception e) {
269 * Create "Converts" relation for the given document and the given format.
275 * @return the created "Converts" relation
277 public ConvertsRelation attach(Document aDoc, String format) {
278 return attach(aDoc, format, null);
282 * Create "Converts" relation for the given document, format and description.
289 * the description of the relation
290 * @return the created "Converts" relation
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,
300 // RKV session.save(export);
301 // RKV session.save(attach);
303 getFileDAO().create(export);
305 // RKV aDoc.addRelation(attach); // Updates this
306 aDoc.getAllRelations().add(attach); // Updates this //RKV
312 * Build a reference (document id) for the given document in the given study basing on the given original document.
315 * the document to set set the new reference to
319 * the original document
320 * @return true if the new reference is set
322 public boolean buildReferenceFrom(Document aDoc, ProjectElement scope,
324 if (aDoc.getProgressState() != ProgressState.inWORK)
327 Scenario context = null;
328 if (scope instanceof Study)
329 owner = (Study) scope;
331 context = ((Scenario) scope);
332 owner = context.getOwnerStudy();
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());
343 * Build a reference (document id) for the given document in the given study.
346 * the document to set set the new reference to
349 * @return true if the new reference is set
351 public boolean buildReferenceFrom(Document aDoc, Study scope) {
352 if (aDoc.getProgressState() != ProgressState.inWORK
353 && aDoc.getProgressState() != ProgressState.EXTERN)
355 DecimalFormat tostring = new DecimalFormat(Document.suformat);
357 aDoc.setDid(aDoc.getDid().replace("%" + Document.suformat,
358 tostring.format(scope.getLastLocalIndex())));
366 * the document to demote
367 * @return true if demoting succeeded
370 public boolean demote(Document aDoc) {
371 ValidationStep torem;
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;
384 for (Iterator<Relation> i = aDoc.getAllRelations().iterator(); i
386 Relation link = i.next();
387 if (!(link instanceof StampRelation))
389 if (((StampRelation) link).getStampType() != torem)
394 getDocumentDAO().update(aDoc);
399 * Promote a document.
402 * the document to promote
404 * the timestamp of the promotion
405 * @return true if promotion succeeded
408 public boolean promote(Document aDoc, Timestamp stamp) {
409 ProgressState newstate = null;
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 ?
421 } else if (aDoc.getProgressState() == ProgressState.inCHECK) {
422 newstate = ProgressState.APPROVED;
424 aDoc.setProgressState(newstate);
426 // RKV: aDoc.addRelation(stamp.getContext());
427 aDoc.getAllRelations().add(stamp.getContext());
429 getDocumentDAO().update(aDoc);
434 * Increments the reference count of this document following its publication in a Study step.
437 * the document to hold
441 public void hold(Document aDoc) {
442 aDoc.setCountag(aDoc.getCountag() + 1);
443 if (aDoc.isSaved()) {
444 getDocumentDAO().update(aDoc);
449 * Decrements the reference count of this document following the removal of a Publication from a Study step.
452 * the document to release
456 public void release(Document aDoc) {
457 aDoc.setCountag(aDoc.getCountag() - 1);
458 if (aDoc.isSaved()) {
459 getDocumentDAO().merge(aDoc);
467 * the document to rename
469 * the new document title
470 * @throws InvalidPropertyException
471 * if the new title is empty
474 public void rename(Document aDoc, String title)
475 throws InvalidPropertyException {
476 if (title.length() == 0)
477 throw new InvalidPropertyException("name");
479 Calendar current = Calendar.getInstance();
480 aDoc.setTitle(title);
481 aDoc.setLastModificationDate(current.getTime()); // Today
482 getDocumentDAO().update(aDoc);
486 * Update a version of the given document.
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);
503 * Update a state of the given document.
511 public void updateAs(Document aDoc, ProgressState state) {
512 Document previous = null;
514 // Set of version number
515 if (state == ProgressState.EXTERN) {
516 if (aDoc.getProgressState() != ProgressState.EXTERN)
517 aDoc.setVersion(null); // Strange use-case...
519 Revision myvers = new Revision(aDoc.getVersion());
520 if (!myvers.isNull()) { // Versionning context
521 for (Iterator<Relation> i = aDoc.getAllRelations().iterator(); i
523 Relation link = i.next();
524 if (!link.getClass().equals(VersionsRelation.class))
526 previous = (Document) link.getTo(); // Versioned document
530 if (aDoc.getProgressState() != null)
531 myvers.incrementAs(state); // Incrementation if the reversion number is not imposed
532 aDoc.setVersion(myvers.toString());
534 // Update this document and the previous version, if exit
535 if (previous != null) {
536 previous.setHistory(previous.getHistory() + 1);
537 getDocumentDAO().merge(previous);
539 aDoc.setProgressState(state);
540 getDocumentDAO().update(aDoc);
543 // protected void upgrade () {
544 // -------------------------
545 // if (this.state != ProgressState.inWORK) return;
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;
552 // Document used = (Document)link.getTo();
553 // if (!used.isVersioned()) continue;
554 // TODO: Update the uses relation
557 // this.lasdate = current.getTime(); // Today
558 // Database.getSession().update(this);
560 // TODO: Promote documents using this one
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
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)
573 public boolean isStudyResult(DocumentType aType) {
574 // -------------------------------
575 List<ProjectSettingsService.Step> step = getProjectSettings()
577 ProjectSettingsService.Step lastep = step.get(step.size() - 1);
578 return (aType.isResultOf(lastep));
582 * Get document by its path.
583 * @param path the document path
584 * @return the document if found or null
586 @Transactional(readOnly=true)
587 public Document getDocumentByPath(String path) {
588 String[] parse = path.split("'");
591 for (int i = 1; i < parse.length; i++) {
592 path = path + "''" + parse[i];
594 Criterion aCondition = Restrictions.eq("path", path);
595 return getDocumentDAO().findByCriteria(aCondition);
599 * Get the studyService.
601 * @return the studyService
603 public StudyService getStudyService() {
604 return _studyService;
608 * Set the studyService.
610 * @param studyService
611 * the studyService to set
613 public void setStudyService(StudyService studyService) {
614 _studyService = studyService;
618 * Get project settings.
620 * @return Project settings service
622 private ProjectSettingsService getProjectSettings() {
623 return _projectSettingsService;
627 * Set project settings service.
629 * @param projectSettingsService
630 * project settings service
632 public void setProjectSettings(ProjectSettingsService projectSettingsService) {
633 _projectSettingsService = projectSettingsService;
637 * Get the documentDAO.
639 * @return the documentDAO
641 public DocumentDAO getDocumentDAO() {
646 * Set the documentDAO.
649 * the documentDAO to set
651 public void setDocumentDAO(DocumentDAO documentDAO) {
652 _documentDAO = documentDAO;
656 * Get the repositoryService.
658 * @return the repositoryService
660 public RepositoryService getRepositoryService() {
661 return _repositoryService;
665 * Set the repositoryService.
667 * @param repositoryService
668 * the repositoryService to set
670 public void setRepositoryService(RepositoryService repositoryService) {
671 _repositoryService = repositoryService;
675 * Get the documentTypeDAO.
677 * @return the documentTypeDAO
679 public DocumentTypeDAO getDocumentTypeDAO() {
680 return _documentTypeDAO;
684 * Set the documentTypeDAO.
686 * @param documentTypeDAO
687 * the documentTypeDAO to set
689 public void setDocumentTypeDAO(DocumentTypeDAO documentTypeDAO) {
690 _documentTypeDAO = documentTypeDAO;
696 * @return the fileDAO
698 public FileDAO getFileDAO() {
708 public void setFileDAO(FileDAO fileDAO) {
714 * @return the studyDAO
716 public StudyDAO getStudyDAO() {
722 * @param studyDAO the studyDAO to set
724 public void setStudyDAO(StudyDAO studyDAO) {
725 _studyDAO = studyDAO;