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

com.thematchbox.river.sessions.files.FilesSessionDelegator 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.sessions.files;

/* 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.google.common.base.Preconditions;
import com.thematchbox.river.actions.IndexJob;
import com.thematchbox.river.sessions.SessionDelegator;
import com.thematchbox.river.sessions.SessionException;
import com.thematchbox.river.sessions.tools.FileHelper;
import com.thematchbox.river.sessions.tools.UpdateTimeHelper;
import com.thematchbox.river.docs.DocumentReader;
import com.thematchbox.river.docs.DocumentType;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class FilesSessionDelegator implements SessionDelegator {

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

    private File folder;
    private boolean recursive;
    private FileFilter fileFilter = null;
    private Set fileExtensions;
    private Map uuidToFileMap;
    private DocumentReader documentReader;

    public FilesSessionDelegator(File folder, DocumentReader documentReader, boolean recursive) {
        this.documentReader = documentReader;
        this.recursive = recursive;
        if (!folder.exists()) {
            logger.warn("Folder " + folder.getPath() + " does not exist.");
        }

        this.folder = folder;
        fileExtensions = new HashSet<>();
        for (DocumentType documentType : DocumentType.values()) {
            fileExtensions.add(documentType.extension);
        }

        fileFilter = new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if (pathname.isDirectory()) {
                    return true;
                }
                String name = pathname.getName();
                int index = name.lastIndexOf(".");

                return index != -1 && fileExtensions.contains(name.substring(index));
            }
        };
    }

    protected List getFiles(File folder) {
        List files = new ArrayList<>();
        getFiles(folder, files);
        return files;
    }

    private void getFiles(File folder, List fileList) {
        File[] files = folder.listFiles(fileFilter);
        for (File file : files) {
            if (file.isFile()) {
                fileList.add(file);
            } else if (recursive) {
                getFiles(file, fileList);
            }
        }
    }

    @Override
    public void openSession() throws SessionException {
    }

    @Override
    public void closeSession() throws SessionException {
    }

    @Override
    public void reset() {
    }

    @Override
    public List getObjects(Class clazz, List ids) throws SessionException {
        Preconditions.checkArgument(uuidToFileMap != null, "No id to file mapping available. getAllIds must be called first.");

        List fileDocuments = new ArrayList<>();
        for (String id : ids) {
            Preconditions.checkArgument(uuidToFileMap.containsKey(id), "Invalid id to file mapping: no file found for id {}.", id);
            File file = uuidToFileMap.get(id);
            DocumentType docType = DocumentType.getDocType(file.getName());
            try (InputStream inputStream = new FileInputStream(file)) {
                String content = documentReader.read(inputStream, docType);
                fileDocuments.add(new FileDocument(id, file.getPath(), file.getName(), content, docType));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                fileDocuments.add(new FileDocument(id, file.getPath(), file.getName(), null, docType));
            }
        }

        return fileDocuments;
    }

    @Override
    public List getAllIds(Class clazz, Client client, IndexJob indexJob) throws SessionException {
        try {
            buildUuidMap();
            if (client != null && indexJob != null) {
                UpdateTimeHelper.setUpdateTime(new Date(), client, indexJob);
            }

            if (uuidToFileMap.isEmpty()) {
                logger.warn("Folder " + folder.getPath() + " is empty.");
            } else if (indexJob != null && logger.isDebugEnabled()) {
                logger.debug("Index {}, type {}: {} items to index.", indexJob.indexKey.indexName, indexJob.indexKey.indexType, uuidToFileMap.size());
            }



            return new ArrayList<>(uuidToFileMap.keySet());
        } catch (IOException e) {
            throw new SessionException(e);
        }
    }

    private void buildUuidMap() {
        uuidToFileMap = new HashMap<>();
        List files = getFiles(folder);
        for (File file : files) {
            String uuid = FileHelper.getUUID(file);
            if (uuidToFileMap.containsKey(uuid)) {
                throw new IllegalStateException("Duplicate file ids for files " + file.getPath() + " and " + uuidToFileMap.get(uuid).getPath());
            }

            uuidToFileMap.put(uuid, file);
        }
    }

    @SuppressWarnings("UnusedDeclaration")
    public List getIdsToUpdate(Client client, IndexJob indexJob) throws IOException {
        buildUuidMap();

        Date updateTime = UpdateTimeHelper.getUpdateTime(client, indexJob);
        UpdateTimeHelper.setUpdateTime(new Date(), client, indexJob);
        if (updateTime != null) {
            List ids = new ArrayList<>();
            for (String uuid : uuidToFileMap.keySet()) {
                File file = uuidToFileMap.get(uuid);
                if (logger.isTraceEnabled()) {
                    logger.trace("Checking for update uid {} for file {}", uuid, file.getPath());
                }
                if (file.lastModified() > updateTime.getTime()) {
                    ids.add(uuid);
                    if (logger.isDebugEnabled()) {
                        logger.debug("File is modified: uid {} for file {}", uuid, file.getPath());
                    }
                } else if (!client.prepareGet(indexJob.indexKey.indexName, indexJob.indexKey.indexType, uuid).execute().actionGet().isExists()) {
                    ids.add(uuid);
                    if (logger.isDebugEnabled()) {
                        logger.debug("File is new: uid {} for file {}", uuid, file.getPath());
                    }
                }
            }

            if (!ids.isEmpty()) {
                logger.debug("Index {}, type {}: {} items to update.", indexJob.indexKey.indexName, indexJob.indexKey.indexType, ids.size());
            }
            if (logger.isTraceEnabled()) {
                logger.debug("Index {}, type {}: 0 items to update.", indexJob.indexKey.indexName, indexJob.indexKey.indexType);
            }

            return ids;
        } else {
            return new ArrayList<>(uuidToFileMap.keySet());
        }
    }

    @SuppressWarnings("UnusedDeclaration")
    public List getIdsToDelete(Client client, IndexJob indexJob) throws ExecutionException, InterruptedException {
        buildUuidMap();

        List idsToDelete = new ArrayList<>();

        TimeValue keepAlive = new TimeValue(60, TimeUnit.SECONDS);
        SearchResponse searchResponse = client.prepareSearch(indexJob.indexKey.indexName).setTypes(indexJob.indexKey.indexType).setSearchType(SearchType.SCAN).setSize(100).setScroll(keepAlive).setQuery(QueryBuilders.matchAllQuery()).setNoFields().execute().actionGet();
        String scrollId = searchResponse.getScrollId();
        long total = searchResponse.getHits().getTotalHits();
        logger.debug("Index {}, type {}: {} items to check for delete, scrollId {}.", indexJob.indexKey.indexName, indexJob.indexKey.indexType, total, scrollId);


        long count = 0;

        while (count < total) {
            searchResponse = client.prepareSearchScroll(scrollId).setScroll(keepAlive).execute().actionGet();
            SearchHit[] hits = searchResponse.getHits().hits();
            scrollId = searchResponse.getScrollId();
            count += hits.length;
            logger.trace("Index {}, type {}: {} items retrieved to check for delete.", indexJob.indexKey.indexName, indexJob.indexKey.indexType, count);

            for (SearchHit hit : hits) {
                String id = hit.getId();
                if (!uuidToFileMap.containsKey(id)) {
                    idsToDelete.add(id);
                    if (logger.isDebugEnabled()) {
                        logger.debug("File is deleted: uid {}", id);
                    }
                } else if (logger.isTraceEnabled()) {
                    logger.trace("Checking for delete uid {} for file {}, scrollId {}", id, uuidToFileMap.get(id).getPath(), scrollId);
                }
            }
        }
        client.prepareClearScroll().addScrollId(scrollId).execute().get();

        if (!idsToDelete.isEmpty()) {
            logger.debug("Index {}, type {}: {} items to delete.", indexJob.indexKey.indexName, indexJob.indexKey.indexType, idsToDelete.size());
        } else {
            logger.debug("Index {}, type {}: No items to delete.", indexJob.indexKey.indexName, indexJob.indexKey.indexType);
        }

        return idsToDelete;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy