001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo
016 */
017
018package org.nuxeo.elasticsearch.work;
019
020import org.nuxeo.elasticsearch.api.ElasticSearchIndexing;
021import org.nuxeo.elasticsearch.commands.IndexingCommand;
022import org.nuxeo.runtime.api.Framework;
023
024import java.util.ArrayList;
025import java.util.List;
026
027/**
028 * Abstract class for sharing code between ElasticSearch related workers
029 *
030 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
031 */
032public abstract class AbstractIndexingWorker extends BaseIndexingWorker {
033
034    private static final long serialVersionUID = 1L;
035
036    protected final List<IndexingCommand> cmds;
037
038    public AbstractIndexingWorker(IndexingCommand cmd) {
039        this.cmds = new ArrayList<>(1);
040        this.cmds.add(cmd);
041        this.repositoryName = cmd.getRepositoryName();
042        this.docId = cmd.getTargetDocumentId();
043    }
044
045    public AbstractIndexingWorker(String repositoryName, List<IndexingCommand> cmds) {
046        this.cmds = cmds;
047        this.repositoryName = repositoryName;
048        if (! cmds.isEmpty()) {
049            this.docId = cmds.get(0).getTargetDocumentId();
050        }
051    }
052
053    @Override
054    public void doWork() {
055        initSession();
056        for (IndexingCommand cmd: cmds) {
057            cmd.attach(session);
058        }
059        ElasticSearchIndexing esi = Framework.getLocalService(ElasticSearchIndexing.class);
060        doIndexingWork(esi, cmds);
061    }
062
063    protected abstract void doIndexingWork(ElasticSearchIndexing esi, List<IndexingCommand> cmds);
064
065}