001/*
002 * (C) Copyright 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 *     Nuxeo
018 */
019
020package org.nuxeo.elasticsearch.work;
021
022import org.nuxeo.elasticsearch.api.ElasticSearchIndexing;
023import org.nuxeo.elasticsearch.commands.IndexingCommand;
024import org.nuxeo.runtime.api.Framework;
025
026import java.util.ArrayList;
027import java.util.List;
028
029/**
030 * Abstract class for sharing code between ElasticSearch related workers
031 *
032 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
033 */
034public abstract class AbstractIndexingWorker extends BaseIndexingWorker {
035
036    private static final long serialVersionUID = 1L;
037
038    protected final List<IndexingCommand> cmds;
039
040    public AbstractIndexingWorker(IndexingCommand cmd) {
041        this.cmds = new ArrayList<>(1);
042        this.cmds.add(cmd);
043        this.repositoryName = cmd.getRepositoryName();
044        this.docId = cmd.getTargetDocumentId();
045    }
046
047    public AbstractIndexingWorker(String repositoryName, List<IndexingCommand> cmds) {
048        this.cmds = cmds;
049        this.repositoryName = repositoryName;
050        if (! cmds.isEmpty()) {
051            this.docId = cmds.get(0).getTargetDocumentId();
052        }
053    }
054
055    @Override
056    public void doWork() {
057        openSystemSession();
058        for (IndexingCommand cmd: cmds) {
059            cmd.attach(session);
060        }
061        ElasticSearchIndexing esi = Framework.getLocalService(ElasticSearchIndexing.class);
062        doIndexingWork(esi, cmds);
063    }
064
065    protected abstract void doIndexingWork(ElasticSearchIndexing esi, List<IndexingCommand> cmds);
066
067}