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

org.n3r.eql.impl.EqlResourceLoaderHelper Maven / Gradle / Ivy

There is a newer version: 0.1.19
Show newest version
package org.n3r.eql.impl;

import com.google.common.base.Optional;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.n3r.eql.base.EqlResourceLoader;
import org.n3r.eql.parser.EqlBlock;
import org.n3r.eql.parser.EqlParser;

import java.util.HashMap;
import java.util.Map;

@Slf4j @UtilityClass
public class EqlResourceLoaderHelper {
    public LoadingCache> buildSqlCache(
            final Cache>> fileCache) {
        return CacheBuilder.newBuilder().build(new CacheLoader>() {
            @Override
            public Optional load(EqlUniqueSqlId eqlUniqueSqlId) {
                return loadBlocks(fileCache, eqlUniqueSqlId);
            }
        });
    }

    private Optional loadBlocks(
            Cache>> fileCache,
            EqlUniqueSqlId sqlId) {
        val blocks = fileCache.getIfPresent(sqlId.getSqlClassPath());
        val eqlBlock = blocks.get().get(sqlId.getSqlId());
        if (eqlBlock == null) return Optional.absent();

        eqlBlock.tryParseSqls();
        return Optional.of(eqlBlock);
    }

    public void updateBlockCache(
            String sqlContent,
            EqlResourceLoader eqlResourceLoader,
            String sqlClassPath,
            Cache> sqlCache,
            Cache>> fileCache) {
        val oldBlocks = fileCache.getIfPresent(sqlClassPath);
        val oldSqlIds = oldBlocks.or(new HashMap<>()).keySet();

        val parser = new EqlParser(eqlResourceLoader, sqlClassPath);
        val blocks = parser.parse(sqlContent);

        for (val block : blocks.values()) {
            val uniqueSqlId = block.getUniqueSqlId();
            sqlCache.put(uniqueSqlId, Optional.of(block));
            oldSqlIds.remove(uniqueSqlId.getSqlId());
        }

        for (val uniqueId : oldSqlIds) {
            sqlCache.invalidate(EqlUniqueSqlId.of(sqlClassPath, uniqueId));
        }

        fileCache.put(sqlClassPath, Optional.of(blocks));
    }

    public Map updateFileCache(
            String sqlContent,
            EqlResourceLoader eqlResourceLoader,
            String sqlClassPath, boolean eqlLazyLoad) {
        val parser = new EqlParser(eqlResourceLoader, sqlClassPath);
        return eqlLazyLoad ? parser.delayParse(sqlContent) : parser.parse(sqlContent);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy