All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.thematchbox.river.MatchBoxRiver Maven / Gradle / Ivy

Go to download

This project contains an abstract implementation of an ElasticSearch River and is used as a basis for custom river implementations.

There is a newer version: 1.1.3
Show newest version
package com.thematchbox.river;

/* Copyright 2015 theMatchBox

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

import com.thematchbox.river.actions.ActionType;
import com.thematchbox.river.actions.IndexJob;
import com.thematchbox.river.indexers.MatchBoxIndexerManager;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.river.AbstractRiverComponent;
import org.elasticsearch.river.River;
import org.elasticsearch.river.RiverName;
import org.elasticsearch.river.RiverSettings;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

public class MatchBoxRiver extends AbstractRiverComponent implements River {

    public static final Logger logger = LoggerFactory.getLogger(MatchBoxRiver.class);

    private Scheduler scheduler = null;

    public static final String INDEX_NAME = "indexName";
    public static final String INDEX_TYPE = "indexType";
    public static final String CRON_TAB = "cronTab";
    public static final String ACTION_TYPE = "actionType";

    public static final String JOB = "job";
    public static final String INDEXING_MANAGER = "indexingManager";

    @Inject
    public MatchBoxRiver(RiverName riverName, RiverSettings settings, MatchBoxIndexerManager matchBoxIndexerManager) {
        super(riverName, settings);


        Map settingsMap = settings.settings();

        List indices = new ArrayList<>();
        if (settingsMap.containsKey(INDEX_NAME)) {
            Object o = settingsMap.get(INDEX_NAME);


            if (indices.getClass().isInstance(o)) {
                //noinspection unchecked
                indices = indices.getClass().cast(o);
            } else if (o instanceof String) {
                indices.add(o.toString());
            }
        }
        if (indices.isEmpty()) {
            throw new MatchBoxRiverException("River parameter " + INDEX_NAME + " is missing. Add one or more index names.");
        }

        List types = new ArrayList<>();
        if (settingsMap.containsKey(INDEX_TYPE)) {
            Object o = settingsMap.get(INDEX_TYPE);


            if (indices.getClass().isInstance(o)) {
                //noinspection unchecked
                types = types.getClass().cast(o);
            } else if (o instanceof String) {
                types.add(o.toString());
            }
        }
        if (types.isEmpty()) {
            throw new MatchBoxRiverException("River parameter " + INDEX_TYPE + " is missing. Add one or more index types.");
        }

        CronScheduleBuilder cronScheduleBuilder = null;
        String cronTab = null;
        if (settingsMap.containsKey(CRON_TAB)) {
            Object o = settingsMap.get(CRON_TAB);
            if (o instanceof String) {
                cronTab = (String) o;
                cronScheduleBuilder = cronSchedule(cronTab);
            }
        }
        if (cronScheduleBuilder == null) {
            throw new MatchBoxRiverException("River parameter " + CRON_TAB + " is missing. Add a valid crontab expression like \"0 0/5 * * * ?\" (every 5 minutes).");
        }

        List actionTypeStrings = new ArrayList<>();
        List actionTypes = new ArrayList<>();
        if (settingsMap.containsKey(ACTION_TYPE)) {
            Object o = settingsMap.get(ACTION_TYPE);
            if (actionTypeStrings.getClass().isInstance(o)) {
                //noinspection unchecked
                actionTypeStrings = actionTypeStrings.getClass().cast(o);
                for (String actionTypeString : actionTypeStrings) {
                    actionTypes.add(ActionType.valueOf(actionTypeString));
                }
            } else if (o instanceof String) {
                String actionTypeStr = (String) o;
                try {
                    actionTypes.add(ActionType.valueOf(actionTypeStr));
                } catch (IllegalArgumentException e) {
                    throw new MatchBoxRiverException("River parameter " + ACTION_TYPE + " is invalid. Choose one of " + Arrays.toString(ActionType.values()) + ".", e);
                }
            }
        }
        if (actionTypes.isEmpty()) {
            throw new MatchBoxRiverException("River parameter " + ACTION_TYPE + " is missing. Add one or more values of " + Arrays.toString(ActionType.values()) + ".");
        }

        try {
            scheduler = StdSchedulerFactory.getDefaultScheduler();

            for (String indexName : indices) {
                for (String indexType : types) {
                    for (ActionType actionType : actionTypes) {
                        com.thematchbox.river.actions.IndexJob request = new com.thematchbox.river.actions.IndexJob(actionType, indexName, indexType);

                        JobDataMap jobDataMap = new JobDataMap();
                        jobDataMap.put(JOB, request);
                        jobDataMap.put(CRON_TAB, cronTab);
                        jobDataMap.put(INDEXING_MANAGER, matchBoxIndexerManager);

                        JobDetail job = newJob(ScheduledIndexJob.class).withIdentity(riverName.name(), createJobName(indexName, indexType, actionType)).usingJobData(jobDataMap).build();
                        Trigger trigger = newTrigger().withSchedule(cronScheduleBuilder.withMisfireHandlingInstructionDoNothing()).build();
                        scheduler.scheduleJob(job, trigger);
                    }
                }
            }

        } catch (SchedulerException e) {
            logger.error(e.getMessage(), e);
        }
    }

    private String createJobName(String indexName, String indexType, ActionType actionType) {
        return indexName + "_" + indexType + "_" + actionType.name();
    }

    @Override
    public void start() {
        try {
            scheduler.start();
        } catch (SchedulerException e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public void close() {
        try {
            scheduler.shutdown();
        } catch (SchedulerException e) {
            logger.error(e.getMessage(), e);
        }
    }

    @DisallowConcurrentExecution
    public static class ScheduledIndexJob implements Job {

        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
            JobDataMap mergedJobDataMap = context.getMergedJobDataMap();
            IndexJob indexJob = (IndexJob) mergedJobDataMap.get(JOB);
            MatchBoxIndexerManager indexerManager = (MatchBoxIndexerManager) mergedJobDataMap.get(INDEXING_MANAGER);
            indexerManager.addRequest(indexJob);
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy