001/*
002 * (C) Copyright 2018 Nuxeo (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 *     Antoine Taillefer <ataillefer@nuxeo.com>
018 */
019package org.nuxeo.ecm.platform.thumbnail.work;
020
021import org.nuxeo.ecm.core.api.DocumentModel;
022import org.nuxeo.ecm.core.api.DocumentModelList;
023import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
024import org.nuxeo.ecm.core.work.AbstractWork;
025import org.nuxeo.ecm.platform.thumbnail.ThumbnailConstants;
026
027/**
028 * Work to recompute the thumbnail of the documents resulting from the provided NXQL query.
029 *
030 * @since 10.10
031 */
032public class ThumbnailRecomputeWork extends AbstractWork {
033
034    private static final long serialVersionUID = 1L;
035
036    protected static final int BATCH_SIZE = 10;
037
038    protected String nxqlQuery;
039
040    public ThumbnailRecomputeWork(String repositoryName, String nxqlQuery) {
041        this.repositoryName = repositoryName;
042        this.nxqlQuery = nxqlQuery;
043    }
044
045    @Override
046    public String getTitle() {
047        return "Thumbnails Recomputation";
048    }
049
050    @Override
051    public void work() {
052        setProgress(Progress.PROGRESS_INDETERMINATE);
053
054        openSystemSession();
055        DocumentModelList docs = session.query(nxqlQuery);
056        long docsUpdated = 0;
057
058        setStatus("Generating thumbnails");
059        for (DocumentModel doc : docs) {
060            if (doc.hasFacet(ThumbnailConstants.THUMBNAIL_FACET)) {
061                BlobHolder blobHolder = doc.getAdapter(BlobHolder.class);
062                if (blobHolder.getBlob() != null) {
063                    // make sure the blob property is dirty for the CheckBlobUpdateListener to trigger the
064                    // UpdateThumbnailListener
065                    blobHolder.setBlob(blobHolder.getBlob());
066                    session.saveDocument(doc);
067                    docsUpdated++;
068                    if (docsUpdated % BATCH_SIZE == 0) {
069                        commitOrRollbackTransaction();
070                        startTransaction();
071                    }
072                }
073            }
074        }
075        setStatus("Done");
076    }
077
078}