001/*
002 * (C) Copyright 2006-2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019package org.nuxeo.ecm.core.storage.sql.coremodel;
020
021import java.io.Serializable;
022import java.util.ArrayList;
023import java.util.Calendar;
024import java.util.Collection;
025import java.util.Collections;
026import java.util.HashMap;
027import java.util.List;
028import java.util.Map;
029import java.util.Set;
030import java.util.function.Consumer;
031
032import org.nuxeo.ecm.core.NXCore;
033import org.nuxeo.ecm.core.api.DocumentNotFoundException;
034import org.nuxeo.ecm.core.api.LifeCycleException;
035import org.nuxeo.ecm.core.api.Lock;
036import org.nuxeo.ecm.core.api.NuxeoException;
037import org.nuxeo.ecm.core.api.PropertyException;
038import org.nuxeo.ecm.core.api.model.DocumentPart;
039import org.nuxeo.ecm.core.api.model.Property;
040import org.nuxeo.ecm.core.api.model.PropertyNotFoundException;
041import org.nuxeo.ecm.core.api.model.impl.ComplexProperty;
042import org.nuxeo.ecm.core.blob.DocumentBlobManager;
043import org.nuxeo.ecm.core.lifecycle.LifeCycle;
044import org.nuxeo.ecm.core.lifecycle.LifeCycleService;
045import org.nuxeo.ecm.core.model.Document;
046import org.nuxeo.ecm.core.schema.DocumentType;
047import org.nuxeo.ecm.core.schema.SchemaManager;
048import org.nuxeo.ecm.core.schema.types.ComplexType;
049import org.nuxeo.ecm.core.schema.types.Field;
050import org.nuxeo.ecm.core.schema.types.ListType;
051import org.nuxeo.ecm.core.schema.types.Schema;
052import org.nuxeo.ecm.core.schema.types.Type;
053import org.nuxeo.ecm.core.storage.BaseDocument;
054import org.nuxeo.ecm.core.storage.sql.Model;
055import org.nuxeo.ecm.core.storage.sql.Node;
056import org.nuxeo.runtime.api.Framework;
057
058public class SQLDocumentLive extends BaseDocument<Node>implements SQLDocument {
059
060    protected final Node node;
061
062    protected final Type type;
063
064    protected SQLSession session;
065
066    /** Proxy-induced types. */
067    protected final List<Schema> proxySchemas;
068
069    /**
070     * Read-only flag, used to allow/disallow writes on versions.
071     */
072    protected boolean readonly;
073
074    protected SQLDocumentLive(Node node, ComplexType type, SQLSession session, boolean readonly) {
075        this.node = node;
076        this.type = type;
077        this.session = session;
078        if (node != null && node.isProxy()) {
079            SchemaManager schemaManager = Framework.getLocalService(SchemaManager.class);
080            proxySchemas = schemaManager.getProxySchemas(type.getName());
081        } else {
082            proxySchemas = null;
083        }
084        this.readonly = readonly;
085    }
086
087    @Override
088    public void setReadOnly(boolean readonly) {
089        this.readonly = readonly;
090    }
091
092    @Override
093    public boolean isReadOnly() {
094        return readonly;
095    }
096
097    @Override
098    public Node getNode() {
099        return node;
100    }
101
102    @Override
103    public String getName() {
104        return getNode() == null ? null : getNode().getName();
105    }
106
107    @Override
108    public Long getPos() {
109        return getNode().getPos();
110    }
111
112    /*
113     * ----- org.nuxeo.ecm.core.model.Document -----
114     */
115
116    @Override
117    public DocumentType getType() {
118        return (DocumentType) type;
119    }
120
121    @Override
122    public SQLSession getSession() {
123        return session;
124    }
125
126    @Override
127    public boolean isFolder() {
128        return type == null // null document
129                || ((DocumentType) type).isFolder();
130    }
131
132    @Override
133    public String getUUID() {
134        return session.idToString(getNode().getId());
135    }
136
137    @Override
138    public Document getParent() {
139        return session.getParent(getNode());
140    }
141
142    @Override
143    public String getPath() {
144        return session.getPath(getNode());
145    }
146
147    @Override
148    public boolean isProxy() {
149        return false;
150    }
151
152    @Override
153    public String getRepositoryName() {
154        return session.getRepositoryName();
155    }
156
157    @Override
158    protected List<Schema> getProxySchemas() {
159        return proxySchemas;
160    }
161
162    @Override
163    public void remove() {
164        session.remove(getNode());
165    }
166
167    /**
168     * Reads into the {@link DocumentPart} the values from this {@link SQLDocument}.
169     */
170    @Override
171    public void readDocumentPart(DocumentPart dp) throws PropertyException {
172        readComplexProperty(getNode(), (ComplexProperty) dp);
173    }
174
175    @Override
176    public Map<String, Serializable> readPrefetch(ComplexType complexType, Set<String> xpaths)
177            throws PropertyException {
178        return readPrefetch(getNode(), complexType, xpaths);
179    }
180
181    @Override
182    public boolean writeDocumentPart(DocumentPart dp, WriteContext writeContext) throws PropertyException {
183        boolean changed = writeComplexProperty(getNode(), (ComplexProperty) dp, writeContext);
184        clearDirtyFlags(dp);
185        return changed;
186    }
187
188    @Override
189    protected Node getChild(Node node, String name, Type type) throws PropertyException {
190        return session.getChildProperty(node, name, type.getName());
191    }
192
193    @Override
194    protected Node getChildForWrite(Node node, String name, Type type) throws PropertyException {
195        return session.getChildPropertyForWrite(node, name, type.getName());
196    }
197
198    @Override
199    protected List<Node> getChildAsList(Node node, String name) throws PropertyException {
200        return session.getComplexList(node, name);
201    }
202
203    @Override
204    protected void updateList(Node node, String name, Field field, String xpath, List<Object> values)
205            throws PropertyException {
206        List<Node> childNodes = getChildAsList(node, name);
207        int oldSize = childNodes.size();
208        int newSize = values.size();
209        // remove extra list elements
210        if (oldSize > newSize) {
211            for (int i = oldSize - 1; i >= newSize; i--) {
212                session.removeProperty(childNodes.remove(i));
213            }
214        }
215        // add new list elements
216        if (oldSize < newSize) {
217            String typeName = field.getType().getName();
218            for (int i = oldSize; i < newSize; i++) {
219                Node childNode = session.addChildProperty(node, name, Long.valueOf(i), typeName);
220                childNodes.add(childNode);
221            }
222        }
223        // write values
224        int i = 0;
225        for (Object v : values) {
226            Node childNode = childNodes.get(i);
227            setValueComplex(childNode, field, xpath + '/' + i, v);
228            i++;
229        }
230    }
231
232    @Override
233    protected List<Node> updateList(Node node, String name, Property property) throws PropertyException {
234        Collection<Property> properties = property.getChildren();
235        List<Node> childNodes = getChildAsList(node, name);
236        int oldSize = childNodes.size();
237        int newSize = properties.size();
238        // remove extra list elements
239        if (oldSize > newSize) {
240            for (int i = oldSize - 1; i >= newSize; i--) {
241                session.removeProperty(childNodes.remove(i));
242            }
243        }
244        // add new list elements
245        if (oldSize < newSize) {
246            String typeName = ((ListType) property.getType()).getFieldType().getName();
247            for (int i = oldSize; i < newSize; i++) {
248                Node childNode = session.addChildProperty(node, name, Long.valueOf(i), typeName);
249                childNodes.add(childNode);
250            }
251        }
252        return childNodes;
253    }
254
255    @Override
256    protected String internalName(String name) {
257        return name;
258    }
259
260    @Override
261    public Object getValue(String xpath) throws PropertyException {
262        return getValueObject(getNode(), xpath);
263    }
264
265    @Override
266    public void setValue(String xpath, Object value) throws PropertyException {
267        setValueObject(getNode(), xpath, value);
268    }
269
270    @Override
271    public void visitBlobs(Consumer<BlobAccessor> blobVisitor) throws PropertyException {
272        visitBlobs(getNode(), blobVisitor, NO_DIRTY);
273    }
274
275    @Override
276    public Serializable getPropertyValue(String name) {
277        return getNode().getSimpleProperty(name).getValue();
278    }
279
280    @Override
281    public void setPropertyValue(String name, Serializable value) {
282        getNode().setSimpleProperty(name, value);
283    }
284
285    protected static final Map<String, String> systemPropNameMap;
286
287    static {
288        systemPropNameMap = new HashMap<String, String>();
289        systemPropNameMap.put(FULLTEXT_JOBID_SYS_PROP, Model.FULLTEXT_JOBID_PROP);
290    }
291
292    @Override
293    public void setSystemProp(String name, Serializable value) {
294        String propertyName;
295        if (name.startsWith(SIMPLE_TEXT_SYS_PROP)) {
296            propertyName = name.replace(SIMPLE_TEXT_SYS_PROP, Model.FULLTEXT_SIMPLETEXT_PROP);
297        } else if (name.startsWith(BINARY_TEXT_SYS_PROP)) {
298            propertyName = name.replace(BINARY_TEXT_SYS_PROP, Model.FULLTEXT_BINARYTEXT_PROP);
299        } else {
300            propertyName = systemPropNameMap.get(name);
301        }
302        if (propertyName == null) {
303            throw new PropertyNotFoundException(name, "Unknown system property");
304        }
305        setPropertyValue(propertyName, value);
306    }
307
308    @Override
309    @SuppressWarnings("unchecked")
310    public <T extends Serializable> T getSystemProp(String name, Class<T> type) {
311        String propertyName = systemPropNameMap.get(name);
312        if (propertyName == null) {
313            throw new PropertyNotFoundException(name, "Unknown system property");
314        }
315        Serializable value = getPropertyValue(propertyName);
316        if (value == null) {
317            if (type == Boolean.class) {
318                value = Boolean.FALSE;
319            } else if (type == Long.class) {
320                value = Long.valueOf(0);
321            }
322        }
323        return (T) value;
324    }
325
326    @Override
327    public String getChangeToken() {
328        if (session.isChangeTokenEnabled()) {
329            Long sysChangeToken = (Long) getPropertyValue(Model.MAIN_SYS_CHANGE_TOKEN_PROP);
330            Long changeToken = (Long) getPropertyValue(Model.MAIN_CHANGE_TOKEN_PROP);
331            return buildUserVisibleChangeToken(sysChangeToken, changeToken);
332        } else {
333            Calendar modified;
334            try {
335                modified = (Calendar) getPropertyValue(DC_MODIFIED);
336            } catch (PropertyNotFoundException e) {
337                modified = null;
338            }
339            return getLegacyChangeToken(modified);
340        }
341    }
342
343    @Override
344    public boolean validateUserVisibleChangeToken(String userVisibleChangeToken) {
345        if (userVisibleChangeToken == null) {
346            return true;
347        }
348        if (session.isChangeTokenEnabled()) {
349            Long sysChangeToken = (Long) getPropertyValue(Model.MAIN_SYS_CHANGE_TOKEN_PROP);
350            Long changeToken = (Long) getPropertyValue(Model.MAIN_CHANGE_TOKEN_PROP);
351            return validateUserVisibleChangeToken(sysChangeToken, changeToken, userVisibleChangeToken);
352        } else {
353            Calendar modified;
354            try {
355                modified = (Calendar) getPropertyValue(DC_MODIFIED);
356            } catch (PropertyNotFoundException e) {
357                modified = null;
358            }
359            return validateLegacyChangeToken(modified, userVisibleChangeToken);
360        }
361    }
362
363    @Override
364    public void markUserChange() {
365        session.markUserChange(getNode().getId());
366    }
367
368    /*
369     * ----- LifeCycle -----
370     */
371
372    @Override
373    public String getLifeCyclePolicy() {
374        return (String) getPropertyValue(Model.MISC_LIFECYCLE_POLICY_PROP);
375    }
376
377    @Override
378    public void setLifeCyclePolicy(String policy) {
379        setPropertyValue(Model.MISC_LIFECYCLE_POLICY_PROP, policy);
380        DocumentBlobManager blobManager = Framework.getService(DocumentBlobManager.class);
381        blobManager.notifyChanges(this, Collections.singleton(Model.MISC_LIFECYCLE_POLICY_PROP));
382    }
383
384    @Override
385    public String getLifeCycleState() {
386        return (String) getPropertyValue(Model.MISC_LIFECYCLE_STATE_PROP);
387    }
388
389    @Override
390    public void setCurrentLifeCycleState(String state) {
391        setPropertyValue(Model.MISC_LIFECYCLE_STATE_PROP, state);
392        DocumentBlobManager blobManager = Framework.getService(DocumentBlobManager.class);
393        blobManager.notifyChanges(this, Collections.singleton(Model.MISC_LIFECYCLE_STATE_PROP));
394    }
395
396    @Override
397    public void followTransition(String transition) throws LifeCycleException {
398        LifeCycleService service = NXCore.getLifeCycleService();
399        if (service == null) {
400            throw new NuxeoException("LifeCycleService not available");
401        }
402        service.followTransition(this, transition);
403    }
404
405    @Override
406    public Collection<String> getAllowedStateTransitions() {
407        LifeCycleService service = NXCore.getLifeCycleService();
408        if (service == null) {
409            throw new NuxeoException("LifeCycleService not available");
410        }
411        LifeCycle lifeCycle = service.getLifeCycleFor(this);
412        if (lifeCycle == null) {
413            return Collections.emptyList();
414        }
415        return lifeCycle.getAllowedStateTransitionsFrom(getLifeCycleState());
416    }
417
418    /*
419     * ----- org.nuxeo.ecm.core.versioning.VersionableDocument -----
420     */
421
422    @Override
423    public boolean isVersion() {
424        return false;
425    }
426
427    @Override
428    public Document getBaseVersion() {
429        if (isCheckedOut()) {
430            return null;
431        }
432        Serializable id = (Serializable) getPropertyValue(Model.MAIN_BASE_VERSION_PROP);
433        if (id == null) {
434            // shouldn't happen
435            return null;
436        }
437        return session.getDocumentById(id);
438    }
439
440    @Override
441    public String getVersionSeriesId() {
442        return getUUID();
443    }
444
445    @Override
446    public Document getSourceDocument() {
447        return this;
448    }
449
450    @Override
451    public Document checkIn(String label, String checkinComment) {
452        Document version = session.checkIn(getNode(), label, checkinComment);
453        DocumentBlobManager blobManager = Framework.getService(DocumentBlobManager.class);
454        blobManager.freezeVersion(version);
455        return version;
456    }
457
458    @Override
459    public void checkOut() {
460        session.checkOut(getNode());
461    }
462
463    @Override
464    public boolean isCheckedOut() {
465        return !Boolean.TRUE.equals(getPropertyValue(Model.MAIN_CHECKED_IN_PROP));
466    }
467
468    @Override
469    public boolean isMajorVersion() {
470        return false;
471    }
472
473    @Override
474    public boolean isLatestVersion() {
475        return false;
476    }
477
478    @Override
479    public boolean isLatestMajorVersion() {
480        return false;
481    }
482
483    @Override
484    public boolean isVersionSeriesCheckedOut() {
485        return isCheckedOut();
486    }
487
488    @Override
489    public String getVersionLabel() {
490        return (String) getPropertyValue(Model.VERSION_LABEL_PROP);
491    }
492
493    @Override
494    public String getCheckinComment() {
495        return (String) getPropertyValue(Model.VERSION_DESCRIPTION_PROP);
496    }
497
498    @Override
499    public Document getWorkingCopy() {
500        return this;
501    }
502
503    @Override
504    public Calendar getVersionCreationDate() {
505        return (Calendar) getPropertyValue(Model.VERSION_CREATED_PROP);
506    }
507
508    @Override
509    public void restore(Document version) {
510        if (!version.isVersion()) {
511            throw new NuxeoException("Cannot restore a non-version: " + version);
512        }
513        session.restore(getNode(), ((SQLDocument) version).getNode());
514    }
515
516    @Override
517    public List<String> getVersionsIds() {
518        String versionSeriesId = getVersionSeriesId();
519        Collection<Document> versions = session.getVersions(versionSeriesId);
520        List<String> ids = new ArrayList<String>(versions.size());
521        for (Document version : versions) {
522            ids.add(version.getUUID());
523        }
524        return ids;
525    }
526
527    @Override
528    public Document getVersion(String label) {
529        String versionSeriesId = getVersionSeriesId();
530        return session.getVersionByLabel(versionSeriesId, label);
531    }
532
533    @Override
534    public List<Document> getVersions() {
535        String versionSeriesId = getVersionSeriesId();
536        return session.getVersions(versionSeriesId);
537    }
538
539    @Override
540    public Document getLastVersion() {
541        String versionSeriesId = getVersionSeriesId();
542        return session.getLastVersion(versionSeriesId);
543    }
544
545    @Override
546    public Document getChild(String name) {
547        return session.getChild(getNode(), name);
548    }
549
550    @Override
551    public List<Document> getChildren() {
552        if (!isFolder()) {
553            return Collections.emptyList();
554        }
555        return session.getChildren(getNode()); // newly allocated
556    }
557
558    @Override
559    public List<String> getChildrenIds() {
560        if (!isFolder()) {
561            return Collections.emptyList();
562        }
563        // not optimized as this method doesn't seem to be used
564        List<Document> children = session.getChildren(getNode());
565        List<String> ids = new ArrayList<String>(children.size());
566        for (Document child : children) {
567            ids.add(child.getUUID());
568        }
569        return ids;
570    }
571
572    @Override
573    public boolean hasChild(String name) {
574        if (!isFolder()) {
575            return false;
576        }
577        return session.hasChild(getNode(), name);
578    }
579
580    @Override
581    public boolean hasChildren() {
582        if (!isFolder()) {
583            return false;
584        }
585        return session.hasChildren(getNode());
586    }
587
588    @Override
589    public Document addChild(String name, String typeName) {
590        if (!isFolder()) {
591            throw new IllegalArgumentException("Not a folder");
592        }
593        return session.addChild(getNode(), name, null, typeName);
594    }
595
596    @Override
597    public void orderBefore(String src, String dest) {
598        SQLDocument srcDoc = (SQLDocument) getChild(src);
599        if (srcDoc == null) {
600            throw new DocumentNotFoundException("Document " + this + " has no child: " + src);
601        }
602        SQLDocument destDoc;
603        if (dest == null) {
604            destDoc = null;
605        } else {
606            destDoc = (SQLDocument) getChild(dest);
607            if (destDoc == null) {
608                throw new DocumentNotFoundException("Document " + this + " has no child: " + dest);
609            }
610        }
611        session.orderBefore(getNode(), srcDoc.getNode(), destDoc == null ? null : destDoc.getNode());
612    }
613
614    @Override
615    public Set<String> getAllFacets() {
616        return getNode().getAllMixinTypes();
617    }
618
619    @Override
620    public String[] getFacets() {
621        return getNode().getMixinTypes();
622    }
623
624    @Override
625    public boolean hasFacet(String facet) {
626        return getNode().hasMixinType(facet);
627    }
628
629    @Override
630    public boolean addFacet(String facet) {
631        return session.addMixinType(getNode(), facet);
632    }
633
634    @Override
635    public boolean removeFacet(String facet) {
636        return session.removeMixinType(getNode(), facet);
637    }
638
639    /*
640     * ----- PropertyContainer inherited from SQLComplexProperty -----
641     */
642
643    /*
644     * ----- toString/equals/hashcode -----
645     */
646
647    @Override
648    public String toString() {
649        return getClass().getSimpleName() + '(' + getName() + ',' + getUUID() + ')';
650    }
651
652    @Override
653    public boolean equals(Object other) {
654        if (other == this) {
655            return true;
656        }
657        if (other == null) {
658            return false;
659        }
660        if (other.getClass() == this.getClass()) {
661            return equals((SQLDocumentLive) other);
662        }
663        return false;
664    }
665
666    private boolean equals(SQLDocumentLive other) {
667        return getNode().equals(other.getNode());
668    }
669
670    @Override
671    public int hashCode() {
672        return getNode().hashCode();
673    }
674
675    @Override
676    public Document getTargetDocument() {
677        return null;
678    }
679
680    @Override
681    public void setTargetDocument(Document target) {
682        throw new NuxeoException("Not a proxy");
683    }
684
685    @Override
686    protected Lock getDocumentLock() {
687        // lock manager can get the lock even on a recently created and unsaved document
688        throw new UnsupportedOperationException();
689    }
690
691    @Override
692    protected Lock setDocumentLock(Lock lock) {
693        // lock manager can set the lock even on a recently created and unsaved document
694        throw new UnsupportedOperationException();
695    }
696
697    @Override
698    protected Lock removeDocumentLock(String owner) {
699        // lock manager can remove the lock even on a recently created and unsaved document
700        throw new UnsupportedOperationException();
701    }
702
703}