view src/luan/modules/lucene/SupplementingConfig.java @ 1578:c922446f53aa

immutable threading
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 08 Feb 2021 14:16:19 -0700
parents 8fbcc4747091
children 46cf5137cb6b
line wrap: on
line source

package luan.modules.lucene;

import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Collections;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.SnapshotDeletionPolicy;
import org.apache.lucene.util.Version;
import goodjava.lucene.queryparser.MultiFieldParser;
import goodjava.lucene.api.MultiFieldParserConfig;
import goodjava.lucene.api.MoreFieldInfo;
import luan.Luan;
import luan.LuanFunction;
import luan.LuanTable;
import luan.LuanMutable;
import luan.LuanException;
import luan.LuanRuntimeException;


final class SupplementingConfig extends MultiFieldParserConfig {
	private final Luan luan;
	private final LuanFunction supplementer;

	SupplementingConfig(Version luceneVersion,MultiFieldParser mfp,Luan luan,LuanFunction supplementer) throws LuanException {
		super(luceneVersion,mfp);
		this.luan = new Luan(luan);
		LuanMutable.makeImmutable(supplementer);
		this.supplementer = supplementer;
	}

	@Override public IndexWriterConfig newLuceneConfig() {
		IndexWriterConfig luceneConfig = super.newLuceneConfig();
		SnapshotDeletionPolicy snapshotDeletionPolicy = new SnapshotDeletionPolicy(luceneConfig.getIndexDeletionPolicy());
		luceneConfig.setIndexDeletionPolicy(snapshotDeletionPolicy);
		return luceneConfig;
	}

	@Override public MoreFieldInfo getMoreFieldInfo(Map<String,Object> storedFields) {
		if( supplementer == null )
			return super.getMoreFieldInfo(storedFields);
		try {
			LuanTable tbl = toTable(storedFields);
			synchronized(luan) {
				tbl = (LuanTable)supplementer.call(luan,tbl);
			}
			if( tbl == null ) {
				return super.getMoreFieldInfo(storedFields);
			} else {
				return new MoreFieldInfo(toLucene(tbl),Collections.emptyMap());
			}
		} catch(LuanException e) {
			throw new LuanRuntimeException(e);
		}
	}

	static LuanTable toTable(Map map) throws LuanException {
		LuanTable table = new LuanTable();
		for( Object obj : map.entrySet() ) {
			Map.Entry entry = (Map.Entry)obj;
			Object value = entry.getValue();
			if( value instanceof List )
				value = new LuanTable((List)value);
			table.rawPut( entry.getKey(), value );
		}
		return table;
	}

	static Map<String,Object> toLucene(LuanTable table) throws LuanException {
		Map<String,Object> map = new LinkedHashMap<String,Object>();
		for( Map.Entry<Object,Object> entry : table.rawIterable() ) {
			String name = (String)entry.getKey();
			Object value  = entry.getValue();
			if( value instanceof LuanTable ) {
				LuanTable list = (LuanTable)value;
				if( !list.isList() )
					throw new LuanException("table value for '"+name+"' must be a list");
				value = list.asList();
			}
			map.put(name,value);
		}
		return map;
	}

}