text
stringlengths
30
1.67M
<s> package com . senseidb . search . client . req . relevance ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import com . senseidb . search . client . json . JsonField ; import com . senseidb . search . client . req . FacetType ; public class Model { private Map < String , List < String > > variables = new HashMap < String , List < String > > ( ) ; ; private Map < String , List < String > > facets = new HashMap < String , List < String > > ( ) ; @ JsonField ( "<STR_LIT>" ) private List < String > functionParams = new ArrayList < String > ( ) ; private String function ; @ JsonField ( "<STR_LIT>" ) private SaveAs saveAs ; public static ModelBuilder builder ( ) { return new ModelBuilder ( ) ; } public static class ModelBuilder { private final Model model ; public ModelBuilder ( ) { this . model = new Model ( ) ; } public ModelBuilder function ( String function ) { this . model . function = function ; return this ; } public ModelBuilder addFunctionParams ( String ... params ) { if ( params != null ) { this . model . functionParams . addAll ( Arrays . asList ( params ) ) ; } return this ; } public ModelBuilder addFacets ( RelevanceFacetType type , String ... names ) { if ( names != null ) { List < String > facets = this . model . facets . get ( type . getValue ( ) ) ; if ( facets == null ) { facets = new ArrayList < String > ( ) ; this . model . facets . put ( type . getValue ( ) , facets ) ; } facets . addAll ( Arrays . asList ( names ) ) ; } return this ; } public ModelBuilder addVariables ( VariableType type , String ... variables ) { if ( variables != null ) { List < String > variablesList = this . model . variables . get ( type . getValue ( ) ) ; if ( variablesList == null ) { variablesList = new ArrayList < String > ( ) ; this . model . variables . put ( type . getValue ( ) , variablesList ) ; } variablesList . addAll ( Arrays . asList ( variables ) ) ; } return this ; } public ModelBuilder saveAs ( String name , boolean overwrite ) { this . model . saveAs = new SaveAs ( name , overwrite ) ; return this ; } public Model build ( ) { return model ; } } } </s>
<s> package com . senseidb . search . client . req . relevance ; public class SaveAs { private String name ; private boolean overwrite ; public SaveAs ( String name , boolean overwrite ) { super ( ) ; this . name = name ; this . overwrite = overwrite ; } public String getName ( ) { return name ; } public boolean isOverwrite ( ) { return overwrite ; } } </s>
<s> package com . senseidb . search . client . req . relevance ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; public class RelevanceValues { protected Map < String , Object > values = new HashMap < String , Object > ( ) ; public static RelevanceValuesBuilder builder ( ) { return new RelevanceValuesBuilder ( ) ; } public Map < String , Object > getValues ( ) { return values ; } private RelevanceValues ( ) { } public static class RelevanceValuesBuilder { private RelevanceValues relevanceValues ; public RelevanceValuesBuilder ( ) { relevanceValues = new RelevanceValues ( ) ; } public RelevanceValuesBuilder addListValue ( String variableName , Object ... values ) { for ( Object value : values ) { checkType ( value ) ; } relevanceValues . values . put ( variableName , Arrays . asList ( values ) ) ; return this ; } public RelevanceValuesBuilder addAtomicValue ( String variableName , Object value ) { checkType ( value ) ; relevanceValues . values . put ( variableName , value ) ; return this ; } private void checkType ( Object value ) { if ( ! ( value instanceof String ) && ! ( value instanceof Number ) ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } } public RelevanceValuesBuilder addMapValue ( String variableName , List keys , List values ) { for ( int i = <NUM_LIT:0> ; i < keys . size ( ) ; i ++ ) { checkType ( keys . get ( i ) ) ; checkType ( values . get ( i ) ) ; } Map < String , Object > ret = new HashMap < String , Object > ( <NUM_LIT:2> ) ; ret . put ( "<STR_LIT:key>" , keys ) ; ret . put ( "<STR_LIT:value>" , values ) ; relevanceValues . values . put ( variableName , ret ) ; return this ; } public RelevanceValuesBuilder addMapValue ( String variableName , Map < Object , Object > valuesMap ) { List < Object > keys = new ArrayList < Object > ( valuesMap . size ( ) ) ; List < Object > values = new ArrayList < Object > ( valuesMap . size ( ) ) ; for ( Map . Entry < Object , Object > entry : valuesMap . entrySet ( ) ) { checkType ( entry . getKey ( ) ) ; checkType ( entry . getValue ( ) ) ; keys . add ( entry . getKey ( ) ) ; values . add ( entry . getValue ( ) ) ; } Map < String , Object > ret = new HashMap < String , Object > ( <NUM_LIT:2> ) ; ret . put ( "<STR_LIT:key>" , keys ) ; ret . put ( "<STR_LIT:value>" , values ) ; relevanceValues . values . put ( variableName , ret ) ; return this ; } public RelevanceValues build ( ) { return relevanceValues ; } } } </s>
<s> package com . senseidb . search . client . req . relevance ; public enum RelevanceFacetType { type_int , type_long , type_double , type_float , type_short , type_string , type_mint , type_mlong , type_mdouble , type_mfloat , type_mshort , type_mstring , type_wmint , type_wmlong , type_wmdouble , type_wmfloat , type_wmshort , type_wmstring ; public String getValue ( ) { return this . name ( ) . substring ( "<STR_LIT>" . length ( ) ) ; } } </s>
<s> package com . senseidb . search . client . req . relevance ; import com . senseidb . search . client . json . CustomJsonHandler ; public class Relevance { private Model model ; @ CustomJsonHandler ( value = RelevanceValuesHandler . class ) private RelevanceValues values ; private Relevance ( ) { } public static Relevance valueOf ( Model model , RelevanceValues values ) { Relevance relevance = new Relevance ( ) ; relevance . model = model ; relevance . values = values ; return relevance ; } } </s>
<s> package com . senseidb . search . client . req . relevance ; public enum VariableType { set_int , set_float , set_string , set_double , set_long , map_int_int , map_int_double , map_int_float , map_int_long , map_int_bool , map_int_string , map_string_int , map_string_double , map_string_float , map_string_long , map_string_bool , map_string_string , type_int , type_double , type_float , type_long , type_bool , type_string ; public String getValue ( ) { if ( this . name ( ) . startsWith ( "<STR_LIT>" ) ) { return this . name ( ) . substring ( "<STR_LIT>" . length ( ) ) ; } return this . name ( ) ; } } </s>
<s> package com . senseidb . search . client . req . relevance ; import org . json . JSONException ; import org . json . JSONObject ; import com . senseidb . search . client . json . JsonHandler ; import com . senseidb . search . client . json . JsonSerializer ; public class RelevanceValuesHandler implements JsonHandler < RelevanceValues > { @ Override public JSONObject serialize ( RelevanceValues bean ) throws JSONException { if ( bean == null ) { return null ; } return ( JSONObject ) JsonSerializer . serialize ( bean . values ) ; } @ Override public RelevanceValues deserialize ( JSONObject json ) throws JSONException { throw new UnsupportedOperationException ( ) ; } } </s>
<s> package com . senseidb . search . client . req ; public enum Operator { and , or ; } </s>
<s> package com . senseidb . search . client . req ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map ; import org . json . JSONException ; import org . json . JSONObject ; import com . senseidb . search . client . json . JsonDeserializer ; import com . senseidb . search . client . json . JsonHandler ; import com . senseidb . search . client . json . JsonSerializer ; public class SelectionJsonHandler implements JsonHandler < Selection > { public static Map < String , Class < ? extends Selection > > selectionClasses = new HashMap < String , Class < ? extends Selection > > ( ) ; static { for ( Class < ? extends Selection > cls : Arrays . asList ( Term . class , Terms . class , Path . class , Range . class , Selection . Custom . class ) ) { selectionClasses . put ( cls . getSimpleName ( ) . toLowerCase ( ) , cls ) ; } } @ Override public JSONObject serialize ( Selection bean ) throws JSONException { if ( bean == null ) { return null ; } if ( bean instanceof Selection . Custom ) { JSONObject ret = new JSONObject ( ) ; ret . put ( "<STR_LIT>" , ( ( Selection . Custom ) bean ) . getCustom ( ) ) ; return ret ; } JSONObject innerObject = ( JSONObject ) JsonSerializer . serialize ( bean , false ) ; JSONObject paramContainer = new JSONObject ( ) ; paramContainer . put ( bean . getField ( ) , innerObject ) ; JSONObject ret = new JSONObject ( ) ; ret . put ( bean . getClass ( ) . getSimpleName ( ) . toLowerCase ( ) , paramContainer ) ; return ret ; } @ Override public Selection deserialize ( JSONObject json ) throws JSONException { String [ ] names = JSONObject . getNames ( json ) ; if ( names . length == <NUM_LIT:0> || ! selectionClasses . keySet ( ) . contains ( names [ <NUM_LIT:0> ] ) ) { throw new IllegalStateException ( "<STR_LIT>" + Arrays . toString ( names ) ) ; } String name = names [ <NUM_LIT:0> ] ; JSONObject innerPart = json . getJSONObject ( name ) ; if ( "<STR_LIT>" . equals ( name ) ) { return Selection . custom ( innerPart ) ; } String fieldName = JSONObject . getNames ( innerPart ) [ <NUM_LIT:0> ] ; Selection selection = JsonDeserializer . deserialize ( selectionClasses . get ( name ) , innerPart . getJSONObject ( fieldName ) , false ) ; selection . setField ( fieldName ) ; return selection ; } } </s>
<s> package com . senseidb . search . client . req ; public class Path extends Selection { private String value ; private boolean strict ; private int depth ; public Path ( String value , boolean strict , int depth ) { super ( ) ; this . value = value ; this . strict = strict ; this . depth = depth ; } public Path ( ) { } public String getValue ( ) { return value ; } } </s>
<s> package com . senseidb . search . client . req ; public class Paging { private int count ; private int offset ; public Paging ( ) { } public Paging ( int count , int offset ) { super ( ) ; this . count = count ; this . offset = offset ; } } </s>
<s> package com . senseidb . search . client . req ; import java . util . List ; import com . senseidb . search . client . json . JsonField ; public class RequestMetadata { @ JsonField ( "<STR_LIT>" ) private List < String > shownOnlyFields ; public RequestMetadata ( List < String > shownOnlyFields ) { super ( ) ; this . shownOnlyFields = shownOnlyFields ; } } </s>
<s> package com . senseidb . search . client . req ; import java . util . HashMap ; import java . util . Map ; public class Facet { int max ; int minHit ; boolean expand ; OrderBy order ; Map < String , String > properties = new HashMap < String , String > ( ) ; public static enum OrderBy { hits , val } public static class Builder { private Facet facet = new Facet ( ) ; public Builder max ( int max ) { facet . max = max ; return this ; } public Builder minHit ( int minCount ) { facet . minHit = minCount ; return this ; } public Builder expand ( boolean expand ) { facet . expand = expand ; return this ; } public Builder orderByHits ( ) { facet . order = OrderBy . hits ; return this ; } public Builder orderByVal ( ) { facet . order = OrderBy . val ; return this ; } public Builder addProperty ( String name , String value ) { facet . properties . put ( name , value ) ; return this ; } public Facet build ( ) { return facet ; } } public static Builder builder ( ) { return new Builder ( ) ; } } </s>
<s> package com . senseidb . gateway . kafka ; public final class DataPacket { public final byte [ ] data ; public final int offset ; public final int size ; public DataPacket ( byte [ ] data , int offset , int size ) { this . data = data ; this . offset = offset ; this . size = size ; } } </s>
<s> package com . senseidb . gateway . kafka ; import java . io . ByteArrayOutputStream ; import org . apache . avro . io . BinaryDecoder ; import org . apache . avro . io . BinaryEncoder ; import org . apache . avro . io . DecoderFactory ; import org . apache . avro . specific . SpecificDatumReader ; import org . apache . avro . specific . SpecificDatumWriter ; public class AvroSerializerHelper { public static < V > byte [ ] toBytes ( V v , Class < V > cls ) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; SpecificDatumWriter < V > writer = new SpecificDatumWriter < V > ( cls ) ; BinaryEncoder binEncoder = new BinaryEncoder ( bout ) ; writer . write ( v , binEncoder ) ; binEncoder . flush ( ) ; return bout . toByteArray ( ) ; } public static < V > V fromBytes ( byte [ ] bytes , Class < V > cls ) throws Exception { SpecificDatumReader < V > reader = new SpecificDatumReader < V > ( cls ) ; BinaryDecoder binDecoder = DecoderFactory . defaultFactory ( ) . createBinaryDecoder ( bytes , null ) ; V val = cls . newInstance ( ) ; reader . read ( val , binDecoder ) ; return val ; } } </s>
<s> package com . senseidb . gateway . kafka ; import java . nio . charset . Charset ; import org . json . JSONObject ; import com . senseidb . indexing . DataSourceFilter ; public class DefaultJsonDataSourceFilter extends DataSourceFilter < DataPacket > { public final static Charset UTF8 = Charset . forName ( "<STR_LIT:UTF-8>" ) ; @ Override protected JSONObject doFilter ( DataPacket packet ) throws Exception { String jsonString = new String ( packet . data , packet . offset , packet . size , UTF8 ) ; return new JSONObject ( jsonString ) ; } } </s>
<s> package com . senseidb . gateway . kafka ; import java . nio . ByteBuffer ; import java . util . Comparator ; import kafka . api . FetchRequest ; import kafka . api . OffsetRequest ; import kafka . consumer . SimpleConsumer ; import kafka . message . ByteBufferMessageSet ; import kafka . message . MessageAndOffset ; import org . apache . log4j . Logger ; import org . json . JSONObject ; import proj . zoie . api . DataConsumer . DataEvent ; import proj . zoie . impl . indexing . StreamDataProvider ; import scala . collection . Iterator ; import com . senseidb . indexing . DataSourceFilter ; public class SimpleKafkaStreamDataProvider extends StreamDataProvider < JSONObject > { private final String _topic ; private long _offset ; private long _startingOffset ; private SimpleConsumer _kafkaConsumer ; private Iterator < MessageAndOffset > _msgIter ; private ThreadLocal < byte [ ] > bytesFactory ; private static Logger logger = Logger . getLogger ( KafkaStreamDataProvider . class ) ; public static final int DEFAULT_MAX_MSG_SIZE = <NUM_LIT:5> * <NUM_LIT> * <NUM_LIT> ; private final String _kafkaHost ; private final int _kafkaPort ; private final int _kafkaSoTimeout ; private volatile boolean _started = false ; private final DataSourceFilter < DataPacket > _dataConverter ; public SimpleKafkaStreamDataProvider ( Comparator < String > versionComparator , String kafkaHost , int kafkaPort , int soTimeout , int batchSize , String topic , long startingOffset , DataSourceFilter < DataPacket > dataConverter ) { super ( versionComparator ) ; _topic = topic ; _startingOffset = startingOffset ; _offset = startingOffset ; super . setBatchSize ( batchSize ) ; _kafkaHost = kafkaHost ; _kafkaPort = kafkaPort ; _kafkaSoTimeout = soTimeout ; _kafkaConsumer = null ; _msgIter = null ; _dataConverter = dataConverter ; if ( _dataConverter == null ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } bytesFactory = new ThreadLocal < byte [ ] > ( ) { @ Override protected byte [ ] initialValue ( ) { return new byte [ DEFAULT_MAX_MSG_SIZE ] ; } } ; } @ Override public void setStartingOffset ( String version ) { _offset = Long . parseLong ( version ) ; } private FetchRequest buildReq ( ) { if ( _offset <= <NUM_LIT:0> ) { long time = OffsetRequest . EarliestTime ( ) ; if ( _offset == - <NUM_LIT:1> ) { time = - OffsetRequest . LatestTime ( ) ; } _offset = _kafkaConsumer . getOffsetsBefore ( _topic , <NUM_LIT:0> , time , <NUM_LIT:1> ) [ <NUM_LIT:0> ] ; } return new FetchRequest ( _topic , <NUM_LIT:0> , _offset , DEFAULT_MAX_MSG_SIZE ) ; } @ Override public DataEvent < JSONObject > next ( ) { if ( ! _started ) return null ; if ( _msgIter == null || ! _msgIter . hasNext ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "<STR_LIT>" + _offset ) ; } FetchRequest req = buildReq ( ) ; ByteBufferMessageSet msgSet = _kafkaConsumer . fetch ( req ) ; _msgIter = msgSet . iterator ( ) ; } if ( _msgIter == null || ! _msgIter . hasNext ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "<STR_LIT>" + _msgIter ) ; } return null ; } MessageAndOffset msg = _msgIter . next ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "<STR_LIT>" + msg ) ; } long version = _offset ; _offset = msg . offset ( ) ; JSONObject data ; try { int size = msg . message ( ) . payloadSize ( ) ; ByteBuffer byteBuffer = msg . message ( ) . payload ( ) ; byte [ ] bytes = bytesFactory . get ( ) ; byteBuffer . get ( bytes , <NUM_LIT:0> , size ) ; data = _dataConverter . filter ( new DataPacket ( bytes , <NUM_LIT:0> , size ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "<STR_LIT>" + data ) ; } return new DataEvent < JSONObject > ( data , String . valueOf ( version ) ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; return null ; } } @ Override public void reset ( ) { _offset = _startingOffset ; } @ Override public void start ( ) { _kafkaConsumer = new SimpleConsumer ( _kafkaHost , _kafkaPort , _kafkaSoTimeout , DEFAULT_MAX_MSG_SIZE ) ; super . start ( ) ; _started = true ; } @ Override public void stop ( ) { _started = false ; try { if ( _kafkaConsumer != null ) { _kafkaConsumer . close ( ) ; } } finally { super . stop ( ) ; } } } </s>
<s> package com . senseidb . gateway . kafka ; import java . nio . ByteBuffer ; import java . util . Comparator ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import kafka . consumer . Consumer ; import kafka . consumer . ConsumerConfig ; import kafka . consumer . ConsumerIterator ; import kafka . consumer . KafkaMessageStream ; import kafka . javaapi . consumer . ConsumerConnector ; import kafka . message . Message ; import org . apache . log4j . Logger ; import org . json . JSONObject ; import proj . zoie . api . DataConsumer . DataEvent ; import proj . zoie . impl . indexing . StreamDataProvider ; import com . senseidb . indexing . DataSourceFilter ; public class KafkaStreamDataProvider extends StreamDataProvider < JSONObject > { private final String _topic ; private final String _consumerGroupId ; private Properties _kafkaConfig ; private ConsumerConnector _consumerConnector ; private ConsumerIterator < Message > _consumerIterator ; private static Logger logger = Logger . getLogger ( KafkaStreamDataProvider . class ) ; private final String _zookeeperUrl ; private final int _kafkaSoTimeout ; private volatile boolean _started = false ; private final DataSourceFilter < DataPacket > _dataConverter ; public KafkaStreamDataProvider ( Comparator < String > versionComparator , String zookeeperUrl , int soTimeout , int batchSize , String consumerGroupId , String topic , long startingOffset , DataSourceFilter < DataPacket > dataConverter ) { this ( versionComparator , zookeeperUrl , soTimeout , batchSize , consumerGroupId , topic , startingOffset , dataConverter , null ) ; } public KafkaStreamDataProvider ( Comparator < String > versionComparator , String zookeeperUrl , int soTimeout , int batchSize , String consumerGroupId , String topic , long startingOffset , DataSourceFilter < DataPacket > dataConverter , Properties kafkaConfig ) { super ( versionComparator ) ; _consumerGroupId = consumerGroupId ; _topic = topic ; super . setBatchSize ( batchSize ) ; _zookeeperUrl = zookeeperUrl ; _kafkaSoTimeout = soTimeout ; _consumerConnector = null ; _consumerIterator = null ; _kafkaConfig = kafkaConfig ; if ( kafkaConfig == null ) { kafkaConfig = new Properties ( ) ; } _dataConverter = dataConverter ; if ( _dataConverter == null ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } } @ Override public void setStartingOffset ( String version ) { } @ Override public DataEvent < JSONObject > next ( ) { if ( ! _started ) return null ; try { if ( ! _consumerIterator . hasNext ( ) ) return null ; } catch ( Exception e ) { return null ; } Message msg = _consumerIterator . next ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "<STR_LIT>" + msg ) ; } long version = System . currentTimeMillis ( ) ; JSONObject data ; try { int size = msg . payloadSize ( ) ; ByteBuffer byteBuffer = msg . payload ( ) ; byte [ ] bytes = new byte [ size ] ; byteBuffer . get ( bytes , <NUM_LIT:0> , size ) ; data = _dataConverter . filter ( new DataPacket ( bytes , <NUM_LIT:0> , size ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "<STR_LIT>" + data ) ; } return new DataEvent < JSONObject > ( data , String . valueOf ( version ) ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; return null ; } } @ Override public void reset ( ) { } @ Override public void start ( ) { Properties props = new Properties ( ) ; props . put ( "<STR_LIT>" , _zookeeperUrl ) ; props . put ( "<STR_LIT>" , _consumerGroupId ) ; for ( String key : _kafkaConfig . stringPropertyNames ( ) ) { props . put ( key , _kafkaConfig . getProperty ( key ) ) ; } ConsumerConfig consumerConfig = new ConsumerConfig ( props ) ; _consumerConnector = Consumer . createJavaConsumerConnector ( consumerConfig ) ; Map < String , Integer > topicCountMap = new HashMap < String , Integer > ( ) ; topicCountMap . put ( _topic , <NUM_LIT:1> ) ; Map < String , List < KafkaMessageStream < Message > > > topicMessageStreams = _consumerConnector . createMessageStreams ( topicCountMap ) ; List < KafkaMessageStream < Message > > streams = topicMessageStreams . get ( _topic ) ; KafkaMessageStream < Message > kafkaMessageStream = streams . iterator ( ) . next ( ) ; _consumerIterator = kafkaMessageStream . iterator ( ) ; super . start ( ) ; _started = true ; } @ Override public void stop ( ) { _started = false ; try { if ( _consumerConnector != null ) { _consumerConnector . shutdown ( ) ; } } finally { super . stop ( ) ; } } } </s>
<s> package com . senseidb . gateway . kafka ; import java . util . Comparator ; import java . util . Set ; import org . json . JSONObject ; import proj . zoie . impl . indexing . StreamDataProvider ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . indexing . DataSourceFilter ; import com . senseidb . indexing . ShardingStrategy ; public class SimpleKafkaGateway extends SenseiGateway < DataPacket > { @ Override public StreamDataProvider < JSONObject > buildDataProvider ( DataSourceFilter < DataPacket > dataFilter , String oldSinceKey , ShardingStrategy shardingStrategy , Set < Integer > partitions ) throws Exception { String kafkaHost = config . get ( "<STR_LIT>" ) ; int kafkaPort = Integer . parseInt ( config . get ( "<STR_LIT>" ) ) ; String topic = config . get ( "<STR_LIT>" ) ; String timeoutStr = config . get ( "<STR_LIT>" ) ; int timeout = timeoutStr != null ? Integer . parseInt ( timeoutStr ) : <NUM_LIT> ; int batchsize = Integer . parseInt ( config . get ( "<STR_LIT>" ) ) ; long offset = oldSinceKey == null ? <NUM_LIT> : Long . parseLong ( oldSinceKey ) ; if ( dataFilter == null ) { String type = config . get ( "<STR_LIT>" ) ; if ( type == null ) { type = "<STR_LIT>" ; } if ( "<STR_LIT>" . equals ( type ) ) { dataFilter = new DefaultJsonDataSourceFilter ( ) ; } else if ( "<STR_LIT>" . equals ( type ) ) { try { String msgClsString = config . get ( "<STR_LIT>" ) ; String dataMapperClassString = config . get ( "<STR_LIT>" ) ; Class cls = Class . forName ( msgClsString ) ; Class dataMapperClass = Class . forName ( dataMapperClassString ) ; DataSourceFilter dataMapper = ( DataSourceFilter ) dataMapperClass . newInstance ( ) ; dataFilter = new AvroDataSourceFilter ( cls , dataMapper ) ; } catch ( Exception e ) { throw new Exception ( "<STR_LIT>" , e ) ; } } else { throw new IllegalArgumentException ( "<STR_LIT>" + type ) ; } } SimpleKafkaStreamDataProvider provider = new SimpleKafkaStreamDataProvider ( KafkaDataProviderBuilder . DEFAULT_VERSION_COMPARATOR , kafkaHost , kafkaPort , timeout , batchsize , topic , offset , dataFilter ) ; return provider ; } @ Override public Comparator < String > getVersionComparator ( ) { return KafkaDataProviderBuilder . DEFAULT_VERSION_COMPARATOR ; } } </s>
<s> package com . senseidb . gateway . kafka ; import java . util . Comparator ; import java . util . Set ; import org . json . JSONObject ; import proj . zoie . impl . indexing . StreamDataProvider ; import proj . zoie . impl . indexing . ZoieConfig ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . indexing . DataSourceFilter ; import com . senseidb . indexing . ShardingStrategy ; public class KafkaDataProviderBuilder extends SenseiGateway < DataPacket > { private final Comparator < String > _versionComparator = ZoieConfig . DEFAULT_VERSION_COMPARATOR ; @ Override public StreamDataProvider < JSONObject > buildDataProvider ( DataSourceFilter < DataPacket > dataFilter , String oldSinceKey , ShardingStrategy shardingStrategy , Set < Integer > partitions ) throws Exception { String zookeeperUrl = config . get ( "<STR_LIT>" ) ; String consumerGroupId = config . get ( "<STR_LIT>" ) ; String topic = config . get ( "<STR_LIT>" ) ; String timeoutStr = config . get ( "<STR_LIT>" ) ; int timeout = timeoutStr != null ? Integer . parseInt ( timeoutStr ) : <NUM_LIT> ; int batchsize = Integer . parseInt ( config . get ( "<STR_LIT>" ) ) ; long offset = oldSinceKey == null ? <NUM_LIT> : Long . parseLong ( oldSinceKey ) ; if ( dataFilter == null ) { String type = config . get ( "<STR_LIT>" ) ; if ( type == null ) { type = "<STR_LIT>" ; } if ( "<STR_LIT>" . equals ( type ) ) { dataFilter = new DefaultJsonDataSourceFilter ( ) ; } else if ( "<STR_LIT>" . equals ( type ) ) { String msgClsString = config . get ( "<STR_LIT>" ) ; String dataMapperClassString = config . get ( "<STR_LIT>" ) ; Class cls = Class . forName ( msgClsString ) ; Class dataMapperClass = Class . forName ( dataMapperClassString ) ; DataSourceFilter dataMapper = ( DataSourceFilter ) dataMapperClass . newInstance ( ) ; dataFilter = new AvroDataSourceFilter ( cls , dataMapper ) ; } else { throw new IllegalArgumentException ( "<STR_LIT>" + type ) ; } } KafkaStreamDataProvider provider = new KafkaStreamDataProvider ( _versionComparator , zookeeperUrl , timeout , batchsize , consumerGroupId , topic , offset , dataFilter ) ; return provider ; } @ Override public Comparator < String > getVersionComparator ( ) { return _versionComparator ; } } </s>
<s> package com . senseidb . gateway . kafka ; import org . apache . avro . io . BinaryDecoder ; import org . apache . avro . io . DecoderFactory ; import org . apache . avro . specific . SpecificDatumReader ; import org . json . JSONObject ; import com . senseidb . indexing . DataSourceFilter ; public class AvroDataSourceFilter < D > extends DataSourceFilter < DataPacket > { private final Class < D > _cls ; private BinaryDecoder binDecoder ; private final SpecificDatumReader < D > reader ; private final DataSourceFilter < D > _dataMapper ; public AvroDataSourceFilter ( Class < D > cls , DataSourceFilter < D > dataMapper ) { _cls = cls ; binDecoder = null ; reader = new SpecificDatumReader < D > ( _cls ) ; _dataMapper = dataMapper ; if ( _dataMapper == null ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } } @ Override protected JSONObject doFilter ( DataPacket packet ) throws Exception { binDecoder = DecoderFactory . defaultFactory ( ) . createBinaryDecoder ( packet . data , packet . offset , packet . size , binDecoder ) ; D avroObj = _cls . newInstance ( ) ; reader . read ( avroObj , binDecoder ) ; return _dataMapper . filter ( avroObj ) ; } } </s>
<s> package com . senseidb . gateway . jms ; import java . util . Comparator ; import java . util . Set ; import javax . jms . JMSException ; import javax . jms . Message ; import javax . jms . TopicConnectionFactory ; import org . apache . commons . configuration . ConfigurationException ; import org . json . JSONObject ; import proj . zoie . api . DataConsumer . DataEvent ; import proj . zoie . dataprovider . jms . DataEventBuilder ; import proj . zoie . dataprovider . jms . JMSStreamDataProvider ; import proj . zoie . dataprovider . jms . TopicFactory ; import proj . zoie . impl . indexing . StreamDataProvider ; import proj . zoie . impl . indexing . ZoieConfig ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . indexing . DataSourceFilter ; import com . senseidb . indexing . ShardingStrategy ; public class JmsDataProviderBuilder extends SenseiGateway < Message > { public static final String name = "<STR_LIT>" ; private final Comparator < String > _versionComparator = ZoieConfig . DEFAULT_VERSION_COMPARATOR ; @ Override public StreamDataProvider < JSONObject > buildDataProvider ( final DataSourceFilter < Message > dataFilter , String oldSinceKey , ShardingStrategy shardingStrategy , Set < Integer > partitions ) throws Exception { final String topic = config . get ( "<STR_LIT>" ) ; final String clientID = config . get ( "<STR_LIT>" ) ; final String topicFac = config . get ( "<STR_LIT>" ) ; TopicFactory topicFactory = pluginRegistry . getBeanByName ( topicFac , TopicFactory . class ) ; if ( topicFactory == null ) topicFactory = pluginRegistry . getBeanByFullPrefix ( topicFac , TopicFactory . class ) ; if ( topicFactory == null ) { throw new ConfigurationException ( "<STR_LIT>" + topicFac ) ; } TopicConnectionFactory connectionFactory = pluginRegistry . getBeanByName ( config . get ( "<STR_LIT>" ) , TopicConnectionFactory . class ) ; if ( connectionFactory == null ) connectionFactory = pluginRegistry . getBeanByFullPrefix ( config . get ( "<STR_LIT>" ) , TopicConnectionFactory . class ) ; if ( connectionFactory == null ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } DataEventBuilder < JSONObject > dataEventBuilder = new DataEventBuilder < JSONObject > ( ) { final DataSourceFilter < Message > filter = dataFilter ; @ Override public DataEvent < JSONObject > buildDataEvent ( Message message ) throws JMSException { try { return new DataEvent < JSONObject > ( filter . filter ( message ) , String . valueOf ( System . nanoTime ( ) ) ) ; } catch ( Exception e ) { throw new JMSException ( e . getMessage ( ) ) ; } } } ; JMSStreamDataProvider < JSONObject > provider = new JMSStreamDataProvider < JSONObject > ( topic , clientID , connectionFactory , topicFactory , dataEventBuilder , _versionComparator ) ; return provider ; } @ Override public Comparator < String > getVersionComparator ( ) { return _versionComparator ; } } </s>
<s> package com . senseidb . gateway . jdbc ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import java . util . Comparator ; import java . util . Set ; import javax . naming . ConfigurationException ; import org . json . JSONObject ; import proj . zoie . api . DataConsumer . DataEvent ; import proj . zoie . dataprovider . jdbc . JDBCConnectionFactory ; import proj . zoie . dataprovider . jdbc . JDBCStreamDataProvider ; import proj . zoie . dataprovider . jdbc . PreparedStatementBuilder ; import proj . zoie . impl . indexing . StreamDataProvider ; import proj . zoie . impl . indexing . ZoieConfig ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . indexing . DataSourceFilter ; import com . senseidb . indexing . ShardingStrategy ; public class JdbcDataProviderBuilder extends SenseiGateway < ResultSet > { private Comparator < String > _versionComparator ; @ Override public void start ( ) { _versionComparator = pluginRegistry . getBeanByName ( "<STR_LIT>" , Comparator . class ) ; if ( _versionComparator == null ) _versionComparator = ZoieConfig . DEFAULT_VERSION_COMPARATOR ; } @ Override public StreamDataProvider < JSONObject > buildDataProvider ( final DataSourceFilter < ResultSet > dataFilter , String oldSinceKey , ShardingStrategy shardingStrategy , Set < Integer > partitions ) throws Exception { final String url = config . get ( "<STR_LIT>" ) ; final String username = config . get ( "<STR_LIT>" ) ; final String password = config . get ( "<STR_LIT>" ) ; final String driver = config . get ( "<STR_LIT>" ) ; final String adaptor = config . get ( "<STR_LIT>" ) ; final SenseiJDBCAdaptor senseiAdaptor = pluginRegistry . getBeanByName ( adaptor , SenseiJDBCAdaptor . class ) != null ? pluginRegistry . getBeanByName ( adaptor , SenseiJDBCAdaptor . class ) : pluginRegistry . getBeanByFullPrefix ( adaptor , SenseiJDBCAdaptor . class ) ; if ( senseiAdaptor == null ) { throw new ConfigurationException ( "<STR_LIT>" + adaptor ) ; } JDBCConnectionFactory connFactory = new JDBCConnectionFactory ( ) { private Connection _conn = null ; @ Override public void showndown ( ) throws SQLException { if ( _conn != null ) { _conn . close ( ) ; } } @ Override public Connection getConnection ( ) throws SQLException { if ( _conn == null ) { try { Class . forName ( driver ) . newInstance ( ) ; } catch ( Exception e ) { throw new SQLException ( "<STR_LIT>" + e . getMessage ( ) ) ; } _conn = DriverManager . getConnection ( url , username , password ) ; } return _conn ; } } ; PreparedStatementBuilder < JSONObject > stmtBuilder = new PreparedStatementBuilder < JSONObject > ( ) { private final DataSourceFilter < ResultSet > filter = dataFilter ; @ Override public PreparedStatement buildStatment ( Connection conn , String fromVersion ) throws SQLException { return senseiAdaptor . buildStatment ( conn , fromVersion ) ; } @ Override public DataEvent < JSONObject > buildDataEvent ( ResultSet rs ) throws SQLException { try { JSONObject jsonObject = filter . filter ( rs ) ; return new DataEvent < JSONObject > ( jsonObject , senseiAdaptor . extractVersion ( rs ) ) ; } catch ( Exception e ) { throw new SQLException ( e . getMessage ( ) , e ) ; } } } ; return new JDBCStreamDataProvider < JSONObject > ( connFactory , stmtBuilder , _versionComparator ) ; } @ Override public Comparator < String > getVersionComparator ( ) { return _versionComparator ; } } </s>
<s> package com . senseidb . gateway . jdbc ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; public interface SenseiJDBCAdaptor { PreparedStatement buildStatment ( Connection conn , String fromVersion ) throws SQLException ; String extractVersion ( ResultSet resultSet ) throws SQLException ; } </s>
<s> package com . senseidb . gateway . test . jdbc ; import java . sql . ResultSet ; import org . json . JSONObject ; import com . senseidb . indexing . DataSourceFilter ; public class ResultSetJsonFilter extends DataSourceFilter < ResultSet > { @ Override protected JSONObject doFilter ( ResultSet rs ) throws Exception { String json = rs . getString ( <NUM_LIT:1> ) ; return new JSONObject ( json ) ; } } </s>
<s> package com . senseidb . gateway . test . jdbc ; import java . sql . Connection ; import java . sql . PreparedStatement ; import java . sql . ResultSet ; import java . sql . SQLException ; import com . senseidb . gateway . jdbc . SenseiJDBCAdaptor ; public class SimpleJDBCAdaptor implements SenseiJDBCAdaptor { private static String sql = "<STR_LIT>" ; @ Override public PreparedStatement buildStatment ( Connection conn , String fromVersion ) throws SQLException { PreparedStatement stmt = conn . prepareStatement ( sql ) ; int version = fromVersion == null ? <NUM_LIT:0> : Integer . parseInt ( fromVersion ) ; stmt . setInt ( <NUM_LIT:1> , version ) ; return stmt ; } @ Override public String extractVersion ( ResultSet resultSet ) throws SQLException { int version = resultSet . getInt ( <NUM_LIT:2> ) ; return String . valueOf ( version ) ; } } </s>
<s> package com . senseidb . gateway . test ; import java . io . File ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . PreparedStatement ; import org . apache . commons . configuration . Configuration ; import org . apache . commons . configuration . PropertiesConfiguration ; import org . json . JSONObject ; import org . junit . AfterClass ; import org . junit . BeforeClass ; import org . junit . Test ; import proj . zoie . impl . indexing . StreamDataProvider ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . gateway . test . jdbc . ResultSetJsonFilter ; import com . senseidb . plugin . SenseiPluginRegistry ; public class TestJDBCGateway { static File confFile = new File ( "<STR_LIT>" ) ; static SenseiGateway gateway ; static SenseiPluginRegistry pluginRegistry ; static Configuration config = null ; static Connection conn = null ; static String insertSql = "<STR_LIT>" ; static String createTableSql = "<STR_LIT>" ; static String dropTableSql = "<STR_LIT>" ; @ BeforeClass public static void init ( ) throws Exception { config = new PropertiesConfiguration ( confFile ) ; String userName = config . getString ( "<STR_LIT>" ) ; String password = config . getString ( "<STR_LIT>" , null ) ; String url = config . getString ( "<STR_LIT>" ) ; Class . forName ( config . getString ( "<STR_LIT>" ) ) ; conn = DriverManager . getConnection ( url , userName , password ) ; conn . setAutoCommit ( false ) ; System . out . println ( "<STR_LIT>" ) ; try { PreparedStatement createDBStmt = conn . prepareStatement ( createTableSql ) ; createDBStmt . execute ( ) ; conn . commit ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } for ( JSONObject obj : BaseGatewayTestUtil . dataList ) { try { PreparedStatement stmt = conn . prepareStatement ( insertSql ) ; stmt . setString ( <NUM_LIT:1> , obj . toString ( ) ) ; stmt . setInt ( <NUM_LIT:2> , obj . getInt ( "<STR_LIT:id>" ) + <NUM_LIT:1> ) ; stmt . executeUpdate ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } conn . commit ( ) ; pluginRegistry = SenseiPluginRegistry . build ( config ) ; pluginRegistry . start ( ) ; gateway = pluginRegistry . getBeanByFullPrefix ( "<STR_LIT>" , SenseiGateway . class ) ; } @ AfterClass public static void shutdown ( ) { gateway . stop ( ) ; pluginRegistry . stop ( ) ; if ( conn != null ) { try { try { PreparedStatement createDBStmt = conn . prepareStatement ( dropTableSql ) ; createDBStmt . execute ( ) ; conn . commit ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } conn . close ( ) ; System . out . println ( "<STR_LIT>" ) ; } catch ( Exception e ) { } } } @ Test public void testHappyPath ( ) throws Exception { final StreamDataProvider < JSONObject > dataProvider = gateway . buildDataProvider ( new ResultSetJsonFilter ( ) , String . valueOf ( "<STR_LIT:0>" ) , null , null ) ; BaseGatewayTestUtil . doTest ( dataProvider ) ; } } </s>
<s> package com . senseidb . gateway . test ; import java . io . File ; import java . io . FileReader ; import java . io . IOException ; import java . util . ArrayList ; import java . util . List ; import java . util . Properties ; import kafka . javaapi . producer . Producer ; import kafka . javaapi . producer . ProducerData ; import kafka . message . Message ; import kafka . producer . ProducerConfig ; import kafka . server . KafkaConfig ; import kafka . server . KafkaServer ; import org . apache . commons . configuration . Configuration ; import org . apache . commons . configuration . PropertiesConfiguration ; import org . apache . commons . io . FileUtils ; import org . json . JSONObject ; import org . junit . AfterClass ; import org . junit . BeforeClass ; import org . junit . Test ; import proj . zoie . impl . indexing . StreamDataProvider ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . gateway . kafka . DefaultJsonDataSourceFilter ; import com . senseidb . plugin . SenseiPluginRegistry ; public class TestKafkaGateway { static File confFile = new File ( "<STR_LIT>" ) ; static File confFile2 = new File ( "<STR_LIT>" ) ; static File kafkaServerFile = new File ( "<STR_LIT>" ) ; static SenseiGateway kafkaGateway ; static SenseiGateway simpleKafkaGateway ; static SenseiPluginRegistry pluginRegistry ; static Configuration config = null ; static SenseiPluginRegistry pluginRegistry2 ; static Configuration config2 = null ; static KafkaServer kafkaServer = null ; static File kafkaLogFile = null ; @ BeforeClass public static void init ( ) throws Exception { config = new PropertiesConfiguration ( confFile ) ; pluginRegistry = SenseiPluginRegistry . build ( config ) ; pluginRegistry . start ( ) ; Properties kafkaProps = new Properties ( ) ; kafkaProps . load ( new FileReader ( kafkaServerFile ) ) ; kafkaLogFile = new File ( kafkaProps . getProperty ( "<STR_LIT>" ) ) ; FileUtils . deleteDirectory ( kafkaLogFile ) ; KafkaConfig kafkaConfig = new KafkaConfig ( kafkaProps ) ; kafkaServer = new KafkaServer ( kafkaConfig ) ; kafkaServer . startup ( ) ; kafkaGateway = pluginRegistry . getBeanByFullPrefix ( "<STR_LIT>" , SenseiGateway . class ) ; kafkaGateway . start ( ) ; config2 = new PropertiesConfiguration ( confFile2 ) ; pluginRegistry2 = SenseiPluginRegistry . build ( config2 ) ; pluginRegistry2 . start ( ) ; simpleKafkaGateway = pluginRegistry2 . getBeanByFullPrefix ( "<STR_LIT>" , SenseiGateway . class ) ; simpleKafkaGateway . start ( ) ; Properties props = new Properties ( ) ; props . put ( "<STR_LIT>" , "<STR_LIT>" ) ; props . put ( "<STR_LIT>" , "<STR_LIT>" ) ; ProducerConfig producerConfig = new ProducerConfig ( props ) ; Producer < String , Message > kafkaProducer = new Producer < String , Message > ( producerConfig ) ; String topic = config2 . getString ( "<STR_LIT>" ) ; List < ProducerData < String , Message > > msgList = new ArrayList < ProducerData < String , Message > > ( ) ; for ( JSONObject jsonObj : BaseGatewayTestUtil . dataList ) { Message m = new Message ( jsonObj . toString ( ) . getBytes ( DefaultJsonDataSourceFilter . UTF8 ) ) ; ProducerData < String , Message > msg = new ProducerData < String , Message > ( topic , m ) ; msgList . add ( msg ) ; } kafkaProducer . send ( msgList ) ; } @ AfterClass public static void shutdown ( ) { kafkaGateway . stop ( ) ; pluginRegistry . stop ( ) ; simpleKafkaGateway . stop ( ) ; pluginRegistry2 . stop ( ) ; try { if ( kafkaServer != null ) { kafkaServer . shutdown ( ) ; kafkaServer . awaitShutdown ( ) ; } } finally { try { FileUtils . deleteDirectory ( kafkaLogFile ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } @ Test public void testSimpleKafka ( ) throws Exception { final StreamDataProvider < JSONObject > dataProvider = simpleKafkaGateway . buildDataProvider ( null , String . valueOf ( "<STR_LIT:0>" ) , null , null ) ; BaseGatewayTestUtil . doTest ( dataProvider ) ; } @ Test public void testKafka ( ) throws Exception { } } </s>
<s> package com . senseidb . gateway . test ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileReader ; import java . util . Collection ; import java . util . Comparator ; import java . util . LinkedList ; import java . util . List ; import junit . framework . TestCase ; import org . apache . commons . configuration . Configuration ; import org . apache . commons . configuration . PropertiesConfiguration ; import org . json . JSONObject ; import org . junit . BeforeClass ; import proj . zoie . api . DataConsumer ; import proj . zoie . api . ZoieException ; import proj . zoie . api . DataConsumer . DataEvent ; import proj . zoie . impl . indexing . StreamDataProvider ; import proj . zoie . impl . indexing . ZoieConfig ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . plugin . SenseiPluginRegistry ; public class BaseGatewayTestUtil { static File dataFile = new File ( "<STR_LIT>" ) ; static List < JSONObject > dataList ; static { try { dataList = readData ( dataFile ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } static List < JSONObject > readData ( File file ) throws Exception { LinkedList < JSONObject > dataList = new LinkedList < JSONObject > ( ) ; BufferedReader reader = new BufferedReader ( new FileReader ( file ) ) ; while ( true ) { String line = reader . readLine ( ) ; if ( line == null ) break ; dataList . add ( new JSONObject ( line ) ) ; } return dataList ; } public static void compareResultList ( List < JSONObject > jsonList ) throws Exception { for ( int i = <NUM_LIT:0> ; i < jsonList . size ( ) ; ++ i ) { String s1 = jsonList . get ( i ) . getString ( "<STR_LIT:id>" ) ; String s2 = BaseGatewayTestUtil . dataList . get ( i ) . getString ( "<STR_LIT:id>" ) ; TestCase . assertEquals ( s1 , s2 ) ; } } public static void doTest ( StreamDataProvider < JSONObject > dataProvider ) throws Exception { final LinkedList < JSONObject > jsonList = new LinkedList < JSONObject > ( ) ; dataProvider . setDataConsumer ( new DataConsumer < JSONObject > ( ) { private volatile String version ; @ Override public void consume ( Collection < DataEvent < JSONObject > > events ) throws ZoieException { for ( DataEvent < JSONObject > event : events ) { JSONObject jsonObj = event . getData ( ) ; System . out . println ( jsonObj + "<STR_LIT>" + event . getVersion ( ) ) ; jsonList . add ( jsonObj ) ; version = event . getVersion ( ) ; } } @ Override public String getVersion ( ) { return version ; } @ Override public Comparator < String > getVersionComparator ( ) { return ZoieConfig . DEFAULT_VERSION_COMPARATOR ; } } ) ; dataProvider . start ( ) ; while ( true ) { Thread . sleep ( <NUM_LIT> ) ; if ( jsonList . size ( ) == BaseGatewayTestUtil . dataList . size ( ) ) { dataProvider . stop ( ) ; BaseGatewayTestUtil . compareResultList ( jsonList ) ; break ; } } } } </s>
<s> package com . senseidb . gateway . perf ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . InputStreamReader ; import java . nio . charset . Charset ; import java . util . ArrayList ; import java . util . List ; import java . util . Properties ; import kafka . javaapi . producer . Producer ; import kafka . javaapi . producer . ProducerData ; import kafka . message . Message ; import kafka . producer . ProducerConfig ; import com . senseidb . gateway . kafka . DefaultJsonDataSourceFilter ; public class PrimeKafkaUtil { static Charset UTF8 = Charset . forName ( "<STR_LIT:UTF-8>" ) ; public static void main ( String [ ] args ) throws Exception { File f = new File ( "<STR_LIT>" ) ; Properties props = new Properties ( ) ; props . put ( "<STR_LIT>" , "<STR_LIT>" ) ; props . put ( "<STR_LIT>" , "<STR_LIT>" ) ; ProducerConfig producerConfig = new ProducerConfig ( props ) ; Producer < String , Message > kafkaProducer = new Producer < String , Message > ( producerConfig ) ; String topic = "<STR_LIT>" ; List < ProducerData < String , Message > > msgList = new ArrayList < ProducerData < String , Message > > ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( f ) , UTF8 ) ) ; int batchSize = <NUM_LIT> ; int count = <NUM_LIT:0> ; while ( true ) { String line = reader . readLine ( ) ; if ( line == null ) break ; count ++ ; System . out . println ( count + "<STR_LIT>" ) ; Message m = new Message ( line . getBytes ( DefaultJsonDataSourceFilter . UTF8 ) ) ; ProducerData < String , Message > msg = new ProducerData < String , Message > ( topic , m ) ; msgList . add ( msg ) ; if ( msgList . size ( ) > batchSize ) { kafkaProducer . send ( msgList ) ; msgList . clear ( ) ; } } if ( msgList . size ( ) > <NUM_LIT:0> ) { kafkaProducer . send ( msgList ) ; } } } </s>
<s> package com . senseidb . gateway . perf ; import java . util . Collection ; import java . util . Comparator ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import proj . zoie . api . DataConsumer ; import proj . zoie . api . ZoieException ; import proj . zoie . impl . indexing . StreamDataProvider ; import proj . zoie . impl . indexing . ZoieConfig ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . gateway . file . LinedFileDataProviderBuilder ; import com . senseidb . gateway . kafka . KafkaDataProviderBuilder ; public class PerfDriver { public static final int MAX_EVENTS_PER_MIN = Integer . MAX_VALUE ; public static class PerfStats { long runTime ; int qps ; volatile int numConsumed ; @ Override public String toString ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "<STR_LIT>" ) . append ( runTime ) . append ( "<STR_LIT>" ) . append ( qps ) . append ( "<STR_LIT>" ) . append ( numConsumed ) ; return buf . toString ( ) ; } } private final SenseiGateway < ? > _gateway ; private final int _max ; private PerfDriver ( SenseiGateway < ? > gateway , int max ) { _gateway = gateway ; _max = max ; } public PerfStats runPerf ( ) throws Exception { StreamDataProvider < ? > dataProvider = _gateway . buildDataProvider ( null , "<STR_LIT:0>" , null , null ) ; dataProvider . setMaxEventsPerMinute ( MAX_EVENTS_PER_MIN ) ; final PerfStats stats = new PerfStats ( ) ; dataProvider . setDataConsumer ( new DataConsumer ( ) { private String _version = "<STR_LIT:0>" ; @ Override public void consume ( Collection data ) throws ZoieException { Iterator < DataEvent < ? > > iter = ( Iterator < DataEvent < ? > > ) data . iterator ( ) ; while ( iter . hasNext ( ) ) { DataEvent < ? > evt = iter . next ( ) ; _version = evt . getVersion ( ) ; } stats . numConsumed += data . size ( ) ; System . out . println ( stats . numConsumed ) ; } @ Override public String getVersion ( ) { return _version ; } @ Override public Comparator getVersionComparator ( ) { return ZoieConfig . DEFAULT_VERSION_COMPARATOR ; } } ) ; dataProvider . start ( ) ; long start = System . currentTimeMillis ( ) ; stats . numConsumed = <NUM_LIT:0> ; while ( stats . numConsumed < _max ) { Thread . sleep ( <NUM_LIT> ) ; } long end = System . currentTimeMillis ( ) ; dataProvider . stop ( ) ; stats . runTime = ( end - start ) ; if ( stats . numConsumed > <NUM_LIT:0> ) { stats . qps = ( int ) ( stats . numConsumed * <NUM_LIT:1000> / ( stats . runTime ) ) ; } return stats ; } private static SenseiGateway < ? > buildFileGateway ( String file ) { LinedFileDataProviderBuilder fileGateway = new LinedFileDataProviderBuilder ( ) ; Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( "<STR_LIT>" , file ) ; fileGateway . init ( config , null ) ; return fileGateway ; } private static SenseiGateway < ? > buildKafkaGateway ( String topic ) { KafkaDataProviderBuilder kafkaGateway = new KafkaDataProviderBuilder ( ) ; Map < String , String > config = new HashMap < String , String > ( ) ; config . put ( "<STR_LIT>" , "<STR_LIT>" ) ; config . put ( "<STR_LIT>" , "<STR_LIT:1>" ) ; config . put ( "<STR_LIT>" , topic ) ; config . put ( "<STR_LIT>" , "<STR_LIT>" ) ; config . put ( "<STR_LIT>" , "<STR_LIT>" ) ; kafkaGateway . init ( config , null ) ; return kafkaGateway ; } public static void main ( String [ ] args ) throws Exception { String file = "<STR_LIT>" ; SenseiGateway < ? > gateway = buildKafkaGateway ( "<STR_LIT>" ) ; PerfDriver driver = new PerfDriver ( gateway , <NUM_LIT> ) ; PerfStats stats = driver . runPerf ( ) ; System . out . println ( stats ) ; } } </s>
<s> package com . senseidb . example . tweets . gateway ; import java . util . Comparator ; import java . util . Set ; import org . json . JSONObject ; import proj . zoie . impl . indexing . StreamDataProvider ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . indexing . DataSourceFilter ; import com . senseidb . indexing . ShardingStrategy ; public class TwitterSampleGateway extends SenseiGateway < JSONObject > { @ Override public StreamDataProvider < JSONObject > buildDataProvider ( DataSourceFilter < JSONObject > dataFilter , String oldSinceKey , ShardingStrategy shardingStrategy , Set < Integer > partitions ) throws Exception { return new TwitterSampleStreamer ( config , SenseiGateway . DEFAULT_VERSION_COMPARATOR ) ; } @ Override public Comparator < String > getVersionComparator ( ) { return SenseiGateway . DEFAULT_VERSION_COMPARATOR ; } } </s>
<s> package com . senseidb . example . tweets . gateway ; import java . io . BufferedReader ; import java . io . InputStream ; import java . io . InputStreamReader ; import java . net . URL ; import java . net . URLConnection ; import java . text . SimpleDateFormat ; import java . util . ArrayList ; import java . util . Comparator ; import java . util . List ; import java . util . Map ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import org . apache . log4j . Logger ; import org . json . JSONObject ; import proj . zoie . api . DataConsumer . DataEvent ; import proj . zoie . impl . indexing . StreamDataProvider ; public class TwitterSampleStreamer extends StreamDataProvider < JSONObject > { private static Logger logger = Logger . getLogger ( TwitterSampleStreamer . class ) ; private static String LATIN_ACCENTS_CHARS = "<STR_LIT>" ; private static final String HASHTAG_ALPHA_CHARS = "<STR_LIT>" + LATIN_ACCENTS_CHARS + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; private static final String HASHTAG_ALPHA_NUMERIC_CHARS = "<STR_LIT>" + HASHTAG_ALPHA_CHARS ; private static final String HASHTAG_ALPHA = "<STR_LIT:[>" + HASHTAG_ALPHA_CHARS + "<STR_LIT:]>" ; private static final String HASHTAG_ALPHA_NUMERIC = "<STR_LIT:[>" + HASHTAG_ALPHA_NUMERIC_CHARS + "<STR_LIT:]>" ; public static final Pattern AUTO_LINK_HASHTAGS = Pattern . compile ( "<STR_LIT>" + HASHTAG_ALPHA_NUMERIC_CHARS + "<STR_LIT>" + HASHTAG_ALPHA_NUMERIC + "<STR_LIT:*>" + HASHTAG_ALPHA + HASHTAG_ALPHA_NUMERIC + "<STR_LIT>" , Pattern . CASE_INSENSITIVE ) ; public static final Pattern HASHTAG_MATCH_END = Pattern . compile ( "<STR_LIT>" ) ; private static List < String > extractHashtags ( String text ) { List < String > extracted = new ArrayList < String > ( ) ; Matcher matcher = AUTO_LINK_HASHTAGS . matcher ( text ) ; while ( matcher . find ( ) ) { String after = text . substring ( matcher . end ( ) ) ; if ( ! HASHTAG_MATCH_END . matcher ( after ) . find ( ) ) { extracted . add ( matcher . group ( <NUM_LIT:3> ) ) ; } } return extracted ; } private final BufferedReader _tweetReader ; public TwitterSampleStreamer ( Map < String , String > config , Comparator < String > versionComparator ) throws Exception { super ( versionComparator ) ; String username = config . get ( "<STR_LIT:username>" ) ; String password = config . get ( "<STR_LIT:password>" ) ; URL url = new URL ( "<STR_LIT>" ) ; URLConnection uc = url . openConnection ( ) ; String userPassword = username + "<STR_LIT::>" + password ; String encoding = new sun . misc . BASE64Encoder ( ) . encode ( userPassword . getBytes ( ) ) ; uc . setRequestProperty ( "<STR_LIT>" , "<STR_LIT>" + encoding ) ; InputStream in = uc . getInputStream ( ) ; _tweetReader = new BufferedReader ( new InputStreamReader ( in , "<STR_LIT:UTF-8>" ) ) ; } @ Override public DataEvent < JSONObject > next ( ) { DataEvent < JSONObject > tweetEvent = null ; try { String tweet = _tweetReader . readLine ( ) ; logger . info ( "<STR_LIT>" + tweet ) ; JSONObject jsonObj = new JSONObject ( tweet ) ; String id = jsonObj . optString ( "<STR_LIT>" , null ) ; if ( id != null ) { JSONObject tweetJSON = new JSONObject ( ) ; tweetJSON . put ( "<STR_LIT:id>" , Long . parseLong ( id ) ) ; String textString = jsonObj . optString ( "<STR_LIT:text>" , "<STR_LIT>" ) ; long time = new SimpleDateFormat ( "<STR_LIT>" ) . parse ( jsonObj . getString ( "<STR_LIT>" ) ) . getTime ( ) ; tweetJSON . put ( "<STR_LIT>" , time ) ; JSONObject user = jsonObj . optJSONObject ( "<STR_LIT:user>" ) ; String screenName = user . optString ( "<STR_LIT>" , "<STR_LIT>" ) ; tweetJSON . put ( "<STR_LIT>" , screenName ) ; List < String > hashtags = extractHashtags ( textString ) ; StringBuilder contentBuilder = new StringBuilder ( ) ; contentBuilder . append ( textString ) . append ( "<STR_LIT:n>" ) ; contentBuilder . append ( screenName ) . append ( "<STR_LIT:n>" ) ; if ( hashtags != null && hashtags . size ( ) > <NUM_LIT:0> ) { StringBuilder buf = new StringBuilder ( ) ; boolean first = true ; for ( String tag : hashtags ) { if ( ! first ) { buf . append ( "<STR_LIT:U+002C>" ) ; } else { first = false ; } buf . append ( tag ) ; contentBuilder . append ( tag ) . append ( "<STR_LIT:n>" ) ; } tweetJSON . put ( "<STR_LIT>" , buf . toString ( ) ) ; } tweetJSON . put ( "<STR_LIT>" , contentBuilder . toString ( ) ) ; tweetJSON . put ( "<STR_LIT>" , jsonObj ) ; tweetEvent = new DataEvent < JSONObject > ( tweetJSON , String . valueOf ( System . currentTimeMillis ( ) ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "<STR_LIT>" + tweetJSON . toString ( ) ) ; } } } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; return null ; } return tweetEvent ; } @ Override public void setStartingOffset ( String version ) { } @ Override public void reset ( ) { } @ Override public void stop ( ) { try { _tweetReader . close ( ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } finally { super . stop ( ) ; } } } </s>
<s> package com . senseidb . indexing . hadoop . demo ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . mapred . JobClient ; import org . apache . hadoop . mapred . JobConf ; import org . apache . hadoop . util . Tool ; import org . apache . hadoop . util . ToolRunner ; import com . senseidb . indexing . hadoop . job . MapReduceJob ; import com . senseidb . indexing . hadoop . util . PropertiesLoader ; public class CarDemo extends MapReduceJob implements Tool { public int run ( String [ ] args ) throws Exception { JobConf conf = createJob ( CarDemo . class ) ; conf . setJobName ( "<STR_LIT>" ) ; JobClient . runJob ( conf ) ; return <NUM_LIT:0> ; } public static void main ( String [ ] args ) throws Exception { long start = System . currentTimeMillis ( ) ; Configuration conf = PropertiesLoader . loadProperties ( "<STR_LIT>" ) ; int res = ToolRunner . run ( conf , new CarDemo ( ) , args ) ; long end = System . currentTimeMillis ( ) ; System . out . println ( "<STR_LIT>" + ( end - start ) ) ; System . exit ( res ) ; } } </s>
<s> package com . senseidb . indexing . hadoop . demo ; import org . json . JSONException ; import org . json . JSONObject ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . Text ; import com . senseidb . indexing . hadoop . map . MapInputConverter ; public class CarMapInputConverter extends MapInputConverter { @ Override public JSONObject getJsonInput ( Object key , Object value , Configuration conf ) throws JSONException { String line = ( ( Text ) value ) . toString ( ) ; return new JSONObject ( line ) ; } @ Override protected JSONObject doFilter ( JSONObject data ) throws Exception { return data ; } } </s>
<s> package com . senseidb . indexing . hadoop . demo ; import org . json . JSONException ; import org . json . JSONObject ; import com . senseidb . indexing . ShardingStrategy ; public class CarShardingStrategy implements ShardingStrategy { @ Override public int caculateShard ( int maxShardId , JSONObject json ) throws JSONException { return ( json . getInt ( "<STR_LIT:id>" ) ) % maxShardId ; } } </s>
<s> package com . senseidb . federated . broker ; import java . io . File ; import java . io . IOException ; import java . net . URISyntaxException ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . apache . commons . io . FileUtils ; import org . apache . commons . io . LineIterator ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import org . springframework . context . support . ClassPathXmlApplicationContext ; import com . browseengine . bobo . api . BrowseSelection ; import com . senseidb . federated . broker . proxy . BrokerProxy ; import com . senseidb . search . req . SenseiRequest ; import com . senseidb . search . req . SenseiResult ; import voldemort . client . StoreClient ; public class FederatedBrokerIntegrationTest extends TestCase { private ClassPathXmlApplicationContext brokerContext ; private FederatedBroker federatedBroker ; private StoreClient < String , String > storeClient ; private BrokerProxy senseiProxy ; @ Override protected void setUp ( ) throws Exception { SingleNodeStarter . start ( "<STR_LIT>" , <NUM_LIT> ) ; brokerContext = new ClassPathXmlApplicationContext ( "<STR_LIT>" ) ; federatedBroker = ( FederatedBroker ) brokerContext . getBean ( "<STR_LIT>" , FederatedBroker . class ) ; storeClient = ( StoreClient < String , String > ) brokerContext . getBean ( "<STR_LIT>" ) ; senseiProxy = ( BrokerProxy ) brokerContext . getBean ( "<STR_LIT>" ) ; JSONArray arr = readCarDocs ( ) ; storeClient . put ( "<STR_LIT:test>" , arr . toString ( ) ) ; } private JSONArray readCarDocs ( ) throws IOException , URISyntaxException , JSONException { JSONArray arr = new JSONArray ( ) ; LineIterator lineIterator = FileUtils . lineIterator ( new File ( FederatedBrokerIntegrationTest . class . getClassLoader ( ) . getResource ( "<STR_LIT>" ) . toURI ( ) ) ) ; while ( lineIterator . hasNext ( ) ) { String car = lineIterator . next ( ) ; if ( car != null && car . contains ( "<STR_LIT:{>" ) ) { JSONObject carDoc = new JSONObject ( car ) ; carDoc . put ( "<STR_LIT:id>" , carDoc . getLong ( "<STR_LIT:id>" ) + <NUM_LIT> ) ; arr . put ( carDoc ) ; } } return arr ; } public void test1SearchOnTwoClusters ( ) throws Exception { SenseiRequest req = new SenseiRequest ( ) ; BrowseSelection sel = new BrowseSelection ( "<STR_LIT>" ) ; String selVal = "<STR_LIT>" ; sel . addValue ( selVal ) ; req . addSelection ( sel ) ; SenseiResult result = federatedBroker . browse ( req ) ; assertEquals ( <NUM_LIT> , result . getTotalDocs ( ) ) ; assertEquals ( <NUM_LIT> , result . getNumHits ( ) ) ; SenseiResult oneProxyResult = senseiProxy . doQuery ( req ) . get ( <NUM_LIT:0> ) ; assertEquals ( <NUM_LIT> , oneProxyResult . getTotalDocs ( ) ) ; assertEquals ( <NUM_LIT> , oneProxyResult . getNumHits ( ) ) ; } @ Override protected void tearDown ( ) throws Exception { brokerContext . close ( ) ; } } </s>
<s> package com . senseidb . federated . broker ; import java . io . File ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . HashMap ; import org . apache . commons . configuration . PropertiesConfiguration ; import org . mortbay . jetty . Server ; import com . senseidb . conf . SenseiConfParams ; import com . senseidb . conf . SenseiServerBuilder ; import com . senseidb . federated . broker . proxy . SenseiBrokerProxy ; import com . senseidb . search . node . SenseiServer ; import com . senseidb . search . req . SenseiRequest ; import com . senseidb . search . req . SenseiResult ; public class SingleNodeStarter { private static boolean serverStarted = false ; private static Server jettyServer ; private static SenseiServer server ; public static void start ( String localPath , int expectedDocs ) { start ( new File ( getUri ( localPath ) ) , expectedDocs ) ; } public static void start ( File confDir , int expectedDocs ) { if ( ! serverStarted ) { try { PropertiesConfiguration senseiConfiguration = new PropertiesConfiguration ( new File ( confDir , "<STR_LIT>" ) ) ; final String indexDir = senseiConfiguration . getString ( SenseiConfParams . SENSEI_INDEX_DIR ) ; rmrf ( new File ( indexDir ) ) ; SenseiServerBuilder senseiServerBuilder = new SenseiServerBuilder ( confDir , null ) ; server = senseiServerBuilder . buildServer ( ) ; jettyServer = senseiServerBuilder . buildHttpRestServer ( ) ; server . start ( true ) ; jettyServer . start ( ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { try { jettyServer . stop ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { server . shutdown ( ) ; rmrf ( new File ( indexDir ) ) ; } } } ) ; SenseiBrokerProxy brokerProxy = SenseiBrokerProxy . valueOf ( senseiConfiguration , new HashMap < String , String > ( ) ) ; while ( true ) { SenseiResult senseiResult = brokerProxy . doQuery ( new SenseiRequest ( ) ) . get ( <NUM_LIT:0> ) ; int totalDocs = senseiResult . getTotalDocs ( ) ; System . out . println ( "<STR_LIT>" + totalDocs ) ; if ( totalDocs >= expectedDocs ) { break ; } Thread . sleep ( <NUM_LIT:100> ) ; } } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } } public static boolean rmrf ( File f ) { if ( f == null || ! f . exists ( ) ) { return true ; } if ( f . isDirectory ( ) ) { for ( File sub : f . listFiles ( ) ) { if ( ! rmrf ( sub ) ) return false ; } } return f . delete ( ) ; } private static URI getUri ( String localPath ) { try { return FederatedBrokerIntegrationTest . class . getClassLoader ( ) . getResource ( localPath ) . toURI ( ) ; } catch ( URISyntaxException ex ) { throw new RuntimeException ( ex ) ; } } } </s>
<s> package com . senseidb . federated . broker ; import java . util . ArrayList ; import java . util . List ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import voldemort . client . StoreClient ; import com . senseidb . federated . broker . proxy . ProxyDataSource ; import com . senseidb . search . req . SenseiRequest ; public class DefaultVoldermortDataSource implements ProxyDataSource { private StoreClient < String , String > storeClient ; private String key ; @ Override public List < JSONObject > getData ( SenseiRequest senseiRequest ) { String raw = storeClient . get ( key ) . getValue ( ) ; try { JSONArray jsonArray = new JSONArray ( raw ) ; List < JSONObject > ret = new ArrayList < JSONObject > ( jsonArray . length ( ) ) ; for ( int i = <NUM_LIT:0> ; i < jsonArray . length ( ) ; i ++ ) { ret . add ( jsonArray . getJSONObject ( i ) ) ; } return ret ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; } } public StoreClient < String , String > getStoreClient ( ) { return storeClient ; } public void setStoreClient ( StoreClient < String , String > storeClient ) { this . storeClient = storeClient ; } public String getKey ( ) { return key ; } public void setKey ( String key ) { this . key = key ; } } </s>
<s> package com . senseidb . federated . broker ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . concurrent . CountDownLatch ; import java . util . concurrent . ExecutorService ; import java . util . concurrent . Executors ; import java . util . concurrent . TimeUnit ; import org . apache . log4j . Logger ; import org . json . JSONObject ; import com . senseidb . federated . broker . proxy . BrokerProxy ; import com . senseidb . federated . broker . proxy . SenseiBrokerProxy ; import com . senseidb . search . node . Broker ; import com . senseidb . search . node . ResultMerger ; import com . senseidb . search . node . SenseiBroker ; import com . senseidb . search . node . inmemory . InMemorySenseiService ; import com . senseidb . search . req . SenseiRequest ; import com . senseidb . search . req . SenseiResult ; import com . senseidb . search . req . SenseiSystemInfo ; import com . senseidb . servlet . AbstractSenseiClientServlet ; import com . senseidb . servlet . DefaultSenseiJSONServlet ; import com . senseidb . svc . api . SenseiException ; import com . senseidb . util . RequestConverter2 ; public class FederatedBroker implements Broker < SenseiRequest , SenseiResult > { private final static Logger logger = Logger . getLogger ( SenseiBrokerProxy . class ) ; private List < BrokerProxy > proxies ; private int numThreads = <NUM_LIT:10> ; private ExecutorService executor ; private long timeout = <NUM_LIT> ; private Map < String , String [ ] > facetInfo = new HashMap < String , String [ ] > ( ) ; public FederatedBroker ( ) { } public FederatedBroker ( List < BrokerProxy > proxies ) { this . proxies = proxies ; } public void start ( ) { executor = Executors . newFixedThreadPool ( numThreads ) ; } public List < BrokerProxy > getProxies ( ) { return proxies ; } public void setProxies ( List < BrokerProxy > proxies ) { this . proxies = proxies ; } public int getNumThreads ( ) { return numThreads ; } public void setNumThreads ( int numThreads ) { this . numThreads = numThreads ; } public long getTimeout ( ) { return timeout ; } public void setTimeout ( long timeout ) { this . timeout = timeout ; } @ Override public SenseiResult browse ( final SenseiRequest request ) throws SenseiException { final List < SenseiResult > resultList = Collections . synchronizedList ( new ArrayList < SenseiResult > ( ) ) ; final CountDownLatch countDownLatch = new CountDownLatch ( proxies . size ( ) ) ; for ( final BrokerProxy proxy : proxies ) { executor . submit ( new Runnable ( ) { public void run ( ) { try { resultList . addAll ( proxy . doQuery ( request ) ) ; countDownLatch . countDown ( ) ; } catch ( Exception ex ) { logger . error ( "<STR_LIT>" , ex ) ; } } } ) ; } try { boolean allTheResults = countDownLatch . await ( timeout , TimeUnit . MILLISECONDS ) ; if ( ! allTheResults ) { logger . warn ( "<STR_LIT>" ) ; } SenseiResult res = ResultMerger . merge ( request , resultList , false ) ; if ( request . isFetchStoredFields ( ) || request . isFetchStoredValue ( ) ) SenseiBroker . recoverSrcData ( res , res . getSenseiHits ( ) , request . isFetchStoredFields ( ) ) ; return res ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } public void setInMemorySenseiService ( InMemorySenseiService inMemorySenseiService ) { if ( inMemorySenseiService != null && inMemorySenseiService . getSenseiSystemInfo ( ) != null ) { facetInfo = AbstractSenseiClientServlet . extractFacetInfo ( inMemorySenseiService . getSenseiSystemInfo ( ) ) ; } } public JSONObject query ( JSONObject request ) { try { SenseiRequest senseiRequest = RequestConverter2 . fromJSON ( request , facetInfo ) ; SenseiResult senseiResult = browse ( senseiRequest ) ; JSONObject jsonResult = DefaultSenseiJSONServlet . buildJSONResult ( senseiRequest , senseiResult ) ; return jsonResult ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } public void stop ( ) { executor . shutdown ( ) ; } } </s>
<s> package com . senseidb . federated . broker . proxy ; import java . util . List ; import org . json . JSONObject ; import com . senseidb . search . req . SenseiRequest ; public interface ProxyDataSource { public List < JSONObject > getData ( SenseiRequest senseiRequest ) ; } </s>
<s> package com . senseidb . federated . broker . proxy ; import java . util . Arrays ; import java . util . List ; import org . json . JSONObject ; import org . springframework . util . Assert ; import com . senseidb . search . node . inmemory . InMemorySenseiService ; import com . senseidb . search . req . SenseiRequest ; import com . senseidb . search . req . SenseiResult ; public class GenericBrokerProxy implements BrokerProxy { private InMemorySenseiService inMemorySenseiService ; private ProxyDataSource proxyDataSource ; private SenseiRequestFactory requestFactory ; public GenericBrokerProxy ( InMemorySenseiService inMemorySenseiService , ProxyDataSource proxyDataSource ) { Assert . notNull ( inMemorySenseiService ) ; Assert . notNull ( proxyDataSource ) ; this . inMemorySenseiService = inMemorySenseiService ; this . proxyDataSource = proxyDataSource ; } public GenericBrokerProxy ( ) { } @ Override public List < SenseiResult > doQuery ( SenseiRequest senseiRequest ) { List < JSONObject > documents = proxyDataSource . getData ( senseiRequest ) ; if ( requestFactory != null ) { senseiRequest = requestFactory . build ( senseiRequest ) ; } SenseiResult senseiResult = inMemorySenseiService . doQuery ( senseiRequest , documents ) ; return Arrays . asList ( senseiResult ) ; } public InMemorySenseiService getInMemorySenseiService ( ) { return inMemorySenseiService ; } public void setInMemorySenseiService ( InMemorySenseiService inMemorySenseiService ) { this . inMemorySenseiService = inMemorySenseiService ; } public ProxyDataSource getProxyDataSource ( ) { return proxyDataSource ; } public void setProxyDataSource ( ProxyDataSource proxyDataSource ) { this . proxyDataSource = proxyDataSource ; } public SenseiRequestFactory getRequestFactory ( ) { return requestFactory ; } public void setRequestFactory ( SenseiRequestFactory requestFactory ) { this . requestFactory = requestFactory ; } } </s>
<s> package com . senseidb . federated . broker . proxy ; import com . senseidb . metrics . MetricFactory ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import java . util . Map ; import java . util . concurrent . Callable ; import java . util . concurrent . TimeUnit ; import org . apache . commons . configuration . Configuration ; import org . apache . log4j . Logger ; import com . linkedin . norbert . javacompat . cluster . ClusterClient ; import com . linkedin . norbert . javacompat . network . PartitionedLoadBalancerFactory ; import com . linkedin . norbert . javacompat . network . PartitionedNetworkClient ; import com . senseidb . cluster . routing . SenseiPartitionedLoadBalancerFactory ; import com . senseidb . metrics . MetricsConstants ; import com . senseidb . search . node . AbstractConsistentHashBroker ; import com . senseidb . search . node . SenseiBroker ; import com . senseidb . search . req . ErrorType ; import com . senseidb . search . req . SenseiError ; import com . senseidb . search . req . SenseiRequest ; import com . senseidb . search . req . SenseiResult ; import com . yammer . metrics . core . Meter ; import com . yammer . metrics . core . MetricName ; import com . yammer . metrics . core . Timer ; public class SenseiBrokerProxy extends SenseiBroker implements BrokerProxy { private final static Logger logger = Logger . getLogger ( SenseiBrokerProxy . class ) ; private static PartitionedLoadBalancerFactory balancerFactory = new SenseiPartitionedLoadBalancerFactory ( <NUM_LIT> ) ; private final Timer scatterTimer ; private final Meter ErrorMeter ; public SenseiBrokerProxy ( PartitionedNetworkClient < String > networkClient , ClusterClient clusterClient , boolean allowPartialMerge ) { super ( networkClient , clusterClient , allowPartialMerge ) ; MetricName scatterMetricName = new MetricName ( SenseiBrokerProxy . class , "<STR_LIT>" ) ; scatterTimer = MetricFactory . newTimer ( scatterMetricName , TimeUnit . MILLISECONDS , TimeUnit . SECONDS ) ; MetricName errorMetricName = new MetricName ( SenseiBrokerProxy . class , "<STR_LIT>" ) ; ErrorMeter = MetricFactory . newMeter ( errorMetricName , "<STR_LIT>" , TimeUnit . SECONDS ) ; } public static SenseiBrokerProxy valueOf ( Configuration senseiConfiguration , Map < String , String > overrideProperties ) { BrokerProxyConfig brokerProxyConfig = new BrokerProxyConfig ( senseiConfiguration , balancerFactory , overrideProperties ) ; brokerProxyConfig . init ( ) ; SenseiBrokerProxy ret = new SenseiBrokerProxy ( brokerProxyConfig . getNetworkClient ( ) , brokerProxyConfig . getClusterClient ( ) , true ) ; return ret ; } @ Override public List < SenseiResult > doQuery ( final SenseiRequest senseiRequest ) { final List < SenseiResult > resultList = new ArrayList < SenseiResult > ( ) ; try { resultList . addAll ( scatterTimer . time ( new Callable < List < SenseiResult > > ( ) { @ Override public List < SenseiResult > call ( ) throws Exception { return doCall ( senseiRequest ) ; } } ) ) ; } catch ( Exception e ) { ErrorMeter . mark ( ) ; SenseiResult emptyResult = getEmptyResultInstance ( ) ; logger . error ( "<STR_LIT>" , e ) ; emptyResult . addError ( new SenseiError ( "<STR_LIT>" + e . getMessage ( ) , ErrorType . BrokerGatherError ) ) ; return Arrays . asList ( emptyResult ) ; } return resultList ; } } </s>
<s> package com . senseidb . federated . broker . proxy ; import java . util . List ; import com . senseidb . search . req . SenseiRequest ; import com . senseidb . search . req . SenseiResult ; public interface BrokerProxy { List < SenseiResult > doQuery ( SenseiRequest senseiRequest ) ; } </s>
<s> package com . senseidb . federated . broker . proxy ; import java . util . Map ; import org . apache . commons . configuration . Configuration ; import com . linkedin . norbert . javacompat . network . PartitionedLoadBalancerFactory ; import com . senseidb . conf . SenseiConfParams ; import com . senseidb . search . node . broker . BrokerConfig ; import com . senseidb . servlet . SenseiConfigServletContextListener ; public class BrokerProxyConfig extends BrokerConfig { public BrokerProxyConfig ( Configuration senseiConf , PartitionedLoadBalancerFactory < String > loadBalancerFactory , Map < String , String > config ) { super ( senseiConf , loadBalancerFactory ) ; clusterName = getStrParam ( config , SenseiConfParams . SENSEI_CLUSTER_NAME , clusterName ) ; zkurl = getStrParam ( config , SenseiConfParams . SENSEI_CLUSTER_URL , zkurl ) ; zkTimeout = getIntParam ( config , SenseiConfParams . SENSEI_CLUSTER_TIMEOUT , zkTimeout ) ; connectTimeoutMillis = getIntParam ( config , SenseiConfigServletContextListener . SENSEI_CONF_NC_CONN_TIMEOUT , connectTimeoutMillis ) ; writeTimeoutMillis = getIntParam ( config , SenseiConfigServletContextListener . SENSEI_CONF_NC_WRITE_TIMEOUT , writeTimeoutMillis ) ; maxConnectionsPerNode = getIntParam ( config , SenseiConfigServletContextListener . SENSEI_CONF_NC_MAX_CONN_PER_NODE , maxConnectionsPerNode ) ; staleRequestTimeoutMins = getIntParam ( config , SenseiConfigServletContextListener . SENSEI_CONF_NC_STALE_TIMEOUT_MINS , staleRequestTimeoutMins ) ; staleRequestCleanupFrequencyMins = getIntParam ( config , SenseiConfigServletContextListener . SENSEI_CONF_NC_STALE_CLEANUP_FREQ_MINS , staleRequestCleanupFrequencyMins ) ; } private String getStrParam ( Map < String , String > config , String paramName , String defaultParam ) { return config . containsKey ( paramName ) ? config . get ( paramName ) : defaultParam ; } private Integer getIntParam ( Map < String , String > config , String paramName , int defaultParam ) { return config . containsKey ( paramName ) ? Integer . parseInt ( config . get ( paramName ) ) : defaultParam ; } } </s>
<s> package com . senseidb . federated . broker . proxy ; import com . senseidb . search . req . SenseiRequest ; public interface SenseiRequestFactory { public SenseiRequest build ( SenseiRequest senseiRequest ) ; } </s>
<s> package org . apache . lucene . store ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . DataInput ; import java . io . DataInputStream ; import java . io . DataOutput ; import java . io . DataOutputStream ; import java . io . IOException ; import java . io . ObjectInputStream ; import java . io . ObjectOutputStream ; import java . util . ArrayList ; import java . util . Map . Entry ; public class RAMDirectorySerializer { private static void streamToBytes ( RAMFile ramFile , DataOutput out ) throws IOException { out . writeLong ( ramFile . getLastModified ( ) ) ; out . writeLong ( ramFile . sizeInBytes ) ; out . writeLong ( ramFile . length ) ; if ( ramFile . buffers == null ) { out . writeInt ( <NUM_LIT:0> ) ; } else { out . writeInt ( ramFile . buffers . size ( ) ) ; for ( byte [ ] bytes : ramFile . buffers ) { out . writeInt ( bytes . length ) ; out . write ( bytes ) ; } } } private static void loadFromBytes ( RAMFile rfile , DataInput din ) throws IOException { rfile . setLastModified ( din . readLong ( ) ) ; rfile . sizeInBytes = din . readLong ( ) ; rfile . length = din . readLong ( ) ; int count = din . readInt ( ) ; rfile . buffers = new ArrayList < byte [ ] > ( count ) ; for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { int size = din . readInt ( ) ; byte [ ] bytes = new byte [ size ] ; din . readFully ( bytes ) ; rfile . buffers . add ( bytes ) ; } } public static byte [ ] toBytes ( RAMDirectory dir ) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream ( dir . sizeInBytes . intValue ( ) ) ; DataOutputStream dout = new DataOutputStream ( bout ) ; toDataOutput ( dout , dir ) ; dout . flush ( ) ; return bout . toByteArray ( ) ; } public static void toDataOutput ( DataOutput dout , RAMDirectory dir ) throws IOException { dout . writeLong ( dir . sizeInBytes ( ) ) ; dout . writeInt ( dir . fileMap . size ( ) ) ; for ( Entry < String , RAMFile > entry : dir . fileMap . entrySet ( ) ) { dout . writeUTF ( entry . getKey ( ) ) ; streamToBytes ( entry . getValue ( ) , dout ) ; } } public static RAMDirectory fromBytes ( byte [ ] bytes ) throws IOException { ByteArrayInputStream bin = new ByteArrayInputStream ( bytes ) ; DataInputStream din = new DataInputStream ( bin ) ; return fromDataInput ( din ) ; } public static RAMDirectory fromDataInput ( DataInput din ) throws IOException { RAMDirectory rdir = new RAMDirectory ( ) ; rdir . sizeInBytes . set ( din . readLong ( ) ) ; int count = din . readInt ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { String fileName = din . readUTF ( ) ; RAMFile rfile = new RAMFile ( rdir ) ; loadFromBytes ( rfile , din ) ; rdir . fileMap . put ( fileName , rfile ) ; } return rdir ; } private static RAMDirectory createMock ( int nfiles , int size ) throws IOException { RAMDirectory dir = new RAMDirectory ( ) ; for ( int i = <NUM_LIT:0> ; i < nfiles ; ++ i ) { IndexOutput output = dir . createOutput ( String . valueOf ( i ) ) ; byte [ ] bytes = new byte [ size ] ; output . writeBytes ( bytes , size ) ; output . flush ( ) ; output . close ( ) ; } return dir ; } private static byte [ ] serializeWithJava ( RAMDirectory rdir ) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; ObjectOutputStream oout = new ObjectOutputStream ( bout ) ; oout . writeObject ( rdir ) ; oout . flush ( ) ; return bout . toByteArray ( ) ; } private static RAMDirectory deserializeWithJava ( byte [ ] bytes ) throws Exception { ByteArrayInputStream bin = new ByteArrayInputStream ( bytes ) ; ObjectInputStream oin = new ObjectInputStream ( bin ) ; return ( RAMDirectory ) ( oin . readObject ( ) ) ; } public static void main ( String [ ] args ) throws Exception { int numFiles = <NUM_LIT:1> ; int avgSize = <NUM_LIT> ; int numIter = <NUM_LIT:20> ; long start , end ; long t1 , t2 ; RAMDirectory mockDir = createMock ( numFiles , avgSize ) ; for ( int i = <NUM_LIT:0> ; i < numIter ; ++ i ) { start = System . nanoTime ( ) ; byte [ ] javaBytes = serializeWithJava ( mockDir ) ; end = System . nanoTime ( ) ; t1 = ( end - start ) ; System . out . println ( "<STR_LIT>" + javaBytes . length + "<STR_LIT>" + t1 ) ; start = System . nanoTime ( ) ; byte [ ] bytes = toBytes ( mockDir ) ; end = System . nanoTime ( ) ; t2 = ( end - start ) ; System . out . println ( "<STR_LIT>" + bytes . length + "<STR_LIT>" + t2 ) ; System . out . println ( "<STR_LIT>" + ( double ) bytes . length / ( double ) javaBytes . length * <NUM_LIT> + "<STR_LIT>" + ( double ) t2 / ( double ) t1 * <NUM_LIT> ) ; start = System . nanoTime ( ) ; mockDir = deserializeWithJava ( javaBytes ) ; end = System . nanoTime ( ) ; t1 = end - start ; System . out . println ( "<STR_LIT>" + t1 ) ; start = System . nanoTime ( ) ; mockDir = fromBytes ( bytes ) ; end = System . nanoTime ( ) ; t2 = end - start ; System . out . println ( "<STR_LIT>" + t2 ) ; System . out . println ( "<STR_LIT>" + ( double ) t2 / ( double ) t1 * <NUM_LIT> ) ; } } } </s>
<s> package org . apache . lucene . store ; import java . io . IOException ; import java . io . StringReader ; import org . apache . lucene . analysis . standard . StandardAnalyzer ; import org . apache . lucene . document . Document ; import org . apache . lucene . document . Field ; import org . apache . lucene . index . CorruptIndexException ; import org . apache . lucene . index . IndexWriter ; import org . apache . lucene . queryParser . ParseException ; import org . apache . lucene . queryParser . QueryParser ; import org . apache . lucene . search . IndexSearcher ; import org . apache . lucene . search . Query ; import org . apache . lucene . search . ScoreDoc ; import org . apache . lucene . search . Searcher ; import org . apache . lucene . search . TopDocs ; import org . apache . lucene . store . RAMDirectory ; import org . apache . lucene . util . Version ; public class TestRAMDirectorySerializer { public static void main ( String [ ] args ) { RAMDirectory idx = new RAMDirectory ( ) ; try { IndexWriter writer = new IndexWriter ( idx , new StandardAnalyzer ( Version . LUCENE_CURRENT ) , true , IndexWriter . MaxFieldLength . UNLIMITED ) ; writer . addDocument ( createDocument ( "<STR_LIT>" , "<STR_LIT>" ) ) ; writer . addDocument ( createDocument ( "<STR_LIT>" , "<STR_LIT>" ) ) ; writer . addDocument ( createDocument ( "<STR_LIT>" , "<STR_LIT>" ) ) ; writer . addDocument ( createDocument ( "<STR_LIT>" , "<STR_LIT>" ) ) ; writer . optimize ( ) ; writer . close ( ) ; byte [ ] bytes = RAMDirectorySerializer . toBytes ( idx ) ; RAMDirectory idxNew = RAMDirectorySerializer . fromBytes ( bytes ) ; searchIndex ( idx ) ; System . out . println ( "<STR_LIT>" ) ; searchIndex ( idxNew ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } catch ( ParseException pe ) { pe . printStackTrace ( ) ; } } private static void searchIndex ( RAMDirectory idx ) throws CorruptIndexException , IOException , ParseException { Searcher searcher = new IndexSearcher ( idx ) ; search ( searcher , "<STR_LIT>" ) ; search ( searcher , "<STR_LIT>" ) ; search ( searcher , "<STR_LIT>" ) ; searcher . close ( ) ; } private static Document createDocument ( String title , String content ) { Document doc = new Document ( ) ; doc . add ( new Field ( "<STR_LIT:title>" , title , Field . Store . YES , Field . Index . NO ) ) ; doc . add ( new Field ( "<STR_LIT:content>" , new StringReader ( content ) ) ) ; return doc ; } private static void search ( Searcher searcher , String queryString ) throws ParseException , IOException { QueryParser parser = new QueryParser ( Version . LUCENE_CURRENT , "<STR_LIT:content>" , new StandardAnalyzer ( Version . LUCENE_CURRENT ) ) ; Query query = parser . parse ( queryString ) ; int numHits = <NUM_LIT:100> ; TopDocs topDocs = searcher . search ( query , numHits ) ; ScoreDoc [ ] hits = topDocs . scoreDocs ; for ( int i = <NUM_LIT:0> ; i < hits . length ; i ++ ) { int docId = hits [ i ] . doc ; float score = hits [ i ] . score ; Document d = searcher . doc ( docId ) ; System . out . println ( "<STR_LIT>" + docId + "<STR_LIT>" + score + "<STR_LIT:t>" + d . get ( "<STR_LIT:title>" ) ) ; } System . out . println ( ) ; } } </s>
<s> package com . senseidb . indexing . hadoop . job ; import java . io . IOException ; import java . net . URI ; import java . net . URISyntaxException ; import java . text . NumberFormat ; import java . util . Arrays ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . conf . Configured ; import org . apache . hadoop . filecache . DistributedCache ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . fs . Trash ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . mapred . FileInputFormat ; import org . apache . hadoop . mapred . FileOutputFormat ; import org . apache . hadoop . mapred . InputFormat ; import org . apache . hadoop . mapred . JobConf ; import org . apache . hadoop . mapred . TextInputFormat ; import org . apache . hadoop . util . StringUtils ; import org . apache . log4j . Logger ; import com . senseidb . indexing . hadoop . keyvalueformat . IntermediateForm ; import com . senseidb . indexing . hadoop . keyvalueformat . Shard ; import com . senseidb . indexing . hadoop . map . SenseiMapper ; import com . senseidb . indexing . hadoop . reduce . FileSystemDirectory ; import com . senseidb . indexing . hadoop . reduce . IndexUpdateOutputFormat ; import com . senseidb . indexing . hadoop . reduce . SenseiCombiner ; import com . senseidb . indexing . hadoop . reduce . SenseiReducer ; import com . senseidb . indexing . hadoop . util . LuceneUtil ; import com . senseidb . indexing . hadoop . util . MRConfig ; import com . senseidb . indexing . hadoop . util . MRJobConfig ; import com . senseidb . indexing . hadoop . util . SenseiJobConfig ; public class MapReduceJob extends Configured { private static final NumberFormat NUMBER_FORMAT = NumberFormat . getInstance ( ) ; private static final Logger logger = Logger . getLogger ( MapReduceJob . class ) ; public JobConf createJob ( Class MRClass ) throws IOException , URISyntaxException { Configuration conf = getConf ( ) ; Path [ ] inputPaths ; Path outputPath ; Shard [ ] shards = null ; int numMapTasks = conf . getInt ( MRJobConfig . NUM_MAPS , <NUM_LIT:2> ) ; int numShards = conf . getInt ( SenseiJobConfig . NUM_SHARDS , <NUM_LIT:2> ) ; String dirs = conf . get ( SenseiJobConfig . INPUT_DIRS , null ) ; logger . info ( "<STR_LIT>" + dirs ) ; String [ ] list = StringUtils . split ( dirs ) ; logger . info ( "<STR_LIT>" + list . length ) ; inputPaths = new Path [ list . length ] ; for ( int i = <NUM_LIT:0> ; i < list . length ; i ++ ) { inputPaths [ i ] = new Path ( StringUtils . unEscapeString ( list [ i ] ) ) ; } logger . info ( "<STR_LIT>" + inputPaths [ <NUM_LIT:0> ] ) ; outputPath = new Path ( conf . get ( SenseiJobConfig . OUTPUT_DIR ) ) ; String indexPath = conf . get ( SenseiJobConfig . INDEX_PATH ) ; String indexSubDirPrefix = conf . get ( SenseiJobConfig . INDEX_SUBDIR_PREFIX , "<STR_LIT>" ) ; shards = createShards ( indexPath , numShards , conf , indexSubDirPrefix ) ; FileSystem fs = FileSystem . get ( conf ) ; String username = conf . get ( "<STR_LIT>" ) ; if ( fs . exists ( outputPath ) && conf . getBoolean ( SenseiJobConfig . FORCE_OUTPUT_OVERWRITE , false ) ) fs . delete ( outputPath , true ) ; if ( fs . exists ( new Path ( indexPath ) ) && conf . getBoolean ( SenseiJobConfig . FORCE_OUTPUT_OVERWRITE , false ) ) fs . delete ( new Path ( indexPath ) , true ) ; setShardGeneration ( conf , shards ) ; Shard . setIndexShards ( conf , shards ) ; conf . setInt ( MRJobConfig . IO_SORT_MB , conf . getInt ( MRJobConfig . IO_SORT_MB , <NUM_LIT:100> ) / <NUM_LIT:2> ) ; conf . set ( MRConfig . TEMP_DIR , "<STR_LIT>" ) ; if ( fs . exists ( new Path ( conf . get ( MRConfig . TEMP_DIR ) ) ) ) fs . delete ( new Path ( conf . get ( MRConfig . TEMP_DIR ) ) , true ) ; if ( fs . exists ( new Path ( "<STR_LIT>" ) ) ) fs . delete ( new Path ( "<STR_LIT>" ) , true ) ; ( new Trash ( conf ) ) . expunge ( ) ; conf . setBoolean ( SenseiJobConfig . USE_COMPOUND_FILE , true ) ; String schemaFile = conf . get ( SenseiJobConfig . SCHEMA_FILE_URL ) ; if ( schemaFile == null ) throw new IOException ( "<STR_LIT>" ) ; else { logger . info ( "<STR_LIT>" + conf . get ( SenseiJobConfig . SCHEMA_FILE_URL ) ) ; DistributedCache . addCacheFile ( new URI ( schemaFile ) , conf ) ; } JobConf jobConf = new JobConf ( conf , MRClass ) ; if ( jobConf . getJobName ( ) . length ( ) < <NUM_LIT:1> ) jobConf . setJobName ( MRClass . getName ( ) + "<STR_LIT:_>" + System . currentTimeMillis ( ) ) ; FileInputFormat . setInputPaths ( jobConf , inputPaths ) ; FileOutputFormat . setOutputPath ( jobConf , outputPath ) ; jobConf . setNumMapTasks ( numMapTasks ) ; jobConf . setNumReduceTasks ( shards . length ) ; jobConf . setInputFormat ( conf . getClass ( SenseiJobConfig . INPUT_FORMAT , TextInputFormat . class , InputFormat . class ) ) ; Path [ ] inputs = FileInputFormat . getInputPaths ( jobConf ) ; StringBuilder buffer = new StringBuilder ( inputs [ <NUM_LIT:0> ] . toString ( ) ) ; for ( int i = <NUM_LIT:1> ; i < inputs . length ; i ++ ) { buffer . append ( "<STR_LIT:U+002C>" ) ; buffer . append ( inputs [ i ] . toString ( ) ) ; } logger . info ( "<STR_LIT>" + buffer . toString ( ) ) ; logger . info ( "<STR_LIT>" + FileOutputFormat . getOutputPath ( jobConf ) . toString ( ) ) ; logger . info ( "<STR_LIT>" + jobConf . getNumMapTasks ( ) ) ; logger . info ( "<STR_LIT>" + jobConf . getNumReduceTasks ( ) ) ; logger . info ( shards . length + "<STR_LIT>" + conf . get ( SenseiJobConfig . INDEX_SHARDS ) ) ; logger . info ( "<STR_LIT>" + jobConf . getInputFormat ( ) . getClass ( ) . getName ( ) ) ; logger . info ( "<STR_LIT>" + jobConf . get ( MRConfig . TEMP_DIR ) ) ; jobConf . setMapOutputKeyClass ( Shard . class ) ; jobConf . setMapOutputValueClass ( IntermediateForm . class ) ; jobConf . setOutputKeyClass ( Shard . class ) ; jobConf . setOutputValueClass ( Text . class ) ; jobConf . setMapperClass ( SenseiMapper . class ) ; jobConf . setCombinerClass ( SenseiCombiner . class ) ; jobConf . setReducerClass ( SenseiReducer . class ) ; jobConf . setOutputFormat ( IndexUpdateOutputFormat . class ) ; jobConf . setReduceSpeculativeExecution ( false ) ; return jobConf ; } private static FileSystem getFileSystem ( String user ) { Configuration conf = new Configuration ( ) ; conf . set ( "<STR_LIT>" , user ) ; try { return FileSystem . get ( conf ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } private static Shard [ ] createShards ( String indexPath , int numShards , org . apache . hadoop . conf . Configuration conf , String indexSubDirPrefix ) throws IOException { String parent = Shard . normalizePath ( indexPath ) + Path . SEPARATOR ; long versionNumber = - <NUM_LIT:1> ; long generation = - <NUM_LIT:1> ; FileSystem fs = FileSystem . get ( conf ) ; Path path = new Path ( indexPath ) ; if ( fs . exists ( path ) ) { FileStatus [ ] fileStatus = fs . listStatus ( path ) ; String [ ] shardNames = new String [ fileStatus . length ] ; int count = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < fileStatus . length ; i ++ ) { if ( fileStatus [ i ] . isDir ( ) ) { shardNames [ count ] = fileStatus [ i ] . getPath ( ) . getName ( ) ; count ++ ; } } Arrays . sort ( shardNames , <NUM_LIT:0> , count ) ; Shard [ ] shards = new Shard [ count >= numShards ? count : numShards ] ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { shards [ i ] = new Shard ( versionNumber , parent + shardNames [ i ] , generation ) ; } int number = count ; for ( int i = count ; i < numShards ; i ++ ) { String shardPath ; while ( true ) { shardPath = parent + indexSubDirPrefix + NUMBER_FORMAT . format ( number ++ ) ; if ( ! fs . exists ( new Path ( shardPath ) ) ) { break ; } } shards [ i ] = new Shard ( versionNumber , shardPath , generation ) ; } return shards ; } else { Shard [ ] shards = new Shard [ numShards ] ; for ( int i = <NUM_LIT:0> ; i < shards . length ; i ++ ) { shards [ i ] = new Shard ( versionNumber , parent + indexSubDirPrefix + NUMBER_FORMAT . format ( i ) , generation ) ; } return shards ; } } void setShardGeneration ( Configuration conf , Shard [ ] shards ) throws IOException { FileSystem fs = FileSystem . get ( conf ) ; for ( int i = <NUM_LIT:0> ; i < shards . length ; i ++ ) { Path path = new Path ( shards [ i ] . getDirectory ( ) ) ; long generation = - <NUM_LIT:1> ; if ( fs . exists ( path ) ) { FileSystemDirectory dir = null ; try { dir = new FileSystemDirectory ( fs , path , false , conf ) ; generation = LuceneUtil . getCurrentSegmentGeneration ( dir ) ; } finally { if ( dir != null ) { dir . close ( ) ; } } } if ( generation != shards [ i ] . getGeneration ( ) ) { shards [ i ] = new Shard ( shards [ i ] . getVersion ( ) , shards [ i ] . getDirectory ( ) , generation ) ; } } } } </s>
<s> package com . senseidb . indexing . hadoop . reduce ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . io . Text ; import org . apache . lucene . store . IndexInput ; import org . apache . lucene . store . IndexOutput ; import org . apache . lucene . store . RAMDirectory ; public class RAMDirectoryUtil { private static final int BUFFER_SIZE = <NUM_LIT> ; public static void writeRAMFiles ( DataOutput out , RAMDirectory dir , String [ ] names ) throws IOException { out . writeInt ( names . length ) ; for ( int i = <NUM_LIT:0> ; i < names . length ; i ++ ) { Text . writeString ( out , names [ i ] ) ; long length = dir . fileLength ( names [ i ] ) ; out . writeLong ( length ) ; if ( length > <NUM_LIT:0> ) { IndexInput input = null ; try { input = dir . openInput ( names [ i ] , BUFFER_SIZE ) ; int position = <NUM_LIT:0> ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; while ( position < length ) { int len = position + BUFFER_SIZE <= length ? BUFFER_SIZE : ( int ) ( length - position ) ; input . readBytes ( buffer , <NUM_LIT:0> , len ) ; out . write ( buffer , <NUM_LIT:0> , len ) ; position += len ; } } finally { if ( input != null ) { input . close ( ) ; } } } } } public static void readRAMFiles ( DataInput in , RAMDirectory dir ) throws IOException { int numFiles = in . readInt ( ) ; for ( int i = <NUM_LIT:0> ; i < numFiles ; i ++ ) { String name = Text . readString ( in ) ; long length = in . readLong ( ) ; if ( length > <NUM_LIT:0> ) { IndexOutput output = null ; try { output = dir . createOutput ( name ) ; int position = <NUM_LIT:0> ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; while ( position < length ) { int len = position + BUFFER_SIZE <= length ? BUFFER_SIZE : ( int ) ( length - position ) ; in . readFully ( buffer , <NUM_LIT:0> , len ) ; output . writeBytes ( buffer , <NUM_LIT:0> , len ) ; position += len ; } } finally { if ( output != null ) { output . close ( ) ; } } } } } } </s>
<s> package com . senseidb . indexing . hadoop . reduce ; import java . io . IOException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FSDataInputStream ; import org . apache . hadoop . fs . FSDataOutputStream ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . lucene . store . BufferedIndexInput ; import org . apache . lucene . store . BufferedIndexOutput ; import org . apache . lucene . store . Directory ; import org . apache . lucene . store . IndexInput ; import org . apache . lucene . store . IndexOutput ; import org . apache . lucene . store . Lock ; import com . senseidb . indexing . hadoop . util . LuceneIndexFileNameFilter ; public class FileSystemDirectory extends Directory { private final FileSystem fs ; private final Path directory ; private final int ioFileBufferSize ; public FileSystemDirectory ( FileSystem fs , Path directory , boolean create , Configuration conf ) throws IOException { this . fs = fs ; this . directory = directory ; this . ioFileBufferSize = conf . getInt ( "<STR_LIT>" , <NUM_LIT> ) ; if ( create ) { create ( ) ; } boolean isDir = false ; try { FileStatus status = fs . getFileStatus ( directory ) ; if ( status != null ) { isDir = status . isDir ( ) ; } } catch ( IOException e ) { } if ( ! isDir ) { throw new IOException ( directory + "<STR_LIT>" ) ; } } private void create ( ) throws IOException { if ( ! fs . exists ( directory ) ) { fs . mkdirs ( directory ) ; } boolean isDir = false ; try { FileStatus status = fs . getFileStatus ( directory ) ; if ( status != null ) { isDir = status . isDir ( ) ; } } catch ( IOException e ) { } if ( ! isDir ) { throw new IOException ( directory + "<STR_LIT>" ) ; } FileStatus [ ] fileStatus = fs . listStatus ( directory , LuceneIndexFileNameFilter . getFilter ( ) ) ; for ( int i = <NUM_LIT:0> ; i < fileStatus . length ; i ++ ) { if ( ! fs . delete ( fileStatus [ i ] . getPath ( ) , true ) ) { throw new IOException ( "<STR_LIT>" + fileStatus [ i ] . getPath ( ) ) ; } } } public String [ ] listAll ( ) throws IOException { FileStatus [ ] fileStatus = fs . listStatus ( directory , LuceneIndexFileNameFilter . getFilter ( ) ) ; String [ ] result = new String [ fileStatus . length ] ; for ( int i = <NUM_LIT:0> ; i < fileStatus . length ; i ++ ) { result [ i ] = fileStatus [ i ] . getPath ( ) . getName ( ) ; } return result ; } public boolean fileExists ( String name ) throws IOException { return fs . exists ( new Path ( directory , name ) ) ; } public long fileModified ( String name ) { throw new UnsupportedOperationException ( ) ; } public void touchFile ( String name ) { throw new UnsupportedOperationException ( ) ; } public long fileLength ( String name ) throws IOException { return fs . getFileStatus ( new Path ( directory , name ) ) . getLen ( ) ; } public void deleteFile ( String name ) throws IOException { if ( ! fs . delete ( new Path ( directory , name ) , true ) ) { throw new IOException ( "<STR_LIT>" + name ) ; } } public void renameFile ( String from , String to ) throws IOException { fs . rename ( new Path ( directory , from ) , new Path ( directory , to ) ) ; } public IndexOutput createOutput ( String name ) throws IOException { Path file = new Path ( directory , name ) ; if ( fs . exists ( file ) && ! fs . delete ( file , true ) ) { throw new IOException ( "<STR_LIT>" + file ) ; } return new FileSystemIndexOutput ( file , ioFileBufferSize ) ; } public IndexInput openInput ( String name ) throws IOException { return openInput ( name , ioFileBufferSize ) ; } public IndexInput openInput ( String name , int bufferSize ) throws IOException { return new FileSystemIndexInput ( new Path ( directory , name ) , bufferSize ) ; } public Lock makeLock ( final String name ) { return new Lock ( ) { public boolean obtain ( ) { return true ; } public void release ( ) { } public boolean isLocked ( ) { throw new UnsupportedOperationException ( ) ; } public String toString ( ) { return "<STR_LIT>" + new Path ( directory , name ) ; } } ; } public void close ( ) throws IOException { } public String toString ( ) { return this . getClass ( ) . getName ( ) + "<STR_LIT:@>" + directory ; } private class FileSystemIndexInput extends BufferedIndexInput { private class Descriptor { public final FSDataInputStream in ; public long position ; public Descriptor ( Path file , int ioFileBufferSize ) throws IOException { this . in = fs . open ( file , ioFileBufferSize ) ; } } private final Path filePath ; private final Descriptor descriptor ; private final long length ; private boolean isOpen ; private boolean isClone ; public FileSystemIndexInput ( Path path , int ioFileBufferSize ) throws IOException { filePath = path ; descriptor = new Descriptor ( path , ioFileBufferSize ) ; length = fs . getFileStatus ( path ) . getLen ( ) ; isOpen = true ; } protected void readInternal ( byte [ ] b , int offset , int len ) throws IOException { synchronized ( descriptor ) { long position = getFilePointer ( ) ; if ( position != descriptor . position ) { descriptor . in . seek ( position ) ; descriptor . position = position ; } int total = <NUM_LIT:0> ; do { int i = descriptor . in . read ( b , offset + total , len - total ) ; if ( i == - <NUM_LIT:1> ) { throw new IOException ( "<STR_LIT>" ) ; } descriptor . position += i ; total += i ; } while ( total < len ) ; } } public void close ( ) throws IOException { if ( ! isClone ) { if ( isOpen ) { descriptor . in . close ( ) ; isOpen = false ; } else { throw new IOException ( "<STR_LIT>" + filePath + "<STR_LIT>" ) ; } } } protected void seekInternal ( long position ) { } public long length ( ) { return length ; } protected void finalize ( ) throws IOException { if ( ! isClone && isOpen ) { close ( ) ; } } public Object clone ( ) { FileSystemIndexInput clone = ( FileSystemIndexInput ) super . clone ( ) ; clone . isClone = true ; return clone ; } } private class FileSystemIndexOutput extends BufferedIndexOutput { private final Path filePath ; private final FSDataOutputStream out ; private boolean isOpen ; public FileSystemIndexOutput ( Path path , int ioFileBufferSize ) throws IOException { filePath = path ; out = fs . create ( path , true , ioFileBufferSize ) ; isOpen = true ; } public void flushBuffer ( byte [ ] b , int offset , int size ) throws IOException { out . write ( b , offset , size ) ; } public void close ( ) throws IOException { if ( isOpen ) { super . close ( ) ; out . close ( ) ; isOpen = false ; } else { throw new IOException ( "<STR_LIT>" + filePath + "<STR_LIT>" ) ; } } public void seek ( long pos ) throws IOException { throw new UnsupportedOperationException ( ) ; } public long length ( ) throws IOException { return out . getPos ( ) ; } protected void finalize ( ) throws IOException { if ( isOpen ) { close ( ) ; } } } } </s>
<s> package com . senseidb . indexing . hadoop . reduce ; import java . io . File ; import java . io . IOException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . lucene . store . Directory ; import org . apache . lucene . store . FSDirectory ; import org . apache . lucene . store . IndexInput ; import org . apache . lucene . store . IndexOutput ; import org . apache . lucene . store . NoLockFactory ; class MixedDirectory extends Directory { private final Directory readDir ; private final Directory writeDir ; public MixedDirectory ( FileSystem readFs , Path readPath , FileSystem writeFs , Path writePath , Configuration conf ) throws IOException { try { readDir = new FileSystemDirectory ( readFs , readPath , false , conf ) ; writeDir = FSDirectory . open ( new File ( writePath . toString ( ) ) ) ; } catch ( IOException e ) { try { close ( ) ; } catch ( IOException e1 ) { } throw e ; } lockFactory = new NoLockFactory ( ) ; } MixedDirectory ( Directory readDir , Directory writeDir ) throws IOException { this . readDir = readDir ; this . writeDir = writeDir ; lockFactory = new NoLockFactory ( ) ; } @ Override public String [ ] listAll ( ) throws IOException { String [ ] readFiles = readDir . listAll ( ) ; String [ ] writeFiles = writeDir . listAll ( ) ; if ( readFiles == null || readFiles . length == <NUM_LIT:0> ) { return writeFiles ; } else if ( writeFiles == null || writeFiles . length == <NUM_LIT:0> ) { return readFiles ; } else { String [ ] result = new String [ readFiles . length + writeFiles . length ] ; System . arraycopy ( readFiles , <NUM_LIT:0> , result , <NUM_LIT:0> , readFiles . length ) ; System . arraycopy ( writeFiles , <NUM_LIT:0> , result , readFiles . length , writeFiles . length ) ; return result ; } } @ Override public void deleteFile ( String name ) throws IOException { if ( writeDir . fileExists ( name ) ) { writeDir . deleteFile ( name ) ; } if ( readDir . fileExists ( name ) ) { readDir . deleteFile ( name ) ; } } @ Override public boolean fileExists ( String name ) throws IOException { return writeDir . fileExists ( name ) || readDir . fileExists ( name ) ; } @ Override public long fileLength ( String name ) throws IOException { if ( writeDir . fileExists ( name ) ) { return writeDir . fileLength ( name ) ; } else { return readDir . fileLength ( name ) ; } } @ Override public long fileModified ( String name ) throws IOException { if ( writeDir . fileExists ( name ) ) { return writeDir . fileModified ( name ) ; } else { return readDir . fileModified ( name ) ; } } public void renameFile ( String from , String to ) throws IOException { throw new UnsupportedOperationException ( ) ; } @ Override public void touchFile ( String name ) throws IOException { if ( writeDir . fileExists ( name ) ) { writeDir . touchFile ( name ) ; } else { readDir . touchFile ( name ) ; } } @ Override public IndexOutput createOutput ( String name ) throws IOException { return writeDir . createOutput ( name ) ; } @ Override public IndexInput openInput ( String name ) throws IOException { if ( writeDir . fileExists ( name ) ) { return writeDir . openInput ( name ) ; } else { return readDir . openInput ( name ) ; } } @ Override public IndexInput openInput ( String name , int bufferSize ) throws IOException { if ( writeDir . fileExists ( name ) ) { return writeDir . openInput ( name , bufferSize ) ; } else { return readDir . openInput ( name , bufferSize ) ; } } @ Override public void close ( ) throws IOException { try { if ( readDir != null ) { readDir . close ( ) ; } } finally { if ( writeDir != null ) { writeDir . close ( ) ; } } } public String toString ( ) { return this . getClass ( ) . getName ( ) + "<STR_LIT:@>" + readDir + "<STR_LIT:&>" + writeDir ; } } </s>
<s> package com . senseidb . indexing . hadoop . reduce ; import java . io . File ; import java . io . IOException ; import java . util . Iterator ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Closeable ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . mapred . JobConf ; import org . apache . hadoop . mapred . MapReduceBase ; import org . apache . hadoop . mapred . OutputCollector ; import org . apache . hadoop . mapred . Reducer ; import org . apache . hadoop . mapred . Reporter ; import org . apache . log4j . Logger ; import com . senseidb . indexing . hadoop . keyvalueformat . IntermediateForm ; import com . senseidb . indexing . hadoop . keyvalueformat . Shard ; import com . senseidb . indexing . hadoop . util . MRConfig ; public class SenseiReducer extends MapReduceBase implements Reducer < Shard , IntermediateForm , Shard , Text > { private static final Logger logger = Logger . getLogger ( SenseiReducer . class ) ; static final Text DONE = new Text ( "<STR_LIT>" ) ; private Configuration iconf ; private String mapredTempDir ; public void reduce ( Shard key , Iterator < IntermediateForm > values , OutputCollector < Shard , Text > output , Reporter reporter ) throws IOException { logger . info ( "<STR_LIT>" + key ) ; FileSystem fs = FileSystem . get ( iconf ) ; logger . info ( "<STR_LIT>" + fs . getName ( ) ) ; String temp = mapredTempDir + Path . SEPARATOR + "<STR_LIT>" + key . toFlatString ( ) + "<STR_LIT:_>" + System . currentTimeMillis ( ) ; logger . info ( "<STR_LIT>" + mapredTempDir ) ; final ShardWriter writer = new ShardWriter ( fs , key , temp , iconf ) ; while ( values . hasNext ( ) ) { IntermediateForm form = values . next ( ) ; writer . process ( form ) ; reporter . progress ( ) ; } final Reporter fReporter = reporter ; new Closeable ( ) { volatile boolean closed = false ; public void close ( ) throws IOException { Thread prog = new Thread ( ) { public void run ( ) { while ( ! closed ) { try { fReporter . setStatus ( "<STR_LIT>" ) ; Thread . sleep ( <NUM_LIT:1000> ) ; } catch ( InterruptedException e ) { continue ; } catch ( Throwable e ) { return ; } } } } ; try { prog . start ( ) ; if ( writer != null ) { writer . optimize ( ) ; writer . close ( ) ; } } finally { closed = true ; } } } . close ( ) ; logger . info ( "<STR_LIT>" + key + "<STR_LIT>" + writer ) ; output . collect ( key , DONE ) ; } @ Override public void close ( ) throws IOException { if ( mapredTempDir != null ) { File file = new File ( mapredTempDir ) ; if ( file . exists ( ) ) deleteDir ( file ) ; } } static void deleteDir ( File file ) { if ( file == null || ! file . exists ( ) ) return ; for ( File f : file . listFiles ( ) ) { if ( f . isDirectory ( ) ) deleteDir ( f ) ; else f . delete ( ) ; } file . delete ( ) ; } public void configure ( JobConf job ) { iconf = job ; mapredTempDir = iconf . get ( MRConfig . TEMP_DIR ) ; mapredTempDir = Shard . normalizePath ( mapredTempDir ) ; } } </s>
<s> package com . senseidb . indexing . hadoop . reduce ; import java . io . IOException ; import java . util . Iterator ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . mapred . JobConf ; import org . apache . hadoop . mapred . MapReduceBase ; import org . apache . hadoop . mapred . OutputCollector ; import org . apache . hadoop . mapred . Reducer ; import org . apache . hadoop . mapred . Reporter ; import org . apache . log4j . Logger ; import com . senseidb . indexing . hadoop . keyvalueformat . IntermediateForm ; import com . senseidb . indexing . hadoop . keyvalueformat . Shard ; import com . senseidb . indexing . hadoop . util . SenseiJobConfig ; public class SenseiCombiner extends MapReduceBase implements Reducer < Shard , IntermediateForm , Shard , IntermediateForm > { private static final Logger logger = Logger . getLogger ( SenseiCombiner . class ) ; Configuration iconf ; long maxSizeInBytes ; long nearMaxSizeInBytes ; public void reduce ( Shard key , Iterator < IntermediateForm > values , OutputCollector < Shard , IntermediateForm > output , Reporter reporter ) throws IOException { String message = key . toString ( ) ; IntermediateForm form = null ; while ( values . hasNext ( ) ) { IntermediateForm singleDocForm = values . next ( ) ; long formSize = form == null ? <NUM_LIT:0> : form . totalSizeInBytes ( ) ; long singleDocFormSize = singleDocForm . totalSizeInBytes ( ) ; if ( form != null && formSize + singleDocFormSize > maxSizeInBytes ) { closeForm ( form , message ) ; output . collect ( key , form ) ; form = null ; } if ( form == null && singleDocFormSize >= nearMaxSizeInBytes ) { output . collect ( key , singleDocForm ) ; } else { if ( form == null ) { form = createForm ( message ) ; } form . process ( singleDocForm ) ; } } if ( form != null ) { closeForm ( form , message ) ; output . collect ( key , form ) ; } } private IntermediateForm createForm ( String message ) throws IOException { logger . info ( "<STR_LIT>" + message ) ; IntermediateForm form = new IntermediateForm ( ) ; form . configure ( iconf ) ; return form ; } private void closeForm ( IntermediateForm form , String message ) throws IOException { form . closeWriter ( ) ; logger . info ( "<STR_LIT>" + message + "<STR_LIT>" + form ) ; } public void configure ( JobConf job ) { iconf = new Configuration ( job ) ; maxSizeInBytes = iconf . getLong ( SenseiJobConfig . MAX_RAMSIZE_BYTES , <NUM_LIT> << <NUM_LIT:20> ) ; nearMaxSizeInBytes = maxSizeInBytes - ( maxSizeInBytes > > > <NUM_LIT:3> ) ; } public void close ( ) throws IOException { } } </s>
<s> package com . senseidb . indexing . hadoop . reduce ; import java . io . IOException ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . mapred . FileOutputFormat ; import org . apache . hadoop . mapred . JobConf ; import org . apache . hadoop . mapred . RecordWriter ; import org . apache . hadoop . mapred . Reporter ; import org . apache . hadoop . util . Progressable ; import com . senseidb . indexing . hadoop . keyvalueformat . Shard ; public class IndexUpdateOutputFormat extends FileOutputFormat < Shard , Text > { static final Text DONE = new Text ( "<STR_LIT>" ) ; public RecordWriter < Shard , Text > getRecordWriter ( final FileSystem fs , JobConf job , String name , final Progressable progress ) throws IOException { final Path perm = new Path ( getWorkOutputPath ( job ) , name ) ; return new RecordWriter < Shard , Text > ( ) { public void write ( Shard key , Text value ) throws IOException { assert ( DONE . equals ( value ) ) ; String shardName = key . getDirectory ( ) ; shardName = shardName . replace ( "<STR_LIT:/>" , "<STR_LIT:_>" ) ; Path doneFile = new Path ( perm , DONE + "<STR_LIT:_>" + shardName ) ; if ( ! fs . exists ( doneFile ) ) { fs . createNewFile ( doneFile ) ; } } public void close ( final Reporter reporter ) throws IOException { } } ; } } </s>
<s> package com . senseidb . indexing . hadoop . reduce ; import java . io . File ; import java . io . IOException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . fs . Trash ; import org . apache . log4j . Logger ; import org . apache . lucene . index . CorruptIndexException ; import org . apache . lucene . index . IndexWriter ; import org . apache . lucene . index . IndexWriter . MaxFieldLength ; import org . apache . lucene . index . KeepOnlyLastCommitDeletionPolicy ; import org . apache . lucene . store . Directory ; import org . apache . lucene . store . FSDirectory ; import com . senseidb . indexing . hadoop . keyvalueformat . IntermediateForm ; import com . senseidb . indexing . hadoop . keyvalueformat . Shard ; import com . senseidb . indexing . hadoop . util . LuceneIndexFileNameFilter ; import com . senseidb . indexing . hadoop . util . SenseiJobConfig ; public class ShardWriter { private static Logger logger = Logger . getLogger ( ShardWriter . class ) ; private final FileSystem fs ; private final FileSystem localFs ; private final Path perm ; private final Path temp ; private final IndexWriter writer ; private int maxNumSegments ; private long numForms = <NUM_LIT:0> ; private Configuration iconf ; public ShardWriter ( FileSystem fs , Shard shard , String tempDir , Configuration iconf ) throws IOException { logger . info ( "<STR_LIT>" ) ; this . iconf = iconf ; this . fs = fs ; localFs = FileSystem . getLocal ( iconf ) ; perm = new Path ( shard . getDirectory ( ) ) ; temp = new Path ( tempDir ) ; long initGeneration = shard . getGeneration ( ) ; if ( localFs . exists ( temp ) ) { File tempFile = new File ( temp . getName ( ) ) ; if ( tempFile . exists ( ) ) SenseiReducer . deleteDir ( tempFile ) ; } if ( ! fs . exists ( perm ) ) { assert ( initGeneration < <NUM_LIT:0> ) ; fs . mkdirs ( perm ) ; } else { moveToTrash ( iconf , perm ) ; fs . mkdirs ( perm ) ; } writer = new IndexWriter ( FSDirectory . open ( new File ( tempDir ) ) , null , new KeepOnlyLastCommitDeletionPolicy ( ) , MaxFieldLength . UNLIMITED ) ; setParameters ( iconf ) ; } public void process ( IntermediateForm form ) throws IOException { writer . addIndexesNoOptimize ( new Directory [ ] { form . getDirectory ( ) } ) ; numForms ++ ; } public void close ( ) throws IOException { logger . info ( "<STR_LIT>" + numForms + "<STR_LIT>" ) ; try { try { if ( maxNumSegments > <NUM_LIT:0> ) { writer . optimize ( maxNumSegments ) ; logger . info ( "<STR_LIT>" + maxNumSegments + "<STR_LIT>" ) ; } } finally { writer . close ( ) ; logger . info ( "<STR_LIT>" ) ; } moveFromTempToPerm ( ) ; logger . info ( "<STR_LIT>" + perm ) ; } finally { logger . info ( "<STR_LIT>" ) ; } } public String toString ( ) { return this . getClass ( ) . getName ( ) + "<STR_LIT:@>" + perm + "<STR_LIT:&>" + temp ; } private void setParameters ( Configuration conf ) { int maxFieldLength = conf . getInt ( SenseiJobConfig . MAX_FIELD_LENGTH , - <NUM_LIT:1> ) ; if ( maxFieldLength > <NUM_LIT:0> ) { writer . setMaxFieldLength ( maxFieldLength ) ; } writer . setUseCompoundFile ( conf . getBoolean ( SenseiJobConfig . USE_COMPOUND_FILE , false ) ) ; maxNumSegments = conf . getInt ( SenseiJobConfig . MAX_NUM_SEGMENTS , - <NUM_LIT:1> ) ; if ( maxFieldLength > <NUM_LIT:0> ) { logger . info ( SenseiJobConfig . MAX_FIELD_LENGTH + "<STR_LIT:U+0020=U+0020>" + writer . getMaxFieldLength ( ) ) ; } logger . info ( SenseiJobConfig . USE_COMPOUND_FILE + "<STR_LIT:U+0020=U+0020>" + writer . getUseCompoundFile ( ) ) ; logger . info ( SenseiJobConfig . MAX_NUM_SEGMENTS + "<STR_LIT:U+0020=U+0020>" + maxNumSegments ) ; } private void moveFromTempToPerm ( ) throws IOException { FileStatus [ ] fileStatus = localFs . listStatus ( temp , LuceneIndexFileNameFilter . getFilter ( ) ) ; for ( int i = <NUM_LIT:0> ; i < fileStatus . length ; i ++ ) { Path path = fileStatus [ i ] . getPath ( ) ; String name = path . getName ( ) ; try { if ( ! fs . exists ( new Path ( perm , name ) ) ) { fs . copyFromLocalFile ( path , new Path ( perm , name ) ) ; } else { moveToTrash ( iconf , perm ) ; fs . copyFromLocalFile ( path , new Path ( perm , name ) ) ; } } catch ( Exception e ) { ; } } } public void optimize ( ) { try { writer . optimize ( ) ; } catch ( CorruptIndexException e ) { logger . error ( "<STR_LIT>" , e ) ; } catch ( IOException e ) { logger . error ( "<STR_LIT>" , e ) ; } } public static void moveToTrash ( Configuration conf , Path path ) throws IOException { Trash t = new Trash ( conf ) ; boolean isMoved = t . moveToTrash ( path ) ; t . expunge ( ) ; if ( ! isMoved ) { logger . error ( "<STR_LIT>" ) ; } } } </s>
<s> package com . senseidb . indexing . hadoop . map ; import java . io . File ; import java . io . IOException ; import java . lang . reflect . Constructor ; import java . net . URL ; import java . net . URLConnection ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import org . apache . commons . configuration . ConfigurationException ; import org . apache . commons . lang . exception . ExceptionUtils ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . filecache . DistributedCache ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . mapred . JobConf ; import org . apache . hadoop . mapred . MapReduceBase ; import org . apache . hadoop . mapred . Mapper ; import org . apache . hadoop . mapred . OutputCollector ; import org . apache . hadoop . mapred . Reporter ; import org . apache . hadoop . util . ReflectionUtils ; import org . apache . log4j . Logger ; import org . apache . lucene . analysis . Analyzer ; import org . apache . lucene . analysis . standard . StandardAnalyzer ; import org . apache . lucene . document . Document ; import org . apache . lucene . document . Field ; import org . apache . lucene . util . Version ; import org . json . JSONException ; import org . json . JSONObject ; import proj . zoie . api . ZoieSegmentReader ; import proj . zoie . api . indexing . AbstractZoieIndexable ; import proj . zoie . api . indexing . ZoieIndexable ; import proj . zoie . api . indexing . ZoieIndexable . IndexingReq ; import com . senseidb . conf . SchemaConverter ; import com . senseidb . conf . SenseiSchema ; import com . senseidb . indexing . DefaultJsonSchemaInterpreter ; import com . senseidb . indexing . JsonFilter ; import com . senseidb . indexing . ShardingStrategy ; import com . senseidb . indexing . hadoop . keyvalueformat . IntermediateForm ; import com . senseidb . indexing . hadoop . keyvalueformat . Shard ; import com . senseidb . indexing . hadoop . util . SenseiJobConfig ; public class SenseiMapper extends MapReduceBase implements Mapper < Object , Object , Shard , IntermediateForm > { private final static Logger logger = Logger . getLogger ( SenseiMapper . class ) ; private static DefaultJsonSchemaInterpreter _defaultInterpreter = null ; private boolean _use_remote_schema = false ; private volatile boolean _isConfigured = false ; private Configuration _conf ; private Shard [ ] _shards ; private ShardingStrategy _shardingStategy ; private MapInputConverter _converter ; private static Analyzer analyzer ; public void map ( Object key , Object value , OutputCollector < Shard , IntermediateForm > output , Reporter reporter ) throws IOException { if ( _isConfigured == false ) throw new IllegalStateException ( "<STR_LIT>" ) ; JSONObject json = null ; try { json = _converter . getJsonInput ( key , value , _conf ) ; json = _converter . doFilter ( json ) ; } catch ( Exception e ) { ExceptionUtils . printRootCauseStackTrace ( e ) ; throw new IllegalStateException ( "<STR_LIT>" ) ; } if ( _defaultInterpreter == null ) reporter . incrCounter ( "<STR_LIT>" , "<STR_LIT>" , <NUM_LIT:1> ) ; if ( _defaultInterpreter != null && json != null && analyzer != null ) { ZoieIndexable indexable = _defaultInterpreter . convertAndInterpret ( json ) ; IndexingReq [ ] idxReqs = indexable . buildIndexingReqs ( ) ; if ( idxReqs . length > <NUM_LIT:0> ) { Document doc = idxReqs [ <NUM_LIT:0> ] . getDocument ( ) ; ZoieSegmentReader . fillDocumentID ( doc , indexable . getUID ( ) ) ; if ( indexable . isStorable ( ) ) { byte [ ] bytes = indexable . getStoreValue ( ) ; if ( bytes != null ) { doc . add ( new Field ( AbstractZoieIndexable . DOCUMENT_STORE_FIELD , bytes ) ) ; } } IntermediateForm form = new IntermediateForm ( ) ; form . configure ( _conf ) ; form . process ( doc , analyzer ) ; form . closeWriter ( ) ; int chosenShard = - <NUM_LIT:1> ; try { chosenShard = _shardingStategy . caculateShard ( _shards . length , json ) ; } catch ( JSONException e ) { throw new IOException ( "<STR_LIT>" ) ; } if ( chosenShard >= <NUM_LIT:0> ) { output . collect ( _shards [ chosenShard ] , form ) ; } else { throw new IOException ( "<STR_LIT>" + chosenShard ) ; } } } } @ Override public void configure ( JobConf job ) { super . configure ( job ) ; _conf = job ; _shards = Shard . getIndexShards ( _conf ) ; _shardingStategy = ( ShardingStrategy ) ReflectionUtils . newInstance ( job . getClass ( SenseiJobConfig . DISTRIBUTION_POLICY , DummyShardingStrategy . class , ShardingStrategy . class ) , job ) ; _converter = ( MapInputConverter ) ReflectionUtils . newInstance ( job . getClass ( SenseiJobConfig . MAPINPUT_CONVERTER , DummyMapInputConverter . class , MapInputConverter . class ) , job ) ; try { setSchema ( job ) ; setAnalyzer ( job ) ; _isConfigured = true ; } catch ( Exception e ) { e . printStackTrace ( ) ; _isConfigured = false ; } } private void setAnalyzer ( JobConf conf ) throws Exception { if ( analyzer != null ) return ; String version = _conf . get ( SenseiJobConfig . DOCUMENT_ANALYZER_VERSION ) ; if ( version == null ) throw new IllegalStateException ( "<STR_LIT>" ) ; String analyzerName = _conf . get ( SenseiJobConfig . DOCUMENT_ANALYZER ) ; if ( analyzerName == null ) throw new IllegalStateException ( "<STR_LIT>" ) ; Class analyzerClass = Class . forName ( analyzerName ) ; Constructor constructor = analyzerClass . getConstructor ( Version . class ) ; analyzer = ( Analyzer ) constructor . newInstance ( ( Version ) Enum . valueOf ( ( Class ) Class . forName ( "<STR_LIT>" ) , version ) ) ; } private void setSchema ( JobConf conf ) throws Exception { String _schema_uri = null ; String metadataFileName = conf . get ( SenseiJobConfig . SCHEMA_FILE_URL ) ; Path [ ] localFiles = DistributedCache . getLocalCacheFiles ( conf ) ; if ( localFiles != null ) { for ( int i = <NUM_LIT:0> ; i < localFiles . length ; i ++ ) { String strFileName = localFiles [ i ] . toString ( ) ; if ( strFileName . contains ( conf . get ( SenseiJobConfig . SCHEMA_FILE_URL ) ) ) { metadataFileName = strFileName ; break ; } } } if ( metadataFileName != null && metadataFileName . length ( ) > <NUM_LIT:0> ) { _schema_uri = "<STR_LIT>" + metadataFileName ; if ( _defaultInterpreter == null ) { logger . info ( "<STR_LIT>" + _schema_uri ) ; URL url = new URL ( _schema_uri ) ; URLConnection conn = url . openConnection ( ) ; conn . connect ( ) ; File xmlSchema = new File ( url . toURI ( ) ) ; if ( ! xmlSchema . exists ( ) ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setIgnoringComments ( true ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; org . w3c . dom . Document schemaXml = db . parse ( xmlSchema ) ; schemaXml . getDocumentElement ( ) . normalize ( ) ; JSONObject schemaData = SchemaConverter . convert ( schemaXml ) ; SenseiSchema schema = SenseiSchema . build ( schemaData ) ; _defaultInterpreter = new DefaultJsonSchemaInterpreter ( schema ) ; } } } } </s>
<s> package com . senseidb . indexing . hadoop . map ; import org . apache . hadoop . conf . Configuration ; import org . json . JSONException ; import org . json . JSONObject ; import com . senseidb . indexing . JsonFilter ; public abstract class MapInputConverter extends JsonFilter { public abstract JSONObject getJsonInput ( Object key , Object value , Configuration conf ) throws JSONException ; @ Override protected abstract JSONObject doFilter ( JSONObject data ) throws Exception ; } </s>
<s> package com . senseidb . indexing . hadoop . map ; import org . json . JSONException ; import org . json . JSONObject ; import com . senseidb . indexing . ShardingStrategy ; public class DummyShardingStrategy implements ShardingStrategy { @ Override public int caculateShard ( int maxShardId , JSONObject dataObj ) throws JSONException { return dataObj . toString ( ) . length ( ) % maxShardId ; } } </s>
<s> package com . senseidb . indexing . hadoop . map ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . Text ; import org . json . JSONException ; import org . json . JSONObject ; public class DummyMapInputConverter extends MapInputConverter { @ Override public JSONObject getJsonInput ( Object key , Object value , Configuration conf ) throws JSONException { String line = ( ( Text ) value ) . toString ( ) ; return new JSONObject ( line ) ; } @ Override protected JSONObject doFilter ( JSONObject data ) throws Exception { return data ; } } </s>
<s> package com . senseidb . indexing . hadoop . util ; public interface SenseiJobConfig { public static final String NUM_SHARDS = "<STR_LIT>" ; public static final String INDEX_PATH = "<STR_LIT>" ; public static final String USE_COMPOUND_FILE = "<STR_LIT>" ; public static final String INPUT_FORMAT = "<STR_LIT>" ; public static final String INDEX_SHARDS = "<STR_LIT>" ; public static final String MAX_FIELD_LENGTH = "<STR_LIT>" ; public static final String DISTRIBUTION_POLICY = "<STR_LIT>" ; public static final String MAPINPUT_CONVERTER = "<STR_LIT>" ; public static final String DOCUMENT_ANALYZER_VERSION = "<STR_LIT>" ; public static final String DOCUMENT_ANALYZER = "<STR_LIT>" ; public static final String MAX_RAMSIZE_BYTES = "<STR_LIT>" ; public static final String MAX_NUM_SEGMENTS = "<STR_LIT>" ; public static final String SCHEMA_FILE_URL = "<STR_LIT>" ; public static final String FORCE_OUTPUT_OVERWRITE = "<STR_LIT>" ; public static final String INPUT_DIRS = "<STR_LIT>" ; public static final String OUTPUT_DIR = "<STR_LIT>" ; public static final String INDEX_SUBDIR_PREFIX = "<STR_LIT>" ; } </s>
<s> package com . senseidb . indexing . hadoop . util ; import java . io . IOException ; import org . apache . lucene . store . Directory ; public final class LuceneUtil { static public final class IndexFileNames { static public final String SEGMENTS = "<STR_LIT>" ; static public final String SEGMENTS_GEN = "<STR_LIT>" ; } public static boolean isSegmentsFile ( String name ) { return name . startsWith ( IndexFileNames . SEGMENTS ) && ! name . equals ( IndexFileNames . SEGMENTS_GEN ) ; } public static boolean isSegmentsGenFile ( String name ) { return name . equals ( IndexFileNames . SEGMENTS_GEN ) ; } public static long getCurrentSegmentGeneration ( Directory directory ) throws IOException { String [ ] files = directory . listAll ( ) ; if ( files == null ) throw new IOException ( "<STR_LIT>" + directory + "<STR_LIT>" ) ; return getCurrentSegmentGeneration ( files ) ; } public static long getCurrentSegmentGeneration ( String [ ] files ) { if ( files == null ) { return - <NUM_LIT:1> ; } long max = - <NUM_LIT:1> ; for ( int i = <NUM_LIT:0> ; i < files . length ; i ++ ) { String file = files [ i ] ; if ( file . startsWith ( IndexFileNames . SEGMENTS ) && ! file . equals ( IndexFileNames . SEGMENTS_GEN ) ) { long gen = generationFromSegmentsFileName ( file ) ; if ( gen > max ) { max = gen ; } } } return max ; } public static long generationFromSegmentsFileName ( String fileName ) { if ( fileName . equals ( IndexFileNames . SEGMENTS ) ) { return <NUM_LIT:0> ; } else if ( fileName . startsWith ( IndexFileNames . SEGMENTS ) ) { return Long . parseLong ( fileName . substring ( <NUM_LIT:1> + IndexFileNames . SEGMENTS . length ( ) ) , Character . MAX_RADIX ) ; } else { throw new IllegalArgumentException ( "<STR_LIT>" + fileName + "<STR_LIT>" ) ; } } } </s>
<s> package com . senseidb . indexing . hadoop . util ; public interface MRJobConfig { public static final String INPUT_FORMAT_CLASS_ATTR = "<STR_LIT>" ; public static final String MAP_CLASS_ATTR = "<STR_LIT>" ; public static final String COMBINE_CLASS_ATTR = "<STR_LIT>" ; public static final String REDUCE_CLASS_ATTR = "<STR_LIT>" ; public static final String OUTPUT_FORMAT_CLASS_ATTR = "<STR_LIT>" ; public static final String PARTITIONER_CLASS_ATTR = "<STR_LIT>" ; public static final String SETUP_CLEANUP_NEEDED = "<STR_LIT>" ; public static final String TASK_CLEANUP_NEEDED = "<STR_LIT>" ; public static final String JAR = "<STR_LIT>" ; public static final String ID = "<STR_LIT>" ; public static final String JOB_NAME = "<STR_LIT>" ; public static final String JAR_UNPACK_PATTERN = "<STR_LIT>" ; public static final String USER_NAME = "<STR_LIT>" ; public static final String PRIORITY = "<STR_LIT>" ; public static final String QUEUE_NAME = "<STR_LIT>" ; public static final String JVM_NUMTASKS_TORUN = "<STR_LIT>" ; public static final String SPLIT_FILE = "<STR_LIT>" ; public static final String NUM_MAPS = "<STR_LIT>" ; public static final String MAX_TASK_FAILURES_PER_TRACKER = "<STR_LIT>" ; public static final String COMPLETED_MAPS_FOR_REDUCE_SLOWSTART = "<STR_LIT>" ; public static final String NUM_REDUCES = "<STR_LIT>" ; public static final String SKIP_RECORDS = "<STR_LIT>" ; public static final String SKIP_OUTDIR = "<STR_LIT>" ; public static final String SPECULATIVE_SLOWNODE_THRESHOLD = "<STR_LIT>" ; public static final String SPECULATIVE_SLOWTASK_THRESHOLD = "<STR_LIT>" ; public static final String SPECULATIVECAP = "<STR_LIT>" ; public static final String JOB_LOCAL_DIR = "<STR_LIT>" ; public static final String OUTPUT_KEY_CLASS = "<STR_LIT>" ; public static final String OUTPUT_VALUE_CLASS = "<STR_LIT>" ; public static final String KEY_COMPARATOR = "<STR_LIT>" ; public static final String GROUP_COMPARATOR_CLASS = "<STR_LIT>" ; public static final String WORKING_DIR = "<STR_LIT>" ; public static final String END_NOTIFICATION_URL = "<STR_LIT>" ; public static final String END_NOTIFICATION_RETRIES = "<STR_LIT>" ; public static final String END_NOTIFICATION_RETRIE_INTERVAL = "<STR_LIT>" ; public static final String CLASSPATH_ARCHIVES = "<STR_LIT>" ; public static final String CLASSPATH_FILES = "<STR_LIT>" ; public static final String CACHE_FILES = "<STR_LIT>" ; public static final String CACHE_ARCHIVES = "<STR_LIT>" ; public static final String CACHE_FILES_SIZES = "<STR_LIT>" ; public static final String CACHE_ARCHIVES_SIZES = "<STR_LIT>" ; public static final String CACHE_LOCALFILES = "<STR_LIT>" ; public static final String CACHE_LOCALARCHIVES = "<STR_LIT>" ; public static final String CACHE_FILE_TIMESTAMPS = "<STR_LIT>" ; public static final String CACHE_ARCHIVES_TIMESTAMPS = "<STR_LIT>" ; public static final String CACHE_FILE_VISIBILITIES = "<STR_LIT>" ; public static final String CACHE_ARCHIVES_VISIBILITIES = "<STR_LIT>" ; public static final String CACHE_SYMLINK = "<STR_LIT>" ; public static final String USER_LOG_RETAIN_HOURS = "<STR_LIT>" ; public static final String IO_SORT_FACTOR = "<STR_LIT>" ; public static final String IO_SORT_MB = "<STR_LIT>" ; public static final String INDEX_CACHE_MEMORY_LIMIT = "<STR_LIT>" ; public static final String PRESERVE_FAILED_TASK_FILES = "<STR_LIT>" ; public static final String PRESERVE_FILES_PATTERN = "<STR_LIT>" ; public static final String TASK_TEMP_DIR = "<STR_LIT>" ; public static final String TASK_DEBUGOUT_LINES = "<STR_LIT>" ; public static final String RECORDS_BEFORE_PROGRESS = "<STR_LIT>" ; public static final String SKIP_START_ATTEMPTS = "<STR_LIT>" ; public static final String TASK_ATTEMPT_ID = "<STR_LIT>" ; public static final String TASK_ISMAP = "<STR_LIT>" ; public static final String TASK_PARTITION = "<STR_LIT>" ; public static final String TASK_PROFILE = "<STR_LIT>" ; public static final String TASK_PROFILE_PARAMS = "<STR_LIT>" ; public static final String NUM_MAP_PROFILES = "<STR_LIT>" ; public static final String NUM_REDUCE_PROFILES = "<STR_LIT>" ; public static final String TASK_TIMEOUT = "<STR_LIT>" ; public static final String TASK_ID = "<STR_LIT>" ; public static final String TASK_OUTPUT_DIR = "<STR_LIT>" ; public static final String TASK_USERLOG_LIMIT = "<STR_LIT>" ; public static final String MAP_SORT_SPILL_PERCENT = "<STR_LIT>" ; public static final String MAP_INPUT_FILE = "<STR_LIT>" ; public static final String MAP_INPUT_PATH = "<STR_LIT>" ; public static final String MAP_INPUT_START = "<STR_LIT>" ; public static final String MAP_MEMORY_MB = "<STR_LIT>" ; public static final String MAP_MEMORY_PHYSICAL_MB = "<STR_LIT>" ; public static final String MAP_ENV = "<STR_LIT>" ; public static final String MAP_JAVA_OPTS = "<STR_LIT>" ; public static final String MAP_ULIMIT = "<STR_LIT>" ; public static final String MAP_MAX_ATTEMPTS = "<STR_LIT>" ; public static final String MAP_DEBUG_SCRIPT = "<STR_LIT>" ; public static final String MAP_SPECULATIVE = "<STR_LIT>" ; public static final String MAP_FAILURES_MAX_PERCENT = "<STR_LIT>" ; public static final String MAP_SKIP_INCR_PROC_COUNT = "<STR_LIT>" ; public static final String MAP_SKIP_MAX_RECORDS = "<STR_LIT>" ; public static final String MAP_COMBINE_MIN_SPILLS = "<STR_LIT>" ; public static final String MAP_OUTPUT_COMPRESS = "<STR_LIT>" ; public static final String MAP_OUTPUT_COMPRESS_CODEC = "<STR_LIT>" ; public static final String MAP_OUTPUT_KEY_CLASS = "<STR_LIT>" ; public static final String MAP_OUTPUT_VALUE_CLASS = "<STR_LIT>" ; public static final String MAP_OUTPUT_KEY_FIELD_SEPERATOR = "<STR_LIT>" ; public static final String MAP_LOG_LEVEL = "<STR_LIT>" ; public static final String REDUCE_LOG_LEVEL = "<STR_LIT>" ; public static final String REDUCE_MERGE_INMEM_THRESHOLD = "<STR_LIT>" ; public static final String REDUCE_INPUT_BUFFER_PERCENT = "<STR_LIT>" ; public static final String REDUCE_MARKRESET_BUFFER_PERCENT = "<STR_LIT>" ; public static final String REDUCE_MARKRESET_BUFFER_SIZE = "<STR_LIT>" ; public static final String REDUCE_MEMORY_PHYSICAL_MB = "<STR_LIT>" ; public static final String REDUCE_MEMORY_MB = "<STR_LIT>" ; public static final String REDUCE_MEMORY_TOTAL_BYTES = "<STR_LIT>" ; public static final String SHUFFLE_INPUT_BUFFER_PERCENT = "<STR_LIT>" ; public static final String SHUFFLE_MERGE_EPRCENT = "<STR_LIT>" ; public static final String REDUCE_FAILURES_MAXPERCENT = "<STR_LIT>" ; public static final String REDUCE_ENV = "<STR_LIT>" ; public static final String REDUCE_JAVA_OPTS = "<STR_LIT>" ; public static final String REDUCE_ULIMIT = "<STR_LIT>" ; public static final String REDUCE_MAX_ATTEMPTS = "<STR_LIT>" ; public static final String SHUFFLE_PARALLEL_COPIES = "<STR_LIT>" ; public static final String REDUCE_DEBUG_SCRIPT = "<STR_LIT>" ; public static final String REDUCE_SPECULATIVE = "<STR_LIT>" ; public static final String SHUFFLE_CONNECT_TIMEOUT = "<STR_LIT>" ; public static final String SHUFFLE_READ_TIMEOUT = "<STR_LIT>" ; public static final String SHUFFLE_FETCH_FAILURES = "<STR_LIT>" ; public static final String SHUFFLE_NOTIFY_READERROR = "<STR_LIT>" ; public static final String REDUCE_SKIP_INCR_PROC_COUNT = "<STR_LIT>" ; public static final String REDUCE_SKIP_MAXGROUPS = "<STR_LIT>" ; public static final String REDUCE_MEMTOMEM_THRESHOLD = "<STR_LIT>" ; public static final String REDUCE_MEMTOMEM_ENABLED = "<STR_LIT>" ; public static final String COMBINE_RECORDS_BEFORE_PROGRESS = "<STR_LIT>" ; public static final String JOB_NAMENODES = "<STR_LIT>" ; public static final String JOB_JOBTRACKER_ID = "<STR_LIT>" ; public static final String JOB_CANCEL_DELEGATION_TOKEN = "<STR_LIT>" ; public static final String JOB_ACL_VIEW_JOB = "<STR_LIT>" ; public static final String JOB_ACL_MODIFY_JOB = "<STR_LIT>" ; public static final String JOB_SUBMITHOST = "<STR_LIT>" ; public static final String JOB_SUBMITHOSTADDR = "<STR_LIT>" ; public static final String COUNTERS_MAX_KEY = "<STR_LIT>" ; public static final int COUNTERS_MAX_DEFAULT = <NUM_LIT> ; public static final String COUNTER_GROUP_NAME_MAX_KEY = "<STR_LIT>" ; public static final int COUNTER_GROUP_NAME_MAX_DEFAULT = <NUM_LIT> ; public static final String COUNTER_NAME_MAX_KEY = "<STR_LIT>" ; public static final int COUNTER_NAME_MAX_DEFAULT = <NUM_LIT> ; public static final String COUNTER_GROUPS_MAX_KEY = "<STR_LIT>" ; public static final int COUNTER_GROUPS_MAX_DEFAULT = <NUM_LIT> ; } </s>
<s> package com . senseidb . indexing . hadoop . util ; public interface MRConfig { public static final String TEMP_DIR = "<STR_LIT>" ; public static final String LOCAL_DIR = "<STR_LIT>" ; public static final String MAPMEMORY_MB = "<STR_LIT>" ; public static final String REDUCEMEMORY_MB = "<STR_LIT>" ; public static final String MR_ACLS_ENABLED = "<STR_LIT>" ; public static final String MR_ADMINS = "<STR_LIT>" ; @ Deprecated public static final String MR_SUPERGROUP = "<STR_LIT>" ; public static final String DELEGATION_KEY_UPDATE_INTERVAL_KEY = "<STR_LIT>" ; public static final long DELEGATION_KEY_UPDATE_INTERVAL_DEFAULT = <NUM_LIT:24> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:1000> ; public static final String DELEGATION_TOKEN_RENEW_INTERVAL_KEY = "<STR_LIT>" ; public static final long DELEGATION_TOKEN_RENEW_INTERVAL_DEFAULT = <NUM_LIT:24> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:1000> ; public static final String DELEGATION_TOKEN_MAX_LIFETIME_KEY = "<STR_LIT>" ; public static final long DELEGATION_TOKEN_MAX_LIFETIME_DEFAULT = <NUM_LIT:7> * <NUM_LIT:24> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT:1000> ; public static final String FRAMEWORK_NAME = "<STR_LIT>" ; public static final String TASK_LOCAL_OUTPUT_CLASS = "<STR_LIT>" ; } </s>
<s> package com . senseidb . indexing . hadoop . util ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStream ; import java . util . Map . Entry ; import java . util . Properties ; import org . apache . hadoop . conf . Configuration ; public class PropertiesLoader { public static void loadProperties ( Configuration conf , Properties properties ) { for ( Entry < Object , Object > entry : properties . entrySet ( ) ) { String key = ( String ) entry . getKey ( ) ; Object v = entry . getValue ( ) ; if ( v instanceof String ) conf . set ( key , ( String ) v ) ; else if ( v instanceof Boolean ) conf . setBoolean ( key , ( Boolean ) v ) ; else if ( v instanceof Float ) conf . setFloat ( key , ( Float ) v ) ; else if ( v instanceof Integer ) conf . setInt ( key , ( Integer ) v ) ; else if ( v instanceof Long ) conf . setLong ( key , ( Long ) v ) ; } } public static Configuration loadProperties ( String path ) throws IOException { InputStream inputStream = new BufferedInputStream ( new FileInputStream ( new File ( path ) . getAbsolutePath ( ) ) ) ; Properties properties = new Properties ( ) ; properties . load ( inputStream ) ; Configuration conf = new Configuration ( ) ; loadProperties ( conf , properties ) ; return conf ; } } </s>
<s> package com . senseidb . indexing . hadoop . util ; import org . apache . hadoop . fs . Path ; import org . apache . hadoop . fs . PathFilter ; import org . apache . lucene . index . IndexFileNameFilter ; public class LuceneIndexFileNameFilter implements PathFilter { private static final LuceneIndexFileNameFilter singleton = new LuceneIndexFileNameFilter ( ) ; public static LuceneIndexFileNameFilter getFilter ( ) { return singleton ; } private final IndexFileNameFilter luceneFilter ; private LuceneIndexFileNameFilter ( ) { luceneFilter = IndexFileNameFilter . getFilter ( ) ; } public boolean accept ( Path path ) { return luceneFilter . accept ( null , path . getName ( ) ) ; } } </s>
<s> package com . senseidb . indexing . hadoop . keyvalueformat ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . StringTokenizer ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . Text ; import org . apache . hadoop . io . WritableComparable ; import com . senseidb . indexing . hadoop . util . SenseiJobConfig ; public class Shard implements WritableComparable { public static String normalizePath ( String path ) { path = path . replace ( "<STR_LIT>" , "<STR_LIT:/>" ) ; path = path . replace ( "<STR_LIT:\\>" , "<STR_LIT:/>" ) ; if ( path . length ( ) > <NUM_LIT:1> && path . endsWith ( "<STR_LIT:/>" ) ) { path = path . substring ( <NUM_LIT:0> , path . length ( ) - <NUM_LIT:1> ) ; } return path ; } public static void setIndexShards ( Configuration conf , Shard [ ] shards ) { StringBuilder shardsString = new StringBuilder ( shards [ <NUM_LIT:0> ] . toString ( ) ) ; for ( int i = <NUM_LIT:1> ; i < shards . length ; i ++ ) { shardsString . append ( "<STR_LIT:U+002C>" ) ; shardsString . append ( shards [ i ] . toString ( ) ) ; } conf . set ( SenseiJobConfig . INDEX_SHARDS , shardsString . toString ( ) ) ; } public static Shard [ ] getIndexShards ( Configuration conf ) { String shards = conf . get ( SenseiJobConfig . INDEX_SHARDS ) ; if ( shards != null ) { ArrayList < Object > list = Collections . list ( new StringTokenizer ( shards , "<STR_LIT:U+002C>" ) ) ; Shard [ ] result = new Shard [ list . size ( ) ] ; for ( int i = <NUM_LIT:0> ; i < list . size ( ) ; i ++ ) { result [ i ] = Shard . createShardFromString ( ( String ) list . get ( i ) ) ; } return result ; } else { return null ; } } private static Shard createShardFromString ( String str ) { int first = str . indexOf ( "<STR_LIT:@>" ) ; int second = str . indexOf ( "<STR_LIT:@>" , first + <NUM_LIT:1> ) ; long version = Long . parseLong ( str . substring ( <NUM_LIT:0> , first ) ) ; String dir = str . substring ( first + <NUM_LIT:1> , second ) ; long gen = Long . parseLong ( str . substring ( second + <NUM_LIT:1> ) ) ; return new Shard ( version , dir , gen ) ; } private long version ; private String dir ; private long gen ; public Shard ( ) { this . version = - <NUM_LIT:1> ; this . dir = null ; this . gen = - <NUM_LIT:1> ; } public Shard ( long version , String dir , long gen ) { this . version = version ; this . dir = normalizePath ( dir ) ; this . gen = gen ; } public Shard ( Shard shard ) { this . version = shard . version ; this . dir = shard . dir ; this . gen = shard . gen ; } public long getVersion ( ) { return version ; } public String getDirectory ( ) { return dir ; } public long getGeneration ( ) { return gen ; } public String toString ( ) { return version + "<STR_LIT:@>" + dir + "<STR_LIT:@>" + gen ; } public String toFlatString ( ) { String dirPath = dir . replace ( "<STR_LIT:/>" , "<STR_LIT:_>" ) ; String flatString = version + "<STR_LIT:_>" + dirPath + "<STR_LIT:_>" + gen ; flatString = flatString . replace ( "<STR_LIT:@>" , "<STR_LIT:_>" ) ; return flatString ; } public void write ( DataOutput out ) throws IOException { out . writeLong ( version ) ; Text . writeString ( out , dir ) ; out . writeLong ( gen ) ; } public void readFields ( DataInput in ) throws IOException { version = in . readLong ( ) ; dir = Text . readString ( in ) ; gen = in . readLong ( ) ; } public int compareTo ( Object o ) { return compareTo ( ( Shard ) o ) ; } public int compareTo ( Shard other ) { if ( version < other . version ) { return - <NUM_LIT:1> ; } else if ( version > other . version ) { return <NUM_LIT:1> ; } int result = dir . compareTo ( other . dir ) ; if ( result != <NUM_LIT:0> ) { return result ; } if ( gen < other . gen ) { return - <NUM_LIT:1> ; } else if ( gen == other . gen ) { return <NUM_LIT:0> ; } else { return <NUM_LIT:1> ; } } public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( ! ( o instanceof Shard ) ) { return false ; } Shard other = ( Shard ) o ; return version == other . version && dir . equals ( other . dir ) && gen == other . gen ; } public int hashCode ( ) { return ( int ) version ^ dir . hashCode ( ) ^ ( int ) gen ; } } </s>
<s> package com . senseidb . indexing . hadoop . keyvalueformat ; import java . io . DataInput ; import java . io . DataOutput ; import java . io . IOException ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . io . Writable ; import org . apache . lucene . analysis . Analyzer ; import org . apache . lucene . document . Document ; import org . apache . lucene . index . IndexWriter ; import org . apache . lucene . index . IndexWriter . MaxFieldLength ; import org . apache . lucene . index . KeepOnlyLastCommitDeletionPolicy ; import org . apache . lucene . store . Directory ; import org . apache . lucene . store . RAMDirectory ; import org . apache . lucene . store . RAMDirectorySerializer ; import com . senseidb . indexing . hadoop . reduce . RAMDirectoryUtil ; import com . senseidb . indexing . hadoop . util . SenseiJobConfig ; public class IntermediateForm implements Writable { private Configuration conf = null ; private RAMDirectory dir ; private IndexWriter writer ; private int numDocs ; public IntermediateForm ( ) throws IOException { dir = new RAMDirectory ( ) ; writer = null ; numDocs = <NUM_LIT:0> ; } public void configure ( Configuration iconf ) { this . conf = iconf ; } public Directory getDirectory ( ) { return dir ; } public void process ( Document doc , Analyzer analyzer ) throws IOException { if ( writer == null ) { writer = createWriter ( ) ; } writer . addDocument ( doc , analyzer ) ; numDocs ++ ; } public void process ( IntermediateForm form ) throws IOException { if ( form . dir . sizeInBytes ( ) > <NUM_LIT:0> ) { if ( writer == null ) { writer = createWriter ( ) ; } writer . addIndexesNoOptimize ( new Directory [ ] { form . dir } ) ; numDocs ++ ; } } public void closeWriter ( ) throws IOException { if ( writer != null ) { writer . optimize ( ) ; writer . close ( ) ; writer = null ; } } public long totalSizeInBytes ( ) throws IOException { long size = dir . sizeInBytes ( ) ; if ( writer != null ) { size += writer . ramSizeInBytes ( ) ; } return size ; } public String toString ( ) { StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( this . getClass ( ) . getSimpleName ( ) ) ; buffer . append ( "<STR_LIT>" ) ; buffer . append ( numDocs ) ; buffer . append ( "<STR_LIT>" ) ; buffer . append ( "<STR_LIT:]>" ) ; return buffer . toString ( ) ; } private IndexWriter createWriter ( ) throws IOException { IndexWriter writer = new IndexWriter ( dir , null , new KeepOnlyLastCommitDeletionPolicy ( ) , MaxFieldLength . UNLIMITED ) ; writer . setUseCompoundFile ( true ) ; if ( conf != null ) { int maxFieldLength = conf . getInt ( SenseiJobConfig . MAX_FIELD_LENGTH , - <NUM_LIT:1> ) ; if ( maxFieldLength > <NUM_LIT:0> ) { writer . setMaxFieldLength ( maxFieldLength ) ; } } return writer ; } private void resetForm ( ) throws IOException { if ( dir . sizeInBytes ( ) > <NUM_LIT:0> ) { dir . close ( ) ; dir = new RAMDirectory ( ) ; } assert ( writer == null ) ; numDocs = <NUM_LIT:0> ; } public void write ( DataOutput out ) throws IOException { String [ ] files = dir . listAll ( ) ; RAMDirectoryUtil . writeRAMFiles ( out , dir , files ) ; } public void readFields ( DataInput in ) throws IOException { resetForm ( ) ; RAMDirectoryUtil . readRAMFiles ( in , dir ) ; } } </s>
<s> package com . senseidb . bql . parsers ; import org . antlr . runtime . RecognitionException ; import org . antlr . runtime . tree . CommonTree ; import org . json . JSONObject ; public abstract class AbstractCompiler { public AbstractCompiler ( ) { super ( ) ; } public abstract JSONObject compile ( String expression ) throws RecognitionException ; public abstract String getErrorMessage ( RecognitionException error ) ; protected void printTree ( CommonTree ast ) { print ( ast , <NUM_LIT:0> ) ; } private void print ( CommonTree tree , int level ) { for ( int i = <NUM_LIT:0> ; i < level ; i ++ ) { System . out . print ( "<STR_LIT:-->" ) ; } if ( tree == null ) { System . out . println ( "<STR_LIT>" ) ; return ; } System . out . println ( "<STR_LIT:U+0020>" + tree . getType ( ) + "<STR_LIT:U+0020>" + tree . getText ( ) ) ; if ( tree . getChildren ( ) != null ) { for ( Object ie : tree . getChildren ( ) ) { print ( ( CommonTree ) ie , level + <NUM_LIT:1> ) ; } } } } </s>
<s> package com . senseidb . bql . parsers ; import java . util . HashMap ; import java . util . Map ; import org . antlr . runtime . ANTLRStringStream ; import org . antlr . runtime . CommonTokenStream ; import org . antlr . runtime . RecognitionException ; import org . antlr . runtime . TokenStream ; import org . antlr . runtime . tree . CommonTree ; import org . json . JSONObject ; import com . senseidb . bql . parsers . BQLLexer ; import com . senseidb . bql . parsers . BQLParser ; public class BQLCompiler extends AbstractCompiler { private Map < String , String [ ] > _facetInfoMap = new HashMap < String , String [ ] > ( ) ; private BQLParser _parser = null ; public BQLCompiler ( Map < String , String [ ] > facetInfoMap ) { _facetInfoMap = facetInfoMap ; } public JSONObject compile ( String bqlStmt ) throws RecognitionException { ANTLRStringStream input = new ANTLRStringStream ( bqlStmt ) ; TokenStream tokens = new CommonTokenStream ( new BQLLexer ( input ) ) ; _parser = new BQLParser ( tokens , _facetInfoMap ) ; BQLParser . statement_return ret = _parser . statement ( ) ; CommonTree ast = ( CommonTree ) ret . tree ; JSONObject json = ( JSONObject ) ret . json ; return json ; } public String getErrorMessage ( RecognitionException error ) { if ( _parser != null ) { return _parser . getErrorMessage ( error , _parser . getTokenNames ( ) ) ; } else { return null ; } } } </s>
<s> package com . senseidb . conf ; import java . io . File ; import proj . zoie . api . indexing . ZoieIndexableInterpreter ; import proj . zoie . impl . indexing . ZoieConfig ; import com . senseidb . search . node . SenseiIndexReaderDecorator ; import com . senseidb . search . node . SenseiZoieFactory ; public interface ZoieFactoryFactory { SenseiZoieFactory < ? > getZoieFactory ( File idxDir , ZoieIndexableInterpreter < ? > interpreter , SenseiIndexReaderDecorator decorator , ZoieConfig config ) ; } </s>
<s> package com . senseidb . conf ; import java . text . ParseException ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Date ; import java . util . HashMap ; import java . util . HashSet ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import org . apache . commons . configuration . ConfigurationException ; import org . apache . log4j . Logger ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import org . springframework . util . Assert ; import com . browseengine . bobo . facets . FacetHandler ; import com . browseengine . bobo . facets . FacetHandler . FacetDataNone ; import com . browseengine . bobo . facets . FacetHandlerInitializerParam ; import com . browseengine . bobo . facets . RuntimeFacetHandler ; import com . browseengine . bobo . facets . RuntimeFacetHandlerFactory ; import com . browseengine . bobo . facets . AbstractRuntimeFacetHandlerFactory ; import com . browseengine . bobo . facets . attribute . AttributesFacetHandler ; import com . browseengine . bobo . facets . data . PredefinedTermListFactory ; import com . browseengine . bobo . facets . data . TermListFactory ; import com . browseengine . bobo . facets . impl . CompactMultiValueFacetHandler ; import com . browseengine . bobo . facets . impl . DynamicTimeRangeFacetHandler ; import com . browseengine . bobo . facets . impl . HistogramFacetHandler ; import com . browseengine . bobo . facets . impl . MultiValueFacetHandler ; import com . browseengine . bobo . facets . impl . MultiValueWithWeightFacetHandler ; import com . browseengine . bobo . facets . impl . PathFacetHandler ; import com . browseengine . bobo . facets . impl . RangeFacetHandler ; import com . browseengine . bobo . facets . impl . SimpleFacetHandler ; import com . browseengine . bobo . facets . range . MultiRangeFacetHandler ; import com . senseidb . conf . SenseiSchema . FacetDefinition ; import com . senseidb . indexing . DefaultSenseiInterpreter ; import com . senseidb . indexing . activity . ActivityValues ; import com . senseidb . indexing . activity . CompositeActivityManager ; import com . senseidb . indexing . activity . CompositeActivityValues ; import com . senseidb . indexing . activity . facet . ActivityRangeFacetHandler ; import com . senseidb . indexing . activity . primitives . ActivityIntValues ; import com . senseidb . indexing . activity . time . TimeAggregatedActivityValues ; import com . senseidb . plugin . SenseiPluginRegistry ; import com . senseidb . search . facet . UIDFacetHandler ; import com . senseidb . search . plugin . PluggableSearchEngineManager ; import com . senseidb . search . req . SenseiSystemInfo ; public class SenseiFacetHandlerBuilder { private static Logger logger = Logger . getLogger ( SenseiFacetHandlerBuilder . class ) ; public static String UID_FACET_NAME = "<STR_LIT>" ; private static Map < String , TermListFactory < ? > > getPredefinedTermListFactoryMap ( JSONObject schemaObj ) throws JSONException , ConfigurationException { HashMap < String , TermListFactory < ? > > retMap = new HashMap < String , TermListFactory < ? > > ( ) ; JSONObject tableElem = schemaObj . optJSONObject ( "<STR_LIT>" ) ; if ( tableElem == null ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } JSONArray columns = tableElem . optJSONArray ( "<STR_LIT>" ) ; int count = <NUM_LIT:0> ; if ( columns != null ) { count = columns . length ( ) ; } for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { JSONObject column = columns . getJSONObject ( i ) ; try { String n = column . getString ( "<STR_LIT:name>" ) ; String t = column . getString ( "<STR_LIT:type>" ) ; TermListFactory < ? > factory = null ; if ( t . equals ( "<STR_LIT:int>" ) ) { factory = DefaultSenseiInterpreter . getTermListFactory ( int . class ) ; } else if ( t . equals ( "<STR_LIT>" ) ) { factory = DefaultSenseiInterpreter . getTermListFactory ( short . class ) ; } else if ( t . equals ( "<STR_LIT:long>" ) ) { factory = DefaultSenseiInterpreter . getTermListFactory ( long . class ) ; } else if ( t . equals ( "<STR_LIT:float>" ) ) { factory = DefaultSenseiInterpreter . getTermListFactory ( float . class ) ; } else if ( t . equals ( "<STR_LIT:double>" ) ) { factory = DefaultSenseiInterpreter . getTermListFactory ( double . class ) ; } else if ( t . equals ( "<STR_LIT>" ) ) { factory = DefaultSenseiInterpreter . getTermListFactory ( char . class ) ; } else if ( t . equals ( "<STR_LIT:string>" ) ) { factory = TermListFactory . StringListFactory ; } else if ( t . equals ( "<STR_LIT:boolean>" ) ) { factory = DefaultSenseiInterpreter . getTermListFactory ( boolean . class ) ; } else if ( t . equals ( "<STR_LIT:date>" ) ) { String f = "<STR_LIT>" ; try { f = column . optString ( "<STR_LIT>" ) ; } catch ( Exception ex ) { logger . error ( ex . getMessage ( ) , ex ) ; } if ( f . isEmpty ( ) ) throw new Exception ( "<STR_LIT>" ) ; else factory = new PredefinedTermListFactory < Date > ( Date . class , f ) ; } if ( factory != null ) { retMap . put ( n , factory ) ; } } catch ( Exception e ) { throw new ConfigurationException ( "<STR_LIT>" + column , e ) ; } } return retMap ; } static SimpleFacetHandler buildSimpleFacetHandler ( String name , String fieldName , Set < String > depends , TermListFactory < ? > termListFactory ) { return new SimpleFacetHandler ( name , fieldName , termListFactory , depends ) ; } static CompactMultiValueFacetHandler buildCompactMultiHandler ( String name , String fieldName , Set < String > depends , TermListFactory < ? > termListFactory ) { return new CompactMultiValueFacetHandler ( name , fieldName , termListFactory ) ; } static MultiValueFacetHandler buildMultiHandler ( String name , String fieldName , TermListFactory < ? > termListFactory , Set < String > depends ) { return new MultiValueFacetHandler ( name , fieldName , termListFactory , null , depends ) ; } static MultiValueFacetHandler buildWeightedMultiHandler ( String name , String fieldName , TermListFactory < ? > termListFactory , Set < String > depends ) { return new MultiValueWithWeightFacetHandler ( name , fieldName , termListFactory ) ; } static PathFacetHandler buildPathHandler ( String name , String fieldName , Map < String , List < String > > paramMap ) { PathFacetHandler handler = new PathFacetHandler ( name , fieldName , false ) ; String sep = null ; if ( paramMap != null ) { List < String > sepVals = paramMap . get ( "<STR_LIT>" ) ; if ( sepVals != null && sepVals . size ( ) > <NUM_LIT:0> ) { sep = sepVals . get ( <NUM_LIT:0> ) ; } } if ( sep != null ) { handler . setSeparator ( sep ) ; } return handler ; } static RangeFacetHandler buildRangeHandler ( String name , String fieldName , TermListFactory < ? > termListFactory , Map < String , List < String > > paramMap ) { LinkedList < String > predefinedRanges = buildPredefinedRanges ( paramMap ) ; return new RangeFacetHandler ( name , fieldName , termListFactory , predefinedRanges ) ; } private static LinkedList < String > buildPredefinedRanges ( Map < String , List < String > > paramMap ) { LinkedList < String > predefinedRanges = new LinkedList < String > ( ) ; if ( paramMap != null ) { List < String > rangeList = paramMap . get ( "<STR_LIT>" ) ; if ( rangeList != null ) { for ( String range : rangeList ) { if ( ! range . matches ( "<STR_LIT>" ) ) { if ( ! range . contains ( "<STR_LIT:->" ) || ! range . contains ( "<STR_LIT:U+002C>" ) ) { range = "<STR_LIT:[>" + range . replaceFirst ( "<STR_LIT>" , "<STR_LIT>" ) + "<STR_LIT:]>" ; } else { range = "<STR_LIT:[>" + range . replaceFirst ( "<STR_LIT:U+002C>" , "<STR_LIT>" ) + "<STR_LIT:]>" ; } } predefinedRanges . add ( range ) ; } } } return predefinedRanges ; } public static Map < String , List < String > > parseParams ( JSONArray paramList ) throws JSONException { HashMap < String , List < String > > retmap = new HashMap < String , List < String > > ( ) ; if ( paramList != null ) { int count = paramList . length ( ) ; for ( int j = <NUM_LIT:0> ; j < count ; ++ j ) { JSONObject param = paramList . getJSONObject ( j ) ; String paramName = param . getString ( "<STR_LIT:name>" ) ; String paramValue = param . getString ( "<STR_LIT:value>" ) ; List < String > list = retmap . get ( paramName ) ; if ( list == null ) { list = new LinkedList < String > ( ) ; retmap . put ( paramName , list ) ; } list . add ( paramValue ) ; } } return retmap ; } private static String getRequiredSingleParam ( Map < String , List < String > > paramMap , String name ) throws ConfigurationException { if ( paramMap != null ) { List < String > vals = paramMap . get ( name ) ; if ( vals != null && vals . size ( ) > <NUM_LIT:0> ) { return vals . get ( <NUM_LIT:0> ) ; } else { throw new ConfigurationException ( "<STR_LIT>" + name + "<STR_LIT>" ) ; } } else { throw new ConfigurationException ( "<STR_LIT>" ) ; } } private static RuntimeFacetHandlerFactory < ? , ? > getHistogramFacetHandlerFactory ( JSONObject facet , String name , Map < String , List < String > > paramMap ) throws ConfigurationException { String dataType = getRequiredSingleParam ( paramMap , "<STR_LIT>" ) ; String dataHandler = getRequiredSingleParam ( paramMap , "<STR_LIT>" ) ; String startParam = getRequiredSingleParam ( paramMap , "<STR_LIT:start>" ) ; String endParam = getRequiredSingleParam ( paramMap , "<STR_LIT>" ) ; String unitParam = getRequiredSingleParam ( paramMap , "<STR_LIT>" ) ; if ( "<STR_LIT:int>" . equals ( dataType ) ) { int start = Integer . parseInt ( startParam ) ; int end = Integer . parseInt ( endParam ) ; int unit = Integer . parseInt ( unitParam ) ; return buildHistogramFacetHandlerFactory ( name , dataHandler , start , end , unit ) ; } else if ( "<STR_LIT>" . equals ( dataType ) ) { short start = ( short ) Integer . parseInt ( startParam ) ; short end = ( short ) Integer . parseInt ( endParam ) ; short unit = ( short ) Integer . parseInt ( unitParam ) ; return buildHistogramFacetHandlerFactory ( name , dataHandler , start , end , unit ) ; } else if ( "<STR_LIT:long>" . equals ( dataType ) ) { long start = Long . parseLong ( startParam ) ; long end = Long . parseLong ( endParam ) ; long unit = Long . parseLong ( unitParam ) ; return buildHistogramFacetHandlerFactory ( name , dataHandler , start , end , unit ) ; } else if ( "<STR_LIT:float>" . equals ( dataType ) ) { float start = Float . parseFloat ( startParam ) ; float end = Float . parseFloat ( endParam ) ; float unit = Float . parseFloat ( unitParam ) ; return buildHistogramFacetHandlerFactory ( name , dataHandler , start , end , unit ) ; } else if ( "<STR_LIT:double>" . equals ( dataType ) ) { double start = Double . parseDouble ( startParam ) ; double end = Double . parseDouble ( endParam ) ; double unit = Double . parseDouble ( unitParam ) ; return buildHistogramFacetHandlerFactory ( name , dataHandler , start , end , unit ) ; } return null ; } private static < T extends Number > RuntimeFacetHandlerFactory < ? , ? > buildHistogramFacetHandlerFactory ( final String name , final String dataHandler , final T start , final T end , final T unit ) { return new AbstractRuntimeFacetHandlerFactory < FacetHandlerInitializerParam , RuntimeFacetHandler < FacetDataNone > > ( ) { @ Override public RuntimeFacetHandler < FacetDataNone > get ( FacetHandlerInitializerParam params ) { return new HistogramFacetHandler < T > ( name , dataHandler , start , end , unit ) ; } ; @ Override public boolean isLoadLazily ( ) { return true ; } @ Override public String getName ( ) { return name ; } } ; } public static SenseiSystemInfo buildFacets ( JSONObject schemaObj , SenseiPluginRegistry pluginRegistry , List < FacetHandler < ? > > facets , List < RuntimeFacetHandlerFactory < ? , ? > > runtimeFacets , PluggableSearchEngineManager pluggableSearchEngineManager ) throws JSONException , ConfigurationException { Set < String > pluggableSearchEngineFacetNames = pluggableSearchEngineManager . getFacetNames ( ) ; SenseiSystemInfo sysInfo = new SenseiSystemInfo ( ) ; JSONArray facetsList = schemaObj . optJSONArray ( "<STR_LIT>" ) ; int count = <NUM_LIT:0> ; if ( facetsList != null ) { count = facetsList . length ( ) ; } if ( count <= <NUM_LIT:0> ) { return sysInfo ; } JSONObject table = schemaObj . optJSONObject ( "<STR_LIT>" ) ; if ( table == null ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } JSONArray columns = table . optJSONArray ( "<STR_LIT>" ) ; Map < String , JSONObject > columnMap = new HashMap < String , JSONObject > ( ) ; for ( int i = <NUM_LIT:0> ; i < columns . length ( ) ; ++ i ) { JSONObject column = columns . getJSONObject ( i ) ; try { String name = column . getString ( "<STR_LIT:name>" ) ; columnMap . put ( name , column ) ; } catch ( Exception e ) { throw new ConfigurationException ( "<STR_LIT>" , e ) ; } } Map < String , TermListFactory < ? > > termListFactoryMap = getPredefinedTermListFactoryMap ( schemaObj ) ; Set < SenseiSystemInfo . SenseiFacetInfo > facetInfos = new HashSet < SenseiSystemInfo . SenseiFacetInfo > ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { JSONObject facet = facetsList . getJSONObject ( i ) ; try { String name = facet . getString ( "<STR_LIT:name>" ) ; if ( UID_FACET_NAME . equals ( name ) ) { logger . error ( "<STR_LIT>" + UID_FACET_NAME + "<STR_LIT>" ) ; continue ; } if ( pluggableSearchEngineFacetNames . contains ( name ) ) { continue ; } String type = facet . getString ( "<STR_LIT:type>" ) ; String fieldName = facet . optString ( "<STR_LIT>" , name ) ; Set < String > dependSet = new HashSet < String > ( ) ; JSONArray dependsArray = facet . optJSONArray ( "<STR_LIT>" ) ; if ( dependsArray != null ) { int depCount = dependsArray . length ( ) ; for ( int k = <NUM_LIT:0> ; k < depCount ; ++ k ) { dependSet . add ( dependsArray . getString ( k ) ) ; } } SenseiSystemInfo . SenseiFacetInfo facetInfo = new SenseiSystemInfo . SenseiFacetInfo ( name ) ; Map < String , String > facetProps = new HashMap < String , String > ( ) ; facetProps . put ( "<STR_LIT:type>" , type ) ; facetProps . put ( "<STR_LIT>" , fieldName ) ; JSONObject column = columnMap . get ( fieldName ) ; String columnType = ( column == null ) ? "<STR_LIT>" : column . optString ( "<STR_LIT:type>" , "<STR_LIT>" ) ; facetProps . put ( "<STR_LIT>" , columnType ) ; facetProps . put ( "<STR_LIT>" , dependSet . toString ( ) ) ; JSONArray paramList = facet . optJSONArray ( "<STR_LIT>" ) ; Map < String , List < String > > paramMap = parseParams ( paramList ) ; for ( Entry < String , List < String > > entry : paramMap . entrySet ( ) ) { facetProps . put ( entry . getKey ( ) , entry . getValue ( ) . toString ( ) ) ; } facetInfo . setProps ( facetProps ) ; facetInfos . add ( facetInfo ) ; FacetHandler < ? > facetHandler = null ; if ( type . equals ( "<STR_LIT>" ) ) { facetHandler = buildSimpleFacetHandler ( name , fieldName , dependSet , termListFactoryMap . get ( fieldName ) ) ; } else if ( type . equals ( "<STR_LIT:path>" ) ) { facetHandler = buildPathHandler ( name , fieldName , paramMap ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { if ( column . optBoolean ( "<STR_LIT>" ) ) { facetHandler = new MultiRangeFacetHandler ( name , fieldName , null , termListFactoryMap . get ( fieldName ) , buildPredefinedRanges ( paramMap ) ) ; } else { facetHandler = buildRangeHandler ( name , fieldName , termListFactoryMap . get ( fieldName ) , paramMap ) ; } } else if ( type . equals ( "<STR_LIT>" ) ) { facetHandler = buildMultiHandler ( name , fieldName , termListFactoryMap . get ( fieldName ) , dependSet ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { facetHandler = buildCompactMultiHandler ( name , fieldName , dependSet , termListFactoryMap . get ( fieldName ) ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { facetHandler = buildWeightedMultiHandler ( name , fieldName , termListFactoryMap . get ( fieldName ) , dependSet ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { facetHandler = new AttributesFacetHandler ( name , fieldName , termListFactoryMap . get ( fieldName ) , null , facetProps ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { RuntimeFacetHandlerFactory < ? , ? > runtimeFacetFactory = getHistogramFacetHandlerFactory ( facet , name , paramMap ) ; runtimeFacets . add ( runtimeFacetFactory ) ; facetInfo . setRunTime ( true ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { if ( dependSet . isEmpty ( ) ) { Assert . isTrue ( fieldName != null && fieldName . length ( ) > <NUM_LIT:0> , "<STR_LIT>" + name + "<STR_LIT>" ) ; RangeFacetHandler internalFacet = new RangeFacetHandler ( name + "<STR_LIT>" , fieldName , new PredefinedTermListFactory ( Long . class , DynamicTimeRangeFacetHandler . NUMBER_FORMAT ) , null ) ; facets . add ( internalFacet ) ; dependSet . add ( internalFacet . getName ( ) ) ; } RuntimeFacetHandlerFactory < ? , ? > runtimeFacetFactory = getDynamicTimeFacetHandlerFactory ( name , fieldName , dependSet , paramMap ) ; runtimeFacets . add ( runtimeFacetFactory ) ; facetInfo . setRunTime ( true ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { boolean isDynamic = facet . optBoolean ( "<STR_LIT>" ) ; if ( isDynamic ) { RuntimeFacetHandlerFactory < ? , ? > runtimeFacetFactory = pluginRegistry . getRuntimeFacet ( name ) ; runtimeFacets . add ( runtimeFacetFactory ) ; facetInfo . setRunTime ( true ) ; } else { facetHandler = pluginRegistry . getFacet ( name ) ; } } else { throw new IllegalArgumentException ( "<STR_LIT>" + type ) ; } if ( facetHandler != null ) { facets . add ( facetHandler ) ; } } catch ( Exception e ) { throw new ConfigurationException ( "<STR_LIT>" + facet , e ) ; } } facets . addAll ( ( Collection < ? extends FacetHandler < ? > > ) pluggableSearchEngineManager . createFacetHandlers ( ) ) ; UIDFacetHandler uidHandler = new UIDFacetHandler ( UID_FACET_NAME ) ; facets . add ( uidHandler ) ; sysInfo . setFacetInfos ( facetInfos ) ; return sysInfo ; } public static RuntimeFacetHandlerFactory < ? , ? > getDynamicTimeFacetHandlerFactory ( final String name , String fieldName , Set < String > dependSet , final Map < String , List < String > > paramMap ) { Assert . isTrue ( dependSet . size ( ) == <NUM_LIT:1> , "<STR_LIT>" + name + "<STR_LIT>" + dependSet ) ; final String depends = dependSet . iterator ( ) . next ( ) ; Assert . notEmpty ( paramMap . get ( "<STR_LIT>" ) , "<STR_LIT>" + name + "<STR_LIT>" ) ; return new AbstractRuntimeFacetHandlerFactory < FacetHandlerInitializerParam , RuntimeFacetHandler < ? > > ( ) { @ Override public String getName ( ) { return name ; } @ Override public RuntimeFacetHandler < ? > get ( FacetHandlerInitializerParam params ) { long overrideNow = - <NUM_LIT:1> ; try { String overrideProp = System . getProperty ( "<STR_LIT>" ) ; if ( overrideProp != null ) { overrideNow = Long . parseLong ( overrideProp ) ; } } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } long now = System . currentTimeMillis ( ) ; if ( overrideNow > <NUM_LIT:0> ) now = overrideNow ; else { if ( params != null ) { long [ ] longParam = params . getLongParam ( "<STR_LIT>" ) ; if ( longParam == null || longParam . length == <NUM_LIT:0> ) longParam = params . getLongParam ( "<STR_LIT>" ) ; if ( longParam != null && longParam . length > <NUM_LIT:0> ) now = longParam [ <NUM_LIT:0> ] ; } } List < String > ranges = paramMap . get ( "<STR_LIT>" ) ; try { return new DynamicTimeRangeFacetHandler ( name , depends , now , ranges ) ; } catch ( ParseException ex ) { throw new RuntimeException ( ex ) ; } } } ; } } </s>
<s> package com . senseidb . conf ; import java . io . File ; import java . util . ArrayList ; import java . util . List ; import java . util . Map ; import org . apache . commons . configuration . FileConfiguration ; import org . springframework . context . ApplicationContext ; import org . springframework . context . support . FileSystemXmlApplicationContext ; import com . senseidb . plugin . SenseiPluginFactory ; import com . senseidb . plugin . SenseiPluginRegistry ; public class SpringSenseiPluginFactory implements SenseiPluginFactory < List < ? > > { private ApplicationContext context = null ; public final String SPRING_FILENAME = "<STR_LIT>" ; public final String CLASS_TO_RETURN = "<STR_LIT>" ; private Class < ? > classToReturn ; private List < Class > classes ; @ Override public synchronized List < ? > getBean ( Map < String , String > initProperties , String fullPrefix , SenseiPluginRegistry pluginRegistry ) { if ( context == null ) { if ( ! initProperties . containsKey ( SPRING_FILENAME ) ) { throw new IllegalArgumentException ( "<STR_LIT>" + SPRING_FILENAME ) ; } if ( ! initProperties . containsKey ( CLASS_TO_RETURN ) ) { throw new IllegalArgumentException ( "<STR_LIT>" + CLASS_TO_RETURN ) ; } String localName = initProperties . get ( SPRING_FILENAME ) ; String springFile = null ; if ( localName . contains ( "<STR_LIT:/>" ) || localName . contains ( "<STR_LIT:\\>" ) ) { springFile = localName ; } else { File directory = ( ( FileConfiguration ) pluginRegistry . getConfiguration ( ) ) . getFile ( ) . getParentFile ( ) ; springFile = new File ( directory , localName ) . getAbsolutePath ( ) ; } try { springFile = "<STR_LIT>" + springFile ; context = new FileSystemXmlApplicationContext ( springFile ) ; classes = getClasses ( initProperties . get ( CLASS_TO_RETURN ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } List < Object > ret = new ArrayList < Object > ( ) ; for ( Class classToReturn : classes ) { for ( String beanName : context . getBeanNamesForType ( classToReturn ) ) { ret . add ( context . getBean ( beanName ) ) ; } } return ret ; } private List < Class > getClasses ( String classesToReturn ) throws ClassNotFoundException { List < String > classesStr = new ArrayList < String > ( ) ; if ( classesToReturn . contains ( "<STR_LIT:U+002C>" ) ) { for ( String cls : classesToReturn . split ( "<STR_LIT:U+002C>" ) ) { classesStr . add ( cls . trim ( ) ) ; } } else { classesStr . add ( classesToReturn . trim ( ) ) ; } List < Class > ret = new ArrayList < Class > ( classesStr . size ( ) ) ; for ( String cls : classesStr ) { ret . add ( Class . forName ( cls ) ) ; } return ret ; } } </s>
<s> package com . senseidb . conf ; import java . util . Comparator ; public interface SenseiConfParams { public static final String NODE_ID = "<STR_LIT>" ; public static final String PARTITIONS = "<STR_LIT>" ; public static final String SERVER_PORT = "<STR_LIT>" ; public static final String SERVER_REQ_THREAD_POOL_SIZE = "<STR_LIT>" ; public static final String SERVER_REQ_THREAD_POOL_MAXSIZE = "<STR_LIT>" ; public static final String SERVER_REQ_THREAD_POOL_KEEPALIVE = "<STR_LIT>" ; public static final String SENSEI_CLUSTER_CLIENT_NAME = "<STR_LIT>" ; public static final String SENSEI_CLUSTER_NAME = "<STR_LIT>" ; public static final String SENSEI_CLUSTER_URL = "<STR_LIT>" ; public static final String SENSEI_CLUSTER_TIMEOUT = "<STR_LIT>" ; public static final String SENSEI_INDEX_DIR = "<STR_LIT>" ; public static final String SENSEI_FEDERATED_BROKER = "<STR_LIT>" ; public static final String SENSEI_FEDERATED_BROKER_PRUNER = "<STR_LIT>" ; public static final String SENSEI_INDEX_BATCH_SIZE = "<STR_LIT>" ; public static final String SENSEI_INDEX_BATCH_DELAY = "<STR_LIT>" ; public static final String SENSEI_INDEX_BATCH_MAXSIZE = "<STR_LIT>" ; public static final String SENSEI_INDEX_REALTIME = "<STR_LIT>" ; public static final String SENSEI_INDEX_FRESHNESS = "<STR_LIT>" ; public static final String SENSEI_SKIP_BAD_RECORDS = "<STR_LIT>" ; public static final String SENSEI_INDEXER_MODE = "<STR_LIT>" ; public static final String SENSEI_INDEXER_TYPE = "<STR_LIT>" ; public static final String SENSEI_INDEXER_TYPE_HOURGLASS = "<STR_LIT>" ; public static final String SENSEI_INDEXER_TYPE_ZOIE = "<STR_LIT>" ; public static final String SENSEI_INDEXER_COPIER = "<STR_LIT>" ; public static final String SENSEI_INDEXER_COPIER_HDFS = "<STR_LIT>" ; public static final String SENSEI_INDEX_ANALYZER = "<STR_LIT>" ; public static final String SENSEI_INDEX_SIMILARITY = "<STR_LIT>" ; public static final String SENSEI_INDEX_INTERPRETER = "<STR_LIT>" ; public static final String SENSEI_INDEX_CUSTOM = "<STR_LIT>" ; public static final String SENSEI_QUERY_BUILDER_FACTORY = "<STR_LIT>" ; public static final String SENSEI_SHARDING_STRATEGY = "<STR_LIT>" ; public static final String SENSEI_INDEX_MANAGER = "<STR_LIT>" ; public static final String SENSEI_INDEX_MANAGER_FILTER = "<STR_LIT>" ; public static final String SENSEI_GATEWAY = "<STR_LIT>" ; public static final String SENSEI_VERSION_COMPARATOR = "<STR_LIT>" ; public static final String SENSEI_PLUGIN_SVCS = "<STR_LIT>" ; public static final String SENSEI_HOURGLASS_SCHEDULE = "<STR_LIT>" ; public static final String SENSEI_HOURGLASS_TRIMTHRESHOLD = "<STR_LIT>" ; public static final String SENSEI_HOURGLASS_FREQUENCY = "<STR_LIT>" ; public static final String SENSEI_HOURGLASS_APPENDONLY = "<STR_LIT>" ; public static final String SENSEI_HOURGLASS_FREQUENCY_MIN = "<STR_LIT>" ; public static final String SENSEI_HOURGLASS_FREQUENCY_HOUR = "<STR_LIT>" ; public static final String SENSEI_HOURGLASS_FREQUENCY_DAY = "<STR_LIT>" ; public static final String SERVER_BROKER_PORT = "<STR_LIT>" ; public static final String SERVER_BROKER_WEBAPP_PATH = "<STR_LIT>" ; public static final String SERVER_BROKER_MINTHREAD = "<STR_LIT>" ; public static final String SERVER_BROKER_MAXTHREAD = "<STR_LIT>" ; public static final String SERVER_BROKER_MAXWAIT = "<STR_LIT>" ; public static final String SERVER_BROKER_TIMEOUT = "<STR_LIT>" ; public static final String ALLOW_PARTIAL_MERGE = "<STR_LIT>" ; public static final String SENSEI_BROKER_POLL_INTERVAL = "<STR_LIT>" ; public static final String SENSEI_BROKER_MIN_RESPONSES = "<STR_LIT>" ; public static final String SENSEI_BROKER_MAX_TOTAL_WAIT = "<STR_LIT>" ; public static final String SENSEI_ACTIVITY_CONFIG = "<STR_LIT>" ; public static final String SERVER_SEARCH_ROUTER_FACTORY = "<STR_LIT>" ; public static final String SENSEI_INDEX_PRUNER = "<STR_LIT>" ; public static final String SENSEI_ZOIE_RETENTION_DAYS = "<STR_LIT>" ; public static final String SENSEI_ZOIE_RETENTION_CLASS = "<STR_LIT>" ; public static final String SENSEI_ZOIE_RETENTION_COLUMN = "<STR_LIT>" ; public static final String SENSEI_ZOIE_RETENTION_TIMEUNIT = "<STR_LIT>" ; public static final String SENSEI_MX4J_PORT = "<STR_LIT>" ; public static final String SENSEI_INDEX_ACTIVITY_FILTER = "<STR_LIT>" ; public static final String SENSEI_INDEX_ACTIVITY_PURGE_FREQUENCY_HOURS = "<STR_LIT>" ; public static final String SENSEI_INDEX_ACTIVITY_PURGE_FREQUENCY_MINUTES = "<STR_LIT>" ; public static final Comparator < String > DEFAULT_VERSION_STRING_COMPARATOR = new Comparator < String > ( ) { @ Override public int compare ( String o1 , String o2 ) { if ( o1 == null && o2 == null ) { return <NUM_LIT:0> ; } if ( o1 == null ) return - <NUM_LIT:1> ; if ( o2 == null ) return <NUM_LIT:1> ; return o1 . compareTo ( o2 ) ; } } ; public static final Comparator < String > DEFAULT_VERSION_LONG_COMPARATOR = new Comparator < String > ( ) { @ Override public int compare ( String o1 , String o2 ) { long l1 , l2 ; if ( o1 == null || o1 . length ( ) == <NUM_LIT:0> ) { l1 = <NUM_LIT> ; } else { l1 = Long . parseLong ( o1 ) ; } if ( o2 == null || o2 . length ( ) == <NUM_LIT:0> ) { l2 = <NUM_LIT> ; } else { l2 = Long . parseLong ( o2 ) ; } return Long . valueOf ( l1 ) . compareTo ( Long . valueOf ( l2 ) ) ; } } ; } </s>
<s> package com . senseidb . conf ; import it . unimi . dsi . fastutil . ints . IntOpenHashSet ; import it . unimi . dsi . fastutil . ints . IntSet ; import java . io . File ; import java . io . FileInputStream ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Comparator ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . concurrent . TimeUnit ; import java . util . regex . Matcher ; import java . util . regex . Pattern ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import org . apache . commons . configuration . Configuration ; import org . apache . commons . configuration . ConfigurationException ; import org . apache . commons . configuration . MapConfiguration ; import org . apache . commons . configuration . PropertiesConfiguration ; import org . apache . commons . io . IOUtils ; import org . apache . log4j . Logger ; import org . apache . lucene . analysis . Analyzer ; import org . apache . lucene . analysis . standard . StandardAnalyzer ; import org . apache . lucene . queryParser . QueryParser ; import org . apache . lucene . search . DefaultSimilarity ; import org . apache . lucene . search . Filter ; import org . apache . lucene . search . Similarity ; import org . apache . lucene . util . Version ; import org . jolokia . http . AgentServlet ; import org . json . JSONException ; import org . json . JSONObject ; import org . mortbay . jetty . Server ; import org . mortbay . jetty . nio . SelectChannelConnector ; import org . mortbay . jetty . servlet . ServletHolder ; import org . mortbay . jetty . webapp . WebAppContext ; import org . mortbay . servlet . GzipFilter ; import org . mortbay . thread . QueuedThreadPool ; import org . springframework . core . io . Resource ; import org . w3c . dom . Document ; import proj . zoie . api . DirectoryManager . DIRECTORY_MODE ; import proj . zoie . api . IndexCopier ; import proj . zoie . api . indexing . ZoieIndexableInterpreter ; import proj . zoie . hourglass . impl . HourGlassScheduler . FREQUENCY ; import proj . zoie . impl . indexing . DefaultReaderCache ; import proj . zoie . impl . indexing . ReaderCacheFactory ; import proj . zoie . impl . indexing . SimpleReaderCache ; import proj . zoie . impl . indexing . ZoieConfig ; import com . browseengine . bobo . facets . FacetHandler ; import com . browseengine . bobo . facets . RuntimeFacetHandlerFactory ; import com . linkedin . norbert . javacompat . cluster . ClusterClient ; import com . linkedin . norbert . javacompat . cluster . ZooKeeperClusterClient ; import com . linkedin . norbert . javacompat . network . NettyNetworkServer ; import com . linkedin . norbert . javacompat . network . NetworkServer ; import com . linkedin . norbert . javacompat . network . NetworkServerConfig ; import com . linkedin . norbert . javacompat . network . PartitionedLoadBalancerFactory ; import com . senseidb . cluster . routing . SenseiPartitionedLoadBalancerFactory ; import com . senseidb . gateway . SenseiGateway ; import com . senseidb . indexing . CustomIndexingPipeline ; import com . senseidb . indexing . DefaultJsonSchemaInterpreter ; import com . senseidb . indexing . DefaultStreamingIndexingManager ; import com . senseidb . indexing . SenseiIndexPruner ; import com . senseidb . indexing . ShardingStrategy ; import com . senseidb . indexing . activity . deletion . PurgeFilterWrapper ; import com . senseidb . jmx . JmxSenseiMBeanServer ; import com . senseidb . plugin . SenseiPluginRegistry ; import com . senseidb . search . node . SenseiCore ; import com . senseidb . search . node . SenseiHourglassFactory ; import com . senseidb . search . node . SenseiIndexReaderDecorator ; import com . senseidb . search . node . SenseiIndexingManager ; import com . senseidb . search . node . SenseiPairFactory ; import com . senseidb . search . node . SenseiQueryBuilderFactory ; import com . senseidb . search . node . SenseiServer ; import com . senseidb . search . node . SenseiZoieFactory ; import com . senseidb . search . node . SenseiZoieSystemFactory ; import com . senseidb . search . node . impl . DefaultJsonQueryBuilderFactory ; import com . senseidb . search . plugin . PluggableSearchEngineManager ; import com . senseidb . search . query . RetentionFilterFactory ; import com . senseidb . search . query . TimeRetentionFilter ; import com . senseidb . search . relevance . CustomRelevanceFunction . CustomRelevanceFunctionFactory ; import com . senseidb . search . relevance . ExternalRelevanceDataStorage ; import com . senseidb . search . relevance . ExternalRelevanceDataStorage . RelevanceObjPlugin ; import com . senseidb . search . relevance . ModelStorage ; import com . senseidb . search . req . AbstractSenseiRequest ; import com . senseidb . search . req . AbstractSenseiResult ; import com . senseidb . search . req . SenseiSystemInfo ; import com . senseidb . servlet . DefaultSenseiJSONServlet ; import com . senseidb . servlet . SenseiConfigServletContextListener ; import com . senseidb . servlet . SenseiHttpInvokerServiceServlet ; import com . senseidb . svc . impl . AbstractSenseiCoreService ; import com . senseidb . util . HDFSIndexCopier ; import com . senseidb . util . NetUtil ; import com . senseidb . util . SenseiUncaughtExceptionHandler ; public class SenseiServerBuilder implements SenseiConfParams { private static Logger logger = Logger . getLogger ( SenseiServerBuilder . class ) ; private static final String DUMMY_OUT_IP = "<STR_LIT>" ; public static final String SENSEI_PROPERTIES = "<STR_LIT>" ; public static final String SCHEMA_FILE_XML = "<STR_LIT>" ; public static final String SCHEMA_FILE_JSON = "<STR_LIT>" ; private final File _senseiConfFile ; private final Configuration _senseiConf ; private SenseiPluginRegistry pluginRegistry ; private final JSONObject _schemaDoc ; private final SenseiSchema _senseiSchema ; private final SenseiGateway _gateway ; private PluggableSearchEngineManager pluggableSearchEngineManager ; static final String SENSEI_CONTEXT_PATH = "<STR_LIT>" ; public Configuration getConfiguration ( ) { return _senseiConf ; } public SenseiPluginRegistry getPluginRegistry ( ) { return pluginRegistry ; } public ClusterClient buildClusterClient ( ) { String clusterName = _senseiConf . getString ( SENSEI_CLUSTER_NAME ) ; String clusterClientName = _senseiConf . getString ( SENSEI_CLUSTER_CLIENT_NAME , clusterName ) ; String zkUrl = _senseiConf . getString ( SENSEI_CLUSTER_URL ) ; int zkTimeout = _senseiConf . getInt ( SENSEI_CLUSTER_TIMEOUT , <NUM_LIT> ) ; ClusterClient clusterClient = new ZooKeeperClusterClient ( clusterClientName , clusterName , zkUrl , zkTimeout ) ; logger . info ( "<STR_LIT>" + clusterName + "<STR_LIT>" ) ; clusterClient . awaitConnectionUninterruptibly ( ) ; logger . info ( "<STR_LIT>" + clusterName + "<STR_LIT>" ) ; return clusterClient ; } private static NetworkServer buildNetworkServer ( Configuration conf , ClusterClient clusterClient ) { NetworkServerConfig networkConfig = new NetworkServerConfig ( ) ; networkConfig . setClusterClient ( clusterClient ) ; networkConfig . setRequestThreadCorePoolSize ( conf . getInt ( SERVER_REQ_THREAD_POOL_SIZE , <NUM_LIT:20> ) ) ; networkConfig . setRequestThreadMaxPoolSize ( conf . getInt ( SERVER_REQ_THREAD_POOL_MAXSIZE , <NUM_LIT> ) ) ; networkConfig . setRequestThreadKeepAliveTimeSecs ( conf . getInt ( SERVER_REQ_THREAD_POOL_KEEPALIVE , <NUM_LIT> ) ) ; return new NettyNetworkServer ( networkConfig ) ; } static { try { org . mortbay . log . Log . setLog ( new org . mortbay . log . Slf4jLog ( ) ) ; } catch ( Throwable t ) { logger . error ( t . getMessage ( ) , t ) ; } } public Server buildHttpRestServer ( ) throws Exception { int port = _senseiConf . getInt ( SERVER_BROKER_PORT ) ; String webappPath = _senseiConf . getString ( SERVER_BROKER_WEBAPP_PATH , "<STR_LIT>" ) ; Server server = new Server ( ) ; QueuedThreadPool threadPool = new QueuedThreadPool ( ) ; threadPool . setName ( "<STR_LIT>" ) ; threadPool . setMinThreads ( _senseiConf . getInt ( SERVER_BROKER_MINTHREAD , <NUM_LIT:20> ) ) ; threadPool . setMaxThreads ( _senseiConf . getInt ( SERVER_BROKER_MAXTHREAD , <NUM_LIT> ) ) ; threadPool . setMaxIdleTimeMs ( _senseiConf . getInt ( SERVER_BROKER_MAXWAIT , <NUM_LIT> ) ) ; server . setThreadPool ( threadPool ) ; logger . info ( "<STR_LIT>" ) ; SelectChannelConnector connector = new SelectChannelConnector ( ) ; connector . setPort ( port ) ; server . addConnector ( connector ) ; DefaultSenseiJSONServlet senseiServlet = new DefaultSenseiJSONServlet ( ) ; ServletHolder senseiServletHolder = new ServletHolder ( senseiServlet ) ; SenseiHttpInvokerServiceServlet springServlet = new SenseiHttpInvokerServiceServlet ( ) ; ServletHolder springServletHolder = new ServletHolder ( springServlet ) ; AgentServlet jmxServlet = new AgentServlet ( ) ; ServletHolder jmxServletHolder = new ServletHolder ( jmxServlet ) ; WebAppContext senseiApp = new WebAppContext ( ) ; senseiApp . addFilter ( GzipFilter . class , "<STR_LIT:/>" + SENSEI_CONTEXT_PATH + "<STR_LIT>" , <NUM_LIT:1> ) ; senseiApp . setAttribute ( "<STR_LIT>" , _senseiConf ) ; senseiApp . setAttribute ( SenseiConfigServletContextListener . SENSEI_CONF_PLUGIN_REGISTRY , pluginRegistry ) ; senseiApp . setAttribute ( "<STR_LIT>" , _gateway . getVersionComparator ( ) ) ; PartitionedLoadBalancerFactory < String > routerFactory = pluginRegistry . getBeanByFullPrefix ( SenseiConfParams . SERVER_SEARCH_ROUTER_FACTORY , PartitionedLoadBalancerFactory . class ) ; if ( routerFactory == null ) { routerFactory = new SenseiPartitionedLoadBalancerFactory ( <NUM_LIT> ) ; } senseiApp . setAttribute ( "<STR_LIT>" , routerFactory ) ; senseiApp . addEventListener ( new SenseiConfigServletContextListener ( ) ) ; senseiApp . addServlet ( senseiServletHolder , "<STR_LIT:/>" + SENSEI_CONTEXT_PATH + "<STR_LIT>" ) ; senseiApp . setResourceBase ( webappPath ) ; senseiApp . addServlet ( springServletHolder , "<STR_LIT>" ) ; senseiApp . addServlet ( jmxServletHolder , "<STR_LIT>" ) ; server . setHandler ( senseiApp ) ; server . setStopAtShutdown ( true ) ; return server ; } public static JSONObject loadSchema ( File confDir ) throws Exception { File jsonSchema = new File ( confDir , SCHEMA_FILE_JSON ) ; if ( jsonSchema . exists ( ) ) { InputStream is = new FileInputStream ( jsonSchema ) ; String json = IOUtils . toString ( is ) ; is . close ( ) ; return new JSONObject ( json ) ; } else { File xmlSchema = new File ( confDir , SCHEMA_FILE_XML ) ; if ( ! xmlSchema . exists ( ) ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setIgnoringComments ( true ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document schemaXml = db . parse ( xmlSchema ) ; schemaXml . getDocumentElement ( ) . normalize ( ) ; return SchemaConverter . convert ( schemaXml ) ; } } public static JSONObject loadSchema ( Resource confDir ) throws Exception { if ( confDir . createRelative ( SCHEMA_FILE_JSON ) . exists ( ) ) { String json = IOUtils . toString ( confDir . createRelative ( SCHEMA_FILE_JSON ) . getInputStream ( ) ) ; return new JSONObject ( json ) ; } else { if ( confDir . createRelative ( SCHEMA_FILE_XML ) . exists ( ) ) { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setIgnoringComments ( true ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document schemaXml = db . parse ( confDir . createRelative ( SCHEMA_FILE_XML ) . getInputStream ( ) ) ; schemaXml . getDocumentElement ( ) . normalize ( ) ; return SchemaConverter . convert ( schemaXml ) ; } else { throw new Exception ( "<STR_LIT>" ) ; } } } public SenseiServerBuilder ( File confDir ) throws Exception { this ( confDir , null ) ; } public SenseiServerBuilder ( File confDir , Map < String , Object > properties ) throws Exception { if ( properties != null ) { _senseiConfFile = null ; _senseiConf = new MapConfiguration ( properties ) ; ( ( MapConfiguration ) _senseiConf ) . setDelimiterParsingDisabled ( true ) ; } else { _senseiConfFile = new File ( confDir , SENSEI_PROPERTIES ) ; if ( ! _senseiConfFile . exists ( ) ) { throw new ConfigurationException ( "<STR_LIT>" + _senseiConfFile . getAbsolutePath ( ) + "<STR_LIT>" ) ; } _senseiConf = new PropertiesConfiguration ( ) ; ( ( PropertiesConfiguration ) _senseiConf ) . setDelimiterParsingDisabled ( true ) ; ( ( PropertiesConfiguration ) _senseiConf ) . load ( _senseiConfFile ) ; } pluginRegistry = SenseiPluginRegistry . build ( _senseiConf ) ; pluginRegistry . start ( ) ; processRelevanceFunctionPlugins ( pluginRegistry ) ; processRelevanceExternalObjectPlugins ( pluginRegistry ) ; _gateway = pluginRegistry . getBeanByFullPrefix ( SENSEI_GATEWAY , SenseiGateway . class ) ; _schemaDoc = loadSchema ( confDir ) ; _senseiSchema = SenseiSchema . build ( _schemaDoc ) ; } public SenseiServerBuilder ( Resource confDir , Map < String , Object > properties ) throws Exception { _senseiConfFile = null ; _senseiConf = new MapConfiguration ( properties ) ; ( ( MapConfiguration ) _senseiConf ) . setDelimiterParsingDisabled ( true ) ; pluginRegistry = SenseiPluginRegistry . build ( _senseiConf ) ; pluginRegistry . start ( ) ; processRelevanceFunctionPlugins ( pluginRegistry ) ; _gateway = pluginRegistry . getBeanByFullPrefix ( SENSEI_GATEWAY , SenseiGateway . class ) ; _schemaDoc = loadSchema ( confDir ) ; _senseiSchema = SenseiSchema . build ( _schemaDoc ) ; } private void processRelevanceFunctionPlugins ( SenseiPluginRegistry pluginRegistry ) { Map < String , CustomRelevanceFunctionFactory > map = pluginRegistry . getNamedBeansByType ( CustomRelevanceFunctionFactory . class ) ; Iterator < String > it = map . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { String name = it . next ( ) ; CustomRelevanceFunctionFactory crf = map . get ( name ) ; ModelStorage . injectPreloadedModel ( name , crf ) ; } } private void processRelevanceExternalObjectPlugins ( SenseiPluginRegistry pluginRegistry ) { List < RelevanceObjPlugin > relObjPlugins = pluginRegistry . getBeansByType ( RelevanceObjPlugin . class ) ; for ( RelevanceObjPlugin rop : relObjPlugins ) ExternalRelevanceDataStorage . putObj ( rop ) ; } static final Pattern PARTITION_PATTERN = Pattern . compile ( "<STR_LIT>" ) ; public static int [ ] buildPartitions ( String [ ] partitionArray ) throws ConfigurationException { IntSet partitions = new IntOpenHashSet ( ) ; try { for ( int i = <NUM_LIT:0> ; i < partitionArray . length ; ++ i ) { Matcher matcher = PARTITION_PATTERN . matcher ( partitionArray [ i ] ) ; if ( ! matcher . matches ( ) ) { throw new ConfigurationException ( "<STR_LIT>" + partitionArray [ i ] ) ; } String [ ] partitionRange = partitionArray [ i ] . split ( "<STR_LIT:->" ) ; int start = Integer . parseInt ( partitionRange [ <NUM_LIT:0> ] ) ; int end ; if ( partitionRange . length > <NUM_LIT:1> ) { end = Integer . parseInt ( partitionRange [ <NUM_LIT:1> ] ) ; if ( end < start ) { throw new ConfigurationException ( "<STR_LIT>" + partitionArray [ i ] ) ; } } else { end = start ; } for ( int k = start ; k <= end ; ++ k ) { partitions . add ( k ) ; } } } catch ( Exception e ) { throw new ConfigurationException ( "<STR_LIT>" + SENSEI_PROPERTIES + "<STR_LIT>" + PARTITIONS + "<STR_LIT:=>" + Arrays . toString ( partitionArray ) , e ) ; } int [ ] ret = partitions . toIntArray ( ) ; Arrays . sort ( ret ) ; return ret ; } public SenseiCore buildCore ( ) throws ConfigurationException { SenseiUncaughtExceptionHandler . setAsDefaultForAllThreads ( ) ; int nodeid = _senseiConf . getInt ( NODE_ID ) ; String partStr = _senseiConf . getString ( PARTITIONS ) ; String [ ] partitionArray = partStr . split ( "<STR_LIT>" ) ; int [ ] partitions = buildPartitions ( partitionArray ) ; logger . info ( "<STR_LIT>" + Arrays . toString ( partitions ) ) ; Analyzer analyzer = pluginRegistry . getBeanByFullPrefix ( SENSEI_INDEX_ANALYZER , Analyzer . class ) ; if ( analyzer == null ) { analyzer = new StandardAnalyzer ( Version . LUCENE_35 ) ; } Similarity similarity = pluginRegistry . getBeanByFullPrefix ( SENSEI_INDEX_SIMILARITY , Similarity . class ) ; if ( similarity == null ) { similarity = new DefaultSimilarity ( ) ; } ZoieConfig zoieConfig ; if ( _gateway != null ) { zoieConfig = new ZoieConfig ( _gateway . getVersionComparator ( ) ) ; } else { zoieConfig = new ZoieConfig ( ) ; } zoieConfig . setAnalyzer ( analyzer ) ; zoieConfig . setSimilarity ( similarity ) ; zoieConfig . setBatchSize ( _senseiConf . getInt ( SENSEI_INDEX_BATCH_SIZE , ZoieConfig . DEFAULT_SETTING_BATCHSIZE ) ) ; zoieConfig . setBatchDelay ( _senseiConf . getLong ( SENSEI_INDEX_BATCH_DELAY , ZoieConfig . DEFAULT_SETTING_BATCHDELAY ) ) ; zoieConfig . setMaxBatchSize ( _senseiConf . getInt ( SENSEI_INDEX_BATCH_MAXSIZE , ZoieConfig . DEFAULT_MAX_BATCH_SIZE ) ) ; zoieConfig . setRtIndexing ( _senseiConf . getBoolean ( SENSEI_INDEX_REALTIME , ZoieConfig . DEFAULT_SETTING_REALTIME ) ) ; zoieConfig . setSkipBadRecord ( _senseiConf . getBoolean ( SENSEI_SKIP_BAD_RECORDS , false ) ) ; int delay = _senseiConf . getInt ( SENSEI_INDEX_FRESHNESS , <NUM_LIT:10> ) ; ReaderCacheFactory readercachefactory ; if ( delay > <NUM_LIT:0> ) { readercachefactory = DefaultReaderCache . FACTORY ; zoieConfig . setFreshness ( delay * <NUM_LIT:1000> ) ; } else { readercachefactory = SimpleReaderCache . FACTORY ; } zoieConfig . setReadercachefactory ( readercachefactory ) ; ShardingStrategy strategy = pluginRegistry . getBeanByFullPrefix ( SENSEI_SHARDING_STRATEGY , ShardingStrategy . class ) ; if ( strategy == null ) { strategy = new ShardingStrategy . FieldModShardingStrategy ( _senseiSchema . getUidField ( ) ) ; } pluggableSearchEngineManager = new PluggableSearchEngineManager ( ) ; pluggableSearchEngineManager . init ( _senseiConf . getString ( SENSEI_INDEX_DIR ) , nodeid , _senseiSchema , zoieConfig . getVersionComparator ( ) , pluginRegistry , strategy ) ; List < FacetHandler < ? > > facetHandlers = new LinkedList < FacetHandler < ? > > ( ) ; List < RuntimeFacetHandlerFactory < ? , ? > > runtimeFacetHandlerFactories = new LinkedList < RuntimeFacetHandlerFactory < ? , ? > > ( ) ; SenseiSystemInfo sysInfo = null ; try { sysInfo = SenseiFacetHandlerBuilder . buildFacets ( _schemaDoc , pluginRegistry , facetHandlers , runtimeFacetHandlerFactories , pluggableSearchEngineManager ) ; } catch ( JSONException jse ) { throw new ConfigurationException ( jse . getMessage ( ) , jse ) ; } if ( sysInfo != null ) { sysInfo . setSchema ( _schemaDoc . toString ( ) ) ; try { List < SenseiSystemInfo . SenseiNodeInfo > clusterInfo = new ArrayList ( <NUM_LIT:1> ) ; String addr = NetUtil . getHostAddress ( ) ; clusterInfo . add ( new SenseiSystemInfo . SenseiNodeInfo ( nodeid , partitions , String . format ( "<STR_LIT>" , addr , _senseiConf . getInt ( SERVER_PORT ) ) , String . format ( "<STR_LIT>" , addr , _senseiConf . getInt ( SERVER_BROKER_PORT ) ) ) ) ; sysInfo . setClusterInfo ( clusterInfo ) ; } catch ( Exception e ) { throw new ConfigurationException ( e . getMessage ( ) , e ) ; } } ZoieIndexableInterpreter interpreter = pluginRegistry . getBeanByFullPrefix ( SENSEI_INDEX_INTERPRETER , ZoieIndexableInterpreter . class ) ; if ( interpreter == null ) { DefaultJsonSchemaInterpreter defaultInterpreter = new DefaultJsonSchemaInterpreter ( _senseiSchema , pluggableSearchEngineManager ) ; interpreter = defaultInterpreter ; CustomIndexingPipeline customIndexingPipeline = pluginRegistry . getBeanByFullPrefix ( SENSEI_INDEX_CUSTOM , CustomIndexingPipeline . class ) ; if ( customIndexingPipeline != null ) { try { defaultInterpreter . setCustomIndexingPipeline ( customIndexingPipeline ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } } } SenseiZoieFactory < ? > zoieSystemFactory = constructZoieFactory ( zoieConfig , facetHandlers , runtimeFacetHandlerFactories , interpreter ) ; SenseiIndexingManager < ? > indexingManager = pluginRegistry . getBeanByFullPrefix ( SENSEI_INDEX_MANAGER , SenseiIndexingManager . class ) ; if ( indexingManager == null ) { indexingManager = new DefaultStreamingIndexingManager ( _senseiSchema , _senseiConf , pluginRegistry , _gateway , strategy , pluggableSearchEngineManager ) ; } SenseiQueryBuilderFactory queryBuilderFactory = pluginRegistry . getBeanByFullPrefix ( SENSEI_QUERY_BUILDER_FACTORY , SenseiQueryBuilderFactory . class ) ; if ( queryBuilderFactory == null ) { QueryParser queryParser = new QueryParser ( Version . LUCENE_35 , "<STR_LIT>" , analyzer ) ; queryBuilderFactory = new DefaultJsonQueryBuilderFactory ( queryParser ) ; } SenseiCore senseiCore = new SenseiCore ( nodeid , partitions , zoieSystemFactory , indexingManager , queryBuilderFactory ) ; senseiCore . setSystemInfo ( sysInfo ) ; SenseiIndexPruner indexPruner = pluginRegistry . getBeanByFullPrefix ( SENSEI_INDEX_PRUNER , SenseiIndexPruner . class ) ; if ( indexPruner != null ) { senseiCore . setIndexPruner ( indexPruner ) ; } if ( pluggableSearchEngineManager != null ) { senseiCore . setPluggableSearchEngineManager ( pluggableSearchEngineManager ) ; } return senseiCore ; } @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) private SenseiZoieFactory < ? > constructZoieFactory ( ZoieConfig zoieConfig , List < FacetHandler < ? > > facetHandlers , List < RuntimeFacetHandlerFactory < ? , ? > > runtimeFacetHandlerFactories , ZoieIndexableInterpreter interpreter ) throws ConfigurationException { String indexerType = _senseiConf . getString ( SENSEI_INDEXER_TYPE , "<STR_LIT>" ) ; SenseiIndexReaderDecorator decorator = new SenseiIndexReaderDecorator ( facetHandlers , runtimeFacetHandlerFactories ) ; File idxDir = new File ( _senseiConf . getString ( SENSEI_INDEX_DIR ) ) ; SenseiZoieFactory < ? > zoieSystemFactory = null ; DIRECTORY_MODE dirMode ; String modeValue = _senseiConf . getString ( SENSEI_INDEXER_MODE , "<STR_LIT>" ) ; if ( "<STR_LIT>" . equalsIgnoreCase ( modeValue ) ) { dirMode = DIRECTORY_MODE . SIMPLE ; } else if ( "<STR_LIT>" . equalsIgnoreCase ( modeValue ) ) { dirMode = DIRECTORY_MODE . NIO ; } else if ( "<STR_LIT>" . equalsIgnoreCase ( modeValue ) ) { dirMode = DIRECTORY_MODE . MMAP ; } else { logger . error ( "<STR_LIT>" + modeValue + "<STR_LIT>" ) ; dirMode = DIRECTORY_MODE . SIMPLE ; } if ( SENSEI_INDEXER_TYPE_ZOIE . equals ( indexerType ) ) { SenseiZoieSystemFactory senseiZoieFactory = new SenseiZoieSystemFactory ( idxDir , dirMode , interpreter , decorator , zoieConfig ) ; int retentionDays = _senseiConf . getInt ( SENSEI_ZOIE_RETENTION_DAYS , - <NUM_LIT:1> ) ; if ( retentionDays > <NUM_LIT:0> ) { RetentionFilterFactory retentionFilterFactory = pluginRegistry . getBeanByFullPrefix ( SENSEI_ZOIE_RETENTION_CLASS , RetentionFilterFactory . class ) ; Filter purgeFilter = null ; if ( retentionFilterFactory != null ) { purgeFilter = retentionFilterFactory . buildRetentionFilter ( retentionDays ) ; } else { String timeColumn = _senseiConf . getString ( SENSEI_ZOIE_RETENTION_COLUMN , null ) ; if ( timeColumn == null ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } String unitString = _senseiConf . getString ( SENSEI_ZOIE_RETENTION_TIMEUNIT , "<STR_LIT>" ) ; TimeUnit unit = TimeUnit . valueOf ( unitString . toUpperCase ( ) ) ; if ( unit == null ) { throw new ConfigurationException ( "<STR_LIT>" + unitString ) ; } purgeFilter = new TimeRetentionFilter ( timeColumn , retentionDays , unit ) ; } if ( purgeFilter != null && pluggableSearchEngineManager != null ) { purgeFilter = new PurgeFilterWrapper ( purgeFilter , pluggableSearchEngineManager ) ; } senseiZoieFactory . setPurgeFilter ( purgeFilter ) ; } zoieSystemFactory = senseiZoieFactory ; } else if ( SENSEI_INDEXER_TYPE_HOURGLASS . equals ( indexerType ) ) { String schedule = _senseiConf . getString ( SENSEI_HOURGLASS_SCHEDULE , "<STR_LIT>" ) ; int trimThreshold = _senseiConf . getInt ( SENSEI_HOURGLASS_TRIMTHRESHOLD , <NUM_LIT> ) ; String frequencyString = _senseiConf . getString ( SENSEI_HOURGLASS_FREQUENCY , "<STR_LIT>" ) ; FREQUENCY frequency ; if ( SENSEI_HOURGLASS_FREQUENCY_MIN . equals ( frequencyString ) ) { frequency = FREQUENCY . MINUTELY ; } else if ( SENSEI_HOURGLASS_FREQUENCY_HOUR . equals ( frequencyString ) ) { frequency = FREQUENCY . HOURLY ; } else if ( SENSEI_HOURGLASS_FREQUENCY_DAY . equals ( frequencyString ) ) { frequency = FREQUENCY . DAILY ; } else { throw new ConfigurationException ( "<STR_LIT>" + frequencyString ) ; } boolean appendOnly = _senseiConf . getBoolean ( SENSEI_HOURGLASS_APPENDONLY , true ) ; zoieSystemFactory = new SenseiHourglassFactory ( idxDir , dirMode , interpreter , decorator , zoieConfig , schedule , appendOnly , trimThreshold , frequency , pluggableSearchEngineManager != null ? Arrays . asList ( pluggableSearchEngineManager ) : Collections . EMPTY_LIST ) ; } else { ZoieFactoryFactory zoieFactoryFactory = pluginRegistry . getBeanByFullPrefix ( indexerType , ZoieFactoryFactory . class ) ; if ( zoieFactoryFactory == null ) { throw new ConfigurationException ( indexerType + "<STR_LIT>" ) ; } zoieSystemFactory = zoieFactoryFactory . getZoieFactory ( idxDir , interpreter , decorator , zoieConfig ) ; } String indexerCopier = _senseiConf . getString ( SENSEI_INDEXER_COPIER ) ; IndexCopier copier = pluginRegistry . getBeanByFullPrefix ( SENSEI_INDEXER_COPIER , IndexCopier . class ) ; if ( copier != null ) { zoieSystemFactory = new SenseiPairFactory ( idxDir , dirMode , copier , interpreter , decorator , zoieConfig , zoieSystemFactory ) ; } else if ( SENSEI_INDEXER_COPIER_HDFS . equals ( indexerCopier ) ) { zoieSystemFactory = new SenseiPairFactory ( idxDir , dirMode , new HDFSIndexCopier ( ) , interpreter , decorator , zoieConfig , zoieSystemFactory ) ; } else { } return zoieSystemFactory ; } public Comparator < String > getVersionComparator ( ) { return _gateway . getVersionComparator ( ) ; } public SenseiServer buildServer ( ) throws ConfigurationException { int port = _senseiConf . getInt ( SERVER_PORT ) ; JmxSenseiMBeanServer . registerCustomMBeanServer ( ) ; ClusterClient clusterClient = buildClusterClient ( ) ; NetworkServer networkServer = buildNetworkServer ( _senseiConf , clusterClient ) ; SenseiCore core = buildCore ( ) ; List < AbstractSenseiCoreService < AbstractSenseiRequest , AbstractSenseiResult > > svcList = ( List ) pluginRegistry . resolveBeansByListKey ( SENSEI_PLUGIN_SVCS , AbstractSenseiCoreService . class ) ; return new SenseiServer ( port , networkServer , clusterClient , core , svcList , pluginRegistry ) ; } } </s>
<s> package com . senseidb . conf ; import java . io . File ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import org . apache . commons . configuration . ConfigurationException ; import org . apache . log4j . Logger ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; public class SchemaConverter { private static Logger logger = Logger . getLogger ( SchemaConverter . class ) ; static public JSONObject convert ( Document schemaDoc ) throws ConfigurationException , JSONException { JSONObject jsonObj = new JSONObject ( ) ; JSONObject tableObj = new JSONObject ( ) ; jsonObj . put ( "<STR_LIT>" , tableObj ) ; NodeList tables = schemaDoc . getElementsByTagName ( "<STR_LIT>" ) ; if ( tables != null && tables . getLength ( ) > <NUM_LIT:0> ) { Element tableElem = ( Element ) tables . item ( <NUM_LIT:0> ) ; tableObj . put ( "<STR_LIT>" , tableElem . getAttribute ( "<STR_LIT>" ) ) ; String deleteField = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( deleteField != null ) tableObj . put ( "<STR_LIT>" , deleteField ) ; String skipField = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( skipField != null ) tableObj . put ( "<STR_LIT>" , skipField ) ; String srcDataStore = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( srcDataStore != null ) tableObj . put ( "<STR_LIT>" , srcDataStore ) ; String srcDatafield = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( srcDatafield == null || srcDatafield . length ( ) == <NUM_LIT:0> ) srcDatafield = "<STR_LIT>" ; tableObj . put ( "<STR_LIT>" , srcDatafield ) ; String compress = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( compress != null && "<STR_LIT:false>" . equals ( compress ) ) tableObj . put ( "<STR_LIT>" , false ) ; else tableObj . put ( "<STR_LIT>" , true ) ; NodeList columns = tableElem . getElementsByTagName ( "<STR_LIT>" ) ; JSONArray columnArray = new JSONArray ( ) ; tableObj . put ( "<STR_LIT>" , columnArray ) ; for ( int i = <NUM_LIT:0> ; i < columns . getLength ( ) ; ++ i ) { try { Element column = ( Element ) columns . item ( i ) ; JSONObject columnObj = new JSONObject ( ) ; columnArray . put ( columnObj ) ; String n = column . getAttribute ( "<STR_LIT:name>" ) ; String t = column . getAttribute ( "<STR_LIT:type>" ) ; String frm = column . getAttribute ( "<STR_LIT>" ) ; columnObj . put ( "<STR_LIT:name>" , n ) ; columnObj . put ( "<STR_LIT:type>" , t ) ; columnObj . put ( "<STR_LIT>" , frm ) ; columnObj . put ( "<STR_LIT>" , Boolean . parseBoolean ( column . getAttribute ( "<STR_LIT>" ) ) ) ; columnObj . put ( "<STR_LIT>" , Boolean . parseBoolean ( column . getAttribute ( "<STR_LIT>" ) ) ) ; String delimString = column . getAttribute ( "<STR_LIT>" ) ; if ( delimString != null && delimString . trim ( ) . length ( ) > <NUM_LIT:0> ) { columnObj . put ( "<STR_LIT>" , delimString ) ; } String f = "<STR_LIT>" ; try { f = column . getAttribute ( "<STR_LIT>" ) ; } catch ( Exception ex ) { logger . error ( ex . getMessage ( ) , ex ) ; } if ( ! f . isEmpty ( ) ) columnObj . put ( "<STR_LIT>" , f ) ; String idxString = column . getAttribute ( "<STR_LIT:index>" ) ; if ( idxString != null ) { columnObj . put ( "<STR_LIT:index>" , idxString ) ; } String storeString = column . getAttribute ( "<STR_LIT>" ) ; if ( storeString != null ) { columnObj . put ( "<STR_LIT>" , storeString ) ; } String tvString = column . getAttribute ( "<STR_LIT>" ) ; if ( tvString != null ) { columnObj . put ( "<STR_LIT>" , tvString ) ; } } catch ( Exception e ) { throw new ConfigurationException ( "<STR_LIT>" + columns . item ( i ) , e ) ; } } } NodeList facets = schemaDoc . getElementsByTagName ( "<STR_LIT>" ) ; JSONArray facetArray = new JSONArray ( ) ; jsonObj . put ( "<STR_LIT>" , facetArray ) ; for ( int i = <NUM_LIT:0> ; i < facets . getLength ( ) ; ++ i ) { try { Element facet = ( Element ) facets . item ( i ) ; JSONObject facetObj = new JSONObject ( ) ; facetArray . put ( facetObj ) ; facetObj . put ( "<STR_LIT:name>" , facet . getAttribute ( "<STR_LIT:name>" ) ) ; facetObj . put ( "<STR_LIT:type>" , facet . getAttribute ( "<STR_LIT:type>" ) ) ; String depends = facet . getAttribute ( "<STR_LIT>" ) ; if ( depends != null ) { String [ ] dependsList = depends . split ( "<STR_LIT:U+002C>" ) ; JSONArray dependsArr = new JSONArray ( ) ; for ( String dependName : dependsList ) { if ( dependName != null ) { dependName = dependName . trim ( ) ; if ( dependName . length ( ) != <NUM_LIT:0> ) dependsArr . put ( dependName ) ; } } facetObj . put ( "<STR_LIT>" , dependsArr ) ; } String column = facet . getAttribute ( "<STR_LIT>" ) ; if ( column != null && column . length ( ) > <NUM_LIT:0> ) { facetObj . put ( "<STR_LIT>" , column ) ; } String dynamic = facet . getAttribute ( "<STR_LIT>" ) ; if ( dynamic != null ) { facetObj . put ( "<STR_LIT>" , dynamic ) ; } NodeList paramList = facet . getElementsByTagName ( "<STR_LIT>" ) ; if ( paramList != null ) { JSONArray params = new JSONArray ( ) ; facetObj . put ( "<STR_LIT>" , params ) ; for ( int j = <NUM_LIT:0> ; j < paramList . getLength ( ) ; ++ j ) { Element param = ( Element ) paramList . item ( j ) ; String paramName = param . getAttribute ( "<STR_LIT:name>" ) ; String paramValue = param . getAttribute ( "<STR_LIT:value>" ) ; JSONObject paramObj = new JSONObject ( ) ; paramObj . put ( "<STR_LIT:name>" , paramName ) ; paramObj . put ( "<STR_LIT:value>" , paramValue ) ; params . put ( paramObj ) ; } } } catch ( Exception e ) { throw new ConfigurationException ( "<STR_LIT>" + facets . item ( i ) , e ) ; } } return jsonObj ; } public static void main ( String [ ] args ) throws Exception { File xmlSchema = new File ( "<STR_LIT>" ) ; if ( ! xmlSchema . exists ( ) ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setIgnoringComments ( true ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document schemaXml = db . parse ( xmlSchema ) ; schemaXml . getDocumentElement ( ) . normalize ( ) ; JSONObject json = SchemaConverter . convert ( schemaXml ) ; System . out . println ( json . toString ( <NUM_LIT:4> ) ) ; } } </s>
<s> package com . senseidb . conf ; import java . text . DecimalFormat ; import java . text . DecimalFormatSymbols ; import java . text . Format ; import java . text . SimpleDateFormat ; import java . util . ArrayList ; import java . util . Date ; import java . util . HashMap ; import java . util . HashSet ; import java . util . List ; import java . util . Locale ; import java . util . Map ; import java . util . Set ; import org . apache . commons . configuration . ConfigurationException ; import org . apache . log4j . Logger ; import org . apache . lucene . document . Field . Index ; import org . apache . lucene . document . Field . Store ; import org . apache . lucene . document . Field . TermVector ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; import com . senseidb . indexing . DefaultSenseiInterpreter ; import com . senseidb . indexing . DefaultSenseiInterpreter . IndexSpec ; import com . senseidb . indexing . MetaType ; public class SenseiSchema { public static final String SRC_DATA_FIELD_NAME = "<STR_LIT>" ; public static final String SRC_DATA_COMPRESSED_FIELD_NAME = "<STR_LIT>" ; public static final String EVENT_TYPE_FIELD = "<STR_LIT:type>" ; public static final String EVENT_FIELD = "<STR_LIT:data>" ; public static final String EVENT_TYPE_ADD = "<STR_LIT>" ; public static final String EVENT_TYPE_UPDATE = "<STR_LIT>" ; public static final String EVENT_TYPE_DELETE = "<STR_LIT>" ; public static final String EVENT_TYPE_SKIP = "<STR_LIT>" ; private static Logger logger = Logger . getLogger ( SenseiSchema . class ) ; private String _uidField ; private String _deleteField ; private String _skipField ; private String _srcDataStore ; private String _srcDataField ; private boolean _compressSrcData ; private List < FacetDefinition > facets = new ArrayList < FacetDefinition > ( ) ; public static class FieldDefinition { public Format formatter ; public boolean isMeta ; public IndexSpec textIndexSpec ; public String fromField ; public boolean isMulti ; public boolean isActivity ; public String delim = "<STR_LIT:U+002C>" ; public Class type = null ; public String name ; } public static class FacetDefinition { public String name ; public String type ; public String column ; public Boolean dynamic ; public Map < String , List < String > > params ; public Set < String > dependSet = new HashSet < String > ( ) ; public static FacetDefinition valueOf ( JSONObject facet ) { try { FacetDefinition ret = new FacetDefinition ( ) ; ret . name = facet . getString ( "<STR_LIT:name>" ) ; ret . type = facet . getString ( "<STR_LIT:type>" ) ; ret . column = facet . optString ( "<STR_LIT>" , ret . name ) ; JSONArray depends = facet . optJSONArray ( "<STR_LIT>" ) ; if ( depends != null ) { for ( int i = <NUM_LIT:0> ; i < depends . length ( ) ; ++ i ) { String dep = depends . getString ( i ) . trim ( ) ; if ( ! dep . isEmpty ( ) ) { ret . dependSet . add ( dep ) ; } } } JSONArray paramList = facet . optJSONArray ( "<STR_LIT>" ) ; ret . params = SenseiFacetHandlerBuilder . parseParams ( paramList ) ; return ret ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } } private SenseiSchema ( ) { } public String getUidField ( ) { return _uidField ; } public String getDeleteField ( ) { return _deleteField ; } public String getSkipField ( ) { return _skipField ; } public String getSrcDataField ( ) { return _srcDataField ; } public String getSrcDataStore ( ) { return _srcDataStore ; } public boolean isCompressSrcData ( ) { return _compressSrcData ; } public void setCompressSrcData ( boolean _compressSrcData ) { this . _compressSrcData = _compressSrcData ; } public Map < String , FieldDefinition > getFieldDefMap ( ) { return _fieldDefMap ; } private Map < String , FieldDefinition > _fieldDefMap ; private static JSONObject schemaObj ; public static SenseiSchema build ( JSONObject schemaObj ) throws JSONException , ConfigurationException { SenseiSchema schema = new SenseiSchema ( ) ; schema . setSchemaObj ( schemaObj ) ; schema . _fieldDefMap = new HashMap < String , FieldDefinition > ( ) ; JSONObject tableElem = schemaObj . optJSONObject ( "<STR_LIT>" ) ; if ( tableElem == null ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } schema . _uidField = tableElem . getString ( "<STR_LIT>" ) ; schema . _deleteField = tableElem . optString ( "<STR_LIT>" , "<STR_LIT>" ) ; schema . _skipField = tableElem . optString ( "<STR_LIT>" , "<STR_LIT>" ) ; schema . _srcDataStore = tableElem . optString ( "<STR_LIT>" , "<STR_LIT>" ) ; schema . _srcDataField = tableElem . optString ( "<STR_LIT>" , "<STR_LIT>" ) ; schema . _compressSrcData = tableElem . optBoolean ( "<STR_LIT>" , true ) ; JSONArray columns = tableElem . optJSONArray ( "<STR_LIT>" ) ; int count = <NUM_LIT:0> ; if ( columns != null ) { count = columns . length ( ) ; } for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { JSONObject column = columns . getJSONObject ( i ) ; try { String n = column . getString ( "<STR_LIT:name>" ) ; String t = column . getString ( "<STR_LIT:type>" ) ; String frm = column . optString ( "<STR_LIT>" ) ; FieldDefinition fdef = new FieldDefinition ( ) ; fdef . formatter = null ; fdef . fromField = frm . length ( ) > <NUM_LIT:0> ? frm : n ; fdef . isMeta = true ; fdef . isMulti = column . optBoolean ( "<STR_LIT>" ) ; fdef . isActivity = column . optBoolean ( "<STR_LIT>" ) ; fdef . name = n ; String delimString = column . optString ( "<STR_LIT>" ) ; if ( delimString != null && delimString . trim ( ) . length ( ) > <NUM_LIT:0> ) { fdef . delim = delimString ; } schema . _fieldDefMap . put ( n , fdef ) ; if ( t . equals ( "<STR_LIT:int>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( int . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = int . class ; } else if ( t . equals ( "<STR_LIT>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( short . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = int . class ; } else if ( t . equals ( "<STR_LIT:long>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( long . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = long . class ; } else if ( t . equals ( "<STR_LIT:float>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( float . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = double . class ; } else if ( t . equals ( "<STR_LIT:double>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( double . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = double . class ; } else if ( t . equals ( "<STR_LIT>" ) ) { fdef . formatter = null ; } else if ( t . equals ( "<STR_LIT:string>" ) ) { fdef . formatter = null ; } else if ( t . equals ( "<STR_LIT:boolean>" ) ) { fdef . formatter = null ; } else if ( t . equals ( "<STR_LIT:date>" ) ) { String f = "<STR_LIT>" ; try { f = column . optString ( "<STR_LIT>" ) ; } catch ( Exception ex ) { logger . error ( ex . getMessage ( ) , ex ) ; } if ( f . isEmpty ( ) ) throw new ConfigurationException ( "<STR_LIT>" ) ; fdef . formatter = new SimpleDateFormat ( f ) ; fdef . type = Date . class ; } else if ( t . equals ( "<STR_LIT:text>" ) ) { fdef . isMeta = false ; String idxString = column . optString ( "<STR_LIT:index>" , null ) ; String storeString = column . optString ( "<STR_LIT>" , null ) ; String tvString = column . optString ( "<STR_LIT>" , null ) ; Index idx = idxString == null ? Index . ANALYZED : DefaultSenseiInterpreter . INDEX_VAL_MAP . get ( idxString . toUpperCase ( ) ) ; Store store = storeString == null ? Store . NO : DefaultSenseiInterpreter . STORE_VAL_MAP . get ( storeString . toUpperCase ( ) ) ; TermVector tv = tvString == null ? TermVector . NO : DefaultSenseiInterpreter . TV_VAL_MAP . get ( tvString . toUpperCase ( ) ) ; if ( idx == null || store == null || tv == null ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } IndexSpec indexingSpec = new IndexSpec ( ) ; indexingSpec . store = store ; indexingSpec . index = idx ; indexingSpec . tv = tv ; fdef . textIndexSpec = indexingSpec ; } } catch ( Exception e ) { throw new ConfigurationException ( "<STR_LIT>" + column , e ) ; } } JSONArray facetsList = schemaObj . optJSONArray ( "<STR_LIT>" ) ; if ( facetsList != null ) { for ( int i = <NUM_LIT:0> ; i < facetsList . length ( ) ; i ++ ) { JSONObject facet = facetsList . optJSONObject ( i ) ; if ( facet != null ) { schema . facets . add ( FacetDefinition . valueOf ( facet ) ) ; } } } return schema ; } @ Deprecated public static SenseiSchema build ( Document schemaDoc ) throws ConfigurationException { SenseiSchema schema = new SenseiSchema ( ) ; schema . _fieldDefMap = new HashMap < String , FieldDefinition > ( ) ; NodeList tables = schemaDoc . getElementsByTagName ( "<STR_LIT>" ) ; if ( tables == null || tables . getLength ( ) == <NUM_LIT:0> ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } if ( tables . getLength ( ) > <NUM_LIT:1> ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } Element tableElem = ( Element ) tables . item ( <NUM_LIT:0> ) ; schema . _uidField = tableElem . getAttribute ( "<STR_LIT>" ) ; schema . _deleteField = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( schema . _deleteField == null ) schema . _deleteField = "<STR_LIT>" ; schema . _skipField = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( schema . _skipField == null ) schema . _skipField = "<STR_LIT>" ; schema . _srcDataStore = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( schema . _srcDataStore == null ) schema . _srcDataStore = "<STR_LIT>" ; schema . _srcDataField = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( schema . _srcDataField == null || schema . _srcDataField . length ( ) == <NUM_LIT:0> ) schema . _srcDataField = "<STR_LIT>" ; schema . _compressSrcData = true ; String compress = tableElem . getAttribute ( "<STR_LIT>" ) ; if ( compress != null && "<STR_LIT:false>" . equals ( compress ) ) schema . _compressSrcData = false ; NodeList columns = tableElem . getElementsByTagName ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < columns . getLength ( ) ; ++ i ) { try { Element column = ( Element ) columns . item ( i ) ; String n = column . getAttribute ( "<STR_LIT:name>" ) ; String t = column . getAttribute ( "<STR_LIT:type>" ) ; String frm = column . getAttribute ( "<STR_LIT>" ) ; FieldDefinition fdef = new FieldDefinition ( ) ; fdef . formatter = null ; fdef . fromField = frm . length ( ) > <NUM_LIT:0> ? frm : n ; fdef . isMeta = true ; fdef . isMulti = false ; String isMultiString = column . getAttribute ( "<STR_LIT>" ) ; if ( isMultiString != null && isMultiString . trim ( ) . length ( ) > <NUM_LIT:0> ) { fdef . isMulti = Boolean . parseBoolean ( isMultiString ) ; } String isActivityString = column . getAttribute ( "<STR_LIT>" ) ; if ( isActivityString != null && isActivityString . trim ( ) . length ( ) > <NUM_LIT:0> ) { fdef . isActivity = Boolean . parseBoolean ( isActivityString ) ; } String delimString = column . getAttribute ( "<STR_LIT>" ) ; if ( delimString != null && delimString . trim ( ) . length ( ) > <NUM_LIT:0> ) { fdef . delim = delimString ; } schema . _fieldDefMap . put ( n , fdef ) ; if ( t . equals ( "<STR_LIT:int>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( int . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = int . class ; } else if ( t . equals ( "<STR_LIT>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( short . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = int . class ; } else if ( t . equals ( "<STR_LIT:long>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( long . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = long . class ; } else if ( t . equals ( "<STR_LIT:float>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( float . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = double . class ; } else if ( t . equals ( "<STR_LIT:double>" ) ) { MetaType metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( double . class ) ; String formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; fdef . formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; fdef . type = double . class ; } else if ( t . equals ( "<STR_LIT>" ) ) { fdef . formatter = null ; } else if ( t . equals ( "<STR_LIT:string>" ) ) { fdef . formatter = null ; } else if ( t . equals ( "<STR_LIT:boolean>" ) ) { fdef . formatter = null ; } else if ( t . equals ( "<STR_LIT:date>" ) ) { String f = "<STR_LIT>" ; try { f = column . getAttribute ( "<STR_LIT>" ) ; } catch ( Exception ex ) { logger . error ( ex . getMessage ( ) , ex ) ; } if ( f . isEmpty ( ) ) throw new ConfigurationException ( "<STR_LIT>" ) ; fdef . formatter = new SimpleDateFormat ( f ) ; fdef . type = Date . class ; } else if ( t . equals ( "<STR_LIT:text>" ) ) { fdef . isMeta = false ; String idxString = column . getAttribute ( "<STR_LIT:index>" ) ; String storeString = column . getAttribute ( "<STR_LIT>" ) ; String tvString = column . getAttribute ( "<STR_LIT>" ) ; Index idx = idxString == null ? Index . ANALYZED : DefaultSenseiInterpreter . INDEX_VAL_MAP . get ( idxString . toUpperCase ( ) ) ; Store store = storeString == null ? Store . NO : DefaultSenseiInterpreter . STORE_VAL_MAP . get ( storeString . toUpperCase ( ) ) ; TermVector tv = tvString == null ? TermVector . NO : DefaultSenseiInterpreter . TV_VAL_MAP . get ( tvString . toUpperCase ( ) ) ; if ( idx == null || store == null || tv == null ) { throw new ConfigurationException ( "<STR_LIT>" ) ; } IndexSpec indexingSpec = new IndexSpec ( ) ; indexingSpec . store = store ; indexingSpec . index = idx ; indexingSpec . tv = tv ; fdef . textIndexSpec = indexingSpec ; } } catch ( Exception e ) { throw new ConfigurationException ( "<STR_LIT>" + columns . item ( i ) , e ) ; } } return schema ; } public List < FacetDefinition > getFacets ( ) { return facets ; } public JSONObject getSchemaObj ( ) { return schemaObj ; } public void setSchemaObj ( JSONObject schemaObj ) { SenseiSchema . schemaObj = schemaObj ; } } </s>
<s> package com . senseidb . jmx ; import java . io . ObjectInputStream ; import java . util . Set ; import javax . management . Attribute ; import javax . management . AttributeList ; import javax . management . AttributeNotFoundException ; import javax . management . InstanceAlreadyExistsException ; import javax . management . InstanceNotFoundException ; import javax . management . IntrospectionException ; import javax . management . InvalidAttributeValueException ; import javax . management . ListenerNotFoundException ; import javax . management . MBeanException ; import javax . management . MBeanInfo ; import javax . management . MBeanRegistrationException ; import javax . management . MBeanServer ; import javax . management . NotCompliantMBeanException ; import javax . management . NotificationFilter ; import javax . management . NotificationListener ; import javax . management . ObjectInstance ; import javax . management . ObjectName ; import javax . management . OperationsException ; import javax . management . QueryExp ; import javax . management . ReflectionException ; import javax . management . loading . ClassLoaderRepository ; public class MockJMXServer implements MBeanServer { @ Override public ObjectInstance createMBean ( String className , ObjectName name ) throws ReflectionException , InstanceAlreadyExistsException , MBeanRegistrationException , MBeanException , NotCompliantMBeanException { return null ; } @ Override public ObjectInstance createMBean ( String className , ObjectName name , ObjectName loaderName ) throws ReflectionException , InstanceAlreadyExistsException , MBeanRegistrationException , MBeanException , NotCompliantMBeanException , InstanceNotFoundException { return null ; } @ Override public ObjectInstance createMBean ( String className , ObjectName name , Object [ ] params , String [ ] signature ) throws ReflectionException , InstanceAlreadyExistsException , MBeanRegistrationException , MBeanException , NotCompliantMBeanException { return null ; } @ Override public ObjectInstance createMBean ( String className , ObjectName name , ObjectName loaderName , Object [ ] params , String [ ] signature ) throws ReflectionException , InstanceAlreadyExistsException , MBeanRegistrationException , MBeanException , NotCompliantMBeanException , InstanceNotFoundException { return null ; } @ Override public ObjectInstance registerMBean ( Object object , ObjectName name ) throws InstanceAlreadyExistsException , MBeanRegistrationException , NotCompliantMBeanException { return null ; } @ Override public void unregisterMBean ( ObjectName name ) throws InstanceNotFoundException , MBeanRegistrationException { } @ Override public ObjectInstance getObjectInstance ( ObjectName name ) throws InstanceNotFoundException { return null ; } @ Override public Set < ObjectInstance > queryMBeans ( ObjectName name , QueryExp query ) { return null ; } @ Override public Set < ObjectName > queryNames ( ObjectName name , QueryExp query ) { return null ; } @ Override public boolean isRegistered ( ObjectName name ) { return false ; } @ Override public Integer getMBeanCount ( ) { return null ; } @ Override public Object getAttribute ( ObjectName name , String attribute ) throws MBeanException , AttributeNotFoundException , InstanceNotFoundException , ReflectionException { return null ; } @ Override public AttributeList getAttributes ( ObjectName name , String [ ] attributes ) throws InstanceNotFoundException , ReflectionException { return null ; } @ Override public void setAttribute ( ObjectName name , Attribute attribute ) throws InstanceNotFoundException , AttributeNotFoundException , InvalidAttributeValueException , MBeanException , ReflectionException { } @ Override public AttributeList setAttributes ( ObjectName name , AttributeList attributes ) throws InstanceNotFoundException , ReflectionException { return null ; } @ Override public Object invoke ( ObjectName name , String operationName , Object [ ] params , String [ ] signature ) throws InstanceNotFoundException , MBeanException , ReflectionException { return null ; } @ Override public String getDefaultDomain ( ) { return null ; } @ Override public String [ ] getDomains ( ) { return null ; } @ Override public void addNotificationListener ( ObjectName name , NotificationListener listener , NotificationFilter filter , Object handback ) throws InstanceNotFoundException { } @ Override public void addNotificationListener ( ObjectName name , ObjectName listener , NotificationFilter filter , Object handback ) throws InstanceNotFoundException { } @ Override public void removeNotificationListener ( ObjectName name , ObjectName listener ) throws InstanceNotFoundException , ListenerNotFoundException { } @ Override public void removeNotificationListener ( ObjectName name , ObjectName listener , NotificationFilter filter , Object handback ) throws InstanceNotFoundException , ListenerNotFoundException { } @ Override public void removeNotificationListener ( ObjectName name , NotificationListener listener ) throws InstanceNotFoundException , ListenerNotFoundException { } @ Override public void removeNotificationListener ( ObjectName name , NotificationListener listener , NotificationFilter filter , Object handback ) throws InstanceNotFoundException , ListenerNotFoundException { } @ Override public MBeanInfo getMBeanInfo ( ObjectName name ) throws InstanceNotFoundException , IntrospectionException , ReflectionException { return null ; } @ Override public boolean isInstanceOf ( ObjectName name , String className ) throws InstanceNotFoundException { return false ; } @ Override public Object instantiate ( String className ) throws ReflectionException , MBeanException { return null ; } @ Override public Object instantiate ( String className , ObjectName loaderName ) throws ReflectionException , MBeanException , InstanceNotFoundException { return null ; } @ Override public Object instantiate ( String className , Object [ ] params , String [ ] signature ) throws ReflectionException , MBeanException { return null ; } @ Override public Object instantiate ( String className , ObjectName loaderName , Object [ ] params , String [ ] signature ) throws ReflectionException , MBeanException , InstanceNotFoundException { return null ; } @ Override public ObjectInputStream deserialize ( ObjectName name , byte [ ] data ) throws InstanceNotFoundException , OperationsException { return null ; } @ Override public ObjectInputStream deserialize ( String className , byte [ ] data ) throws OperationsException , ReflectionException { return null ; } @ Override public ObjectInputStream deserialize ( String className , ObjectName loaderName , byte [ ] data ) throws InstanceNotFoundException , OperationsException , ReflectionException { return null ; } @ Override public ClassLoader getClassLoaderFor ( ObjectName mbeanName ) throws InstanceNotFoundException { return null ; } @ Override public ClassLoader getClassLoader ( ObjectName loaderName ) throws InstanceNotFoundException { return null ; } @ Override public ClassLoaderRepository getClassLoaderRepository ( ) { return null ; } } </s>
<s> package com . senseidb . jmx ; import java . lang . management . ManagementFactory ; import java . lang . reflect . Field ; import java . lang . reflect . InvocationHandler ; import java . lang . reflect . Method ; import java . lang . reflect . Proxy ; import javax . management . MBeanServer ; import javax . management . ObjectName ; import org . apache . log4j . Logger ; import com . sun . jmx . mbeanserver . SunJmxMBeanServer ; public class JmxSenseiMBeanServer { private static Logger logger = Logger . getLogger ( JmxSenseiMBeanServer . class ) ; private static boolean registered = false ; public synchronized static void registerCustomMBeanServer ( ) { try { if ( ! registered ) { MBeanServer platformMBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; Field platformMBeanServerField = ManagementFactory . class . getDeclaredField ( "<STR_LIT>" ) ; platformMBeanServerField . setAccessible ( true ) ; Object modifiedMbeanServer = Proxy . newProxyInstance ( platformMBeanServer . getClass ( ) . getClassLoader ( ) , new Class [ ] { MBeanServer . class , SunJmxMBeanServer . class } , new MBeanServerInvocationHandler ( platformMBeanServer ) ) ; platformMBeanServerField . set ( null , modifiedMbeanServer ) ; registered = true ; } } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } public static class MBeanServerInvocationHandler implements InvocationHandler { final MBeanServer mBeanServer ; public MBeanServerInvocationHandler ( MBeanServer underlying ) { this . mBeanServer = underlying ; } public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { if ( ! method . getName ( ) . equals ( "<STR_LIT>" ) ) { return method . invoke ( mBeanServer , args ) ; } ObjectName objectName = ( ObjectName ) args [ <NUM_LIT:1> ] ; String canonicalName = objectName . getCanonicalName ( ) ; if ( ! canonicalName . contains ( "<STR_LIT>" ) && ! canonicalName . contains ( "<STR_LIT>" ) && ! canonicalName . contains ( "<STR_LIT>" ) && ! canonicalName . contains ( "<STR_LIT>" ) ) { return method . invoke ( mBeanServer , args ) ; } for ( int i = <NUM_LIT:0> ; i < <NUM_LIT> ; i ++ ) { if ( ! mBeanServer . isRegistered ( objectName ) ) { break ; } logger . warn ( "<STR_LIT>" + canonicalName + "<STR_LIT>" ) ; objectName = new ObjectName ( canonicalName + i ) ; } args [ <NUM_LIT:1> ] = objectName ; return method . invoke ( mBeanServer , args ) ; } } } </s>
<s> package com . senseidb . jmx ; import java . lang . management . ManagementFactory ; import java . lang . reflect . Field ; import java . util . Collections ; import java . util . LinkedList ; import java . util . List ; import javax . management . InstanceAlreadyExistsException ; import javax . management . MBeanServer ; import javax . management . ObjectName ; import javax . management . StandardMBean ; import org . apache . log4j . Logger ; import com . senseidb . metrics . MetricsConstants ; public class JmxUtil { private static final Logger log = Logger . getLogger ( JmxUtil . class ) ; private static final MBeanServer MbeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; private static final List < ObjectName > RegisteredBeans = Collections . synchronizedList ( new LinkedList < ObjectName > ( ) ) ; public static MBeanServer registerNewJmxServer ( MBeanServer newBeanServer ) { MBeanServer platformMBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; try { Field platformMBeanServerField = ManagementFactory . class . getDeclaredField ( "<STR_LIT>" ) ; platformMBeanServerField . setAccessible ( true ) ; platformMBeanServerField . set ( null , newBeanServer ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } return platformMBeanServer ; } public static void registerMBean ( StandardMBean bean , String key , String val ) { ObjectName objectName = null ; try { objectName = new ObjectName ( MetricsConstants . Domain , key , val ) ; log . info ( "<STR_LIT>" + objectName ) ; MbeanServer . registerMBean ( bean , objectName ) ; RegisteredBeans . add ( objectName ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; if ( e instanceof InstanceAlreadyExistsException ) { RegisteredBeans . add ( objectName ) ; } } } public static void unregisterMBeans ( ) { for ( ObjectName mbeanName : RegisteredBeans ) { try { log . info ( "<STR_LIT>" + mbeanName ) ; MbeanServer . unregisterMBean ( mbeanName ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } } RegisteredBeans . clear ( ) ; } } </s>
<s> package com . senseidb . dataprovider . http ; import java . io . IOException ; import java . io . InputStream ; import java . util . Comparator ; import java . util . Iterator ; import org . apache . commons . io . IOUtils ; import org . apache . http . Header ; import org . apache . http . HeaderElement ; import org . apache . http . HttpEntity ; import org . apache . http . HttpException ; import org . apache . http . HttpRequest ; import org . apache . http . HttpRequestInterceptor ; import org . apache . http . HttpResponse ; import org . apache . http . HttpResponseInterceptor ; import org . apache . http . HttpVersion ; import org . apache . http . StatusLine ; import org . apache . http . client . entity . GzipDecompressingEntity ; import org . apache . http . client . methods . HttpGet ; import org . apache . http . conn . ClientConnectionManager ; import org . apache . http . conn . scheme . PlainSocketFactory ; import org . apache . http . conn . scheme . Scheme ; import org . apache . http . conn . scheme . SchemeRegistry ; import org . apache . http . conn . ssl . SSLSocketFactory ; import org . apache . http . impl . client . DefaultHttpClient ; import org . apache . http . impl . conn . SingleClientConnManager ; import org . apache . http . params . BasicHttpParams ; import org . apache . http . params . HttpConnectionParams ; import org . apache . http . params . HttpParams ; import org . apache . http . params . HttpProtocolParams ; import org . apache . http . protocol . HttpContext ; import org . apache . log4j . Logger ; import proj . zoie . api . DataConsumer . DataEvent ; import proj . zoie . impl . indexing . StreamDataProvider ; public abstract class HttpStreamDataProvider < D > extends StreamDataProvider < D > implements HttpDataProviderAdminMBean { private static final Logger logger = Logger . getLogger ( HttpStreamDataProvider . class ) ; protected final String _baseUrl ; private final ClientConnectionManager _httpClientManager ; private DefaultHttpClient _httpclient ; public static final int DEFAULT_TIMEOUT_MS = <NUM_LIT> ; public static final int DEFAULT_RETRYTIME_MS = <NUM_LIT> ; public static final String DEFAULT_OFFSET_PARAM = "<STR_LIT>" ; public static final String DFEAULT_DATA_PARAM = "<STR_LIT:data>" ; protected final int _fetchSize ; protected final String _password ; protected String _offset ; protected String _initialOffset ; private final boolean _disableHttps ; private Iterator < DataEvent < D > > _currentDataIter ; private volatile boolean _stopped ; private int _retryTime ; private volatile long _httpGetLatency ; private volatile long _responseParseLatency ; public HttpStreamDataProvider ( Comparator < String > versionComparator , String baseUrl , String pw , int fetchSize , String startingOffset , boolean disableHttps ) { super ( versionComparator ) ; _baseUrl = baseUrl ; _password = pw ; _fetchSize = fetchSize ; _offset = startingOffset ; _disableHttps = disableHttps ; _initialOffset = null ; _currentDataIter = null ; _stopped = true ; _httpGetLatency = <NUM_LIT> ; _responseParseLatency = <NUM_LIT> ; Scheme http = new Scheme ( "<STR_LIT:http>" , <NUM_LIT> , PlainSocketFactory . getSocketFactory ( ) ) ; SchemeRegistry sr = new SchemeRegistry ( ) ; sr . register ( http ) ; HttpParams params = new BasicHttpParams ( ) ; params . setParameter ( HttpProtocolParams . PROTOCOL_VERSION , HttpVersion . HTTP_1_1 ) ; params . setParameter ( HttpProtocolParams . HTTP_CONTENT_CHARSET , "<STR_LIT:UTF-8>" ) ; params . setIntParameter ( HttpConnectionParams . CONNECTION_TIMEOUT , <NUM_LIT> ) ; params . setIntParameter ( HttpConnectionParams . SO_LINGER , <NUM_LIT:0> ) ; params . setBooleanParameter ( HttpConnectionParams . TCP_NODELAY , true ) ; params . setIntParameter ( HttpConnectionParams . SO_TIMEOUT , <NUM_LIT> ) ; params . setIntParameter ( HttpConnectionParams . SOCKET_BUFFER_SIZE , <NUM_LIT> * <NUM_LIT> ) ; params . setBooleanParameter ( HttpConnectionParams . SO_REUSEADDR , true ) ; _httpClientManager = new SingleClientConnManager ( sr ) ; _httpclient = new DefaultHttpClient ( _httpClientManager , params ) ; if ( ! _disableHttps ) { _httpclient = HttpsClientDecorator . decorate ( _httpclient ) ; } _httpclient . addRequestInterceptor ( new HttpRequestInterceptor ( ) { public void process ( final HttpRequest request , final HttpContext context ) throws HttpException , IOException { if ( ! request . containsHeader ( "<STR_LIT>" ) ) { request . addHeader ( "<STR_LIT>" , "<STR_LIT>" ) ; } } } ) ; _httpclient . addResponseInterceptor ( new HttpResponseInterceptor ( ) { public void process ( final HttpResponse response , final HttpContext context ) throws HttpException , IOException { HttpEntity entity = response . getEntity ( ) ; Header ceheader = entity . getContentEncoding ( ) ; if ( ceheader != null ) { HeaderElement [ ] codecs = ceheader . getElements ( ) ; for ( int i = <NUM_LIT:0> ; i < codecs . length ; i ++ ) { if ( codecs [ i ] . getName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) ) { response . setEntity ( new GzipDecompressingEntity ( response . getEntity ( ) ) ) ; return ; } } } } } ) ; _retryTime = DEFAULT_RETRYTIME_MS ; } public void setRetryTime ( int retryTime ) { _retryTime = retryTime ; } public int getRetryTime ( ) { return _retryTime ; } @ Override public void setStartingOffset ( String initialOffset ) { _initialOffset = initialOffset ; } protected abstract String buildGetString ( String offset ) ; protected abstract Iterator < DataEvent < D > > parse ( InputStream is ) throws Exception ; private Iterator < DataEvent < D > > fetchBatch ( ) throws HttpException { InputStream stream = null ; try { HttpGet httpget = new HttpGet ( buildGetString ( _offset ) ) ; long getStart = System . currentTimeMillis ( ) ; HttpResponse response = _httpclient . execute ( httpget ) ; long getEnd = System . currentTimeMillis ( ) ; _httpGetLatency = getEnd - getStart ; HttpEntity entity = response . getEntity ( ) ; StatusLine status = response . getStatusLine ( ) ; int statusCode = status . getStatusCode ( ) ; if ( statusCode >= <NUM_LIT> ) { try { IOUtils . closeQuietly ( entity . getContent ( ) ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } throw new HttpException ( status . getReasonPhrase ( ) ) ; } try { stream = entity . getContent ( ) ; long parseStart = System . currentTimeMillis ( ) ; Iterator < DataEvent < D > > iter = parse ( stream ) ; long parseEnd = System . currentTimeMillis ( ) ; _responseParseLatency = parseEnd - parseStart ; return iter ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; httpget . abort ( ) ; throw new HttpException ( e . getMessage ( ) , e ) ; } } catch ( IOException ioe ) { throw new HttpException ( ioe . getMessage ( ) , ioe ) ; } finally { if ( stream != null ) { IOUtils . closeQuietly ( stream ) ; } } } @ Override public DataEvent < D > next ( ) { if ( _stopped ) { return null ; } if ( _currentDataIter == null || ! _currentDataIter . hasNext ( ) ) { while ( true && ! _stopped ) { try { Iterator < DataEvent < D > > data = fetchBatch ( ) ; if ( data == null || ! data . hasNext ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "<STR_LIT>" ) ; } synchronized ( this ) { try { this . wait ( _retryTime ) ; return null ; } catch ( InterruptedException e1 ) { return null ; } } } _currentDataIter = data ; break ; } catch ( HttpException e ) { logger . error ( e . getMessage ( ) , e ) ; try { logger . error ( "<STR_LIT>" + _retryTime + "<STR_LIT>" ) ; synchronized ( this ) { this . wait ( _retryTime ) ; } continue ; } catch ( InterruptedException e1 ) { return null ; } } } } DataEvent < D > data = null ; if ( _currentDataIter != null && _currentDataIter . hasNext ( ) ) { data = _currentDataIter . next ( ) ; if ( data != null ) { _offset = data . getVersion ( ) ; } } return data ; } @ Override public void reset ( ) { if ( _initialOffset != null ) { _offset = _initialOffset ; } } @ Override public long getHttpGetLatency ( ) { return _httpGetLatency ; } @ Override public long getResponseParseLatency ( ) { return _responseParseLatency ; } @ Override public void start ( ) { super . start ( ) ; _stopped = false ; } @ Override public void stop ( ) { synchronized ( this ) { _stopped = true ; this . notifyAll ( ) ; } try { super . stop ( ) ; } finally { if ( _httpClientManager != null ) { _httpClientManager . shutdown ( ) ; } } } } </s>
<s> package com . senseidb . dataprovider . http ; import java . security . cert . CertificateException ; import java . security . cert . X509Certificate ; import javax . net . ssl . SSLContext ; import javax . net . ssl . TrustManager ; import javax . net . ssl . X509TrustManager ; import org . apache . http . conn . ClientConnectionManager ; import org . apache . http . conn . scheme . Scheme ; import org . apache . http . conn . scheme . SchemeRegistry ; import org . apache . http . conn . ssl . SSLSocketFactory ; import org . apache . http . impl . client . DefaultHttpClient ; import org . apache . log4j . Logger ; public class HttpsClientDecorator { private static Logger logger = Logger . getLogger ( HttpsClientDecorator . class ) ; public static DefaultHttpClient decorate ( DefaultHttpClient base ) { try { SSLContext ctx = SSLContext . getInstance ( "<STR_LIT>" ) ; X509TrustManager tm = new X509TrustManager ( ) { public void checkClientTrusted ( X509Certificate [ ] xcs , String string ) throws CertificateException { } public void checkServerTrusted ( X509Certificate [ ] xcs , String string ) throws CertificateException { } public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } } ; ctx . init ( null , new TrustManager [ ] { tm } , null ) ; SSLSocketFactory ssf = new SSLSocketFactory ( ctx , SSLSocketFactory . ALLOW_ALL_HOSTNAME_VERIFIER ) ; ClientConnectionManager ccm = base . getConnectionManager ( ) ; SchemeRegistry sr = ccm . getSchemeRegistry ( ) ; sr . register ( new Scheme ( "<STR_LIT>" , <NUM_LIT> , ssf ) ) ; return new DefaultHttpClient ( ccm , base . getParams ( ) ) ; } catch ( Exception ex ) { logger . error ( ex . getMessage ( ) , ex ) ; return null ; } } } </s>
<s> package com . senseidb . dataprovider . http ; import proj . zoie . mbean . DataProviderAdminMBean ; public interface HttpDataProviderAdminMBean extends DataProviderAdminMBean { public long getHttpGetLatency ( ) ; public long getResponseParseLatency ( ) ; } </s>
<s> package com . senseidb . util ; import java . net . DatagramSocket ; import java . net . InetAddress ; import java . net . SocketException ; import java . net . UnknownHostException ; public class NetUtil { private static final String DUMMY_OUT_IP = "<STR_LIT>" ; public static String getHostAddress ( ) throws SocketException , UnknownHostException { DatagramSocket ds = new DatagramSocket ( ) ; ds . connect ( InetAddress . getByName ( DUMMY_OUT_IP ) , <NUM_LIT> ) ; InetAddress localAddress = ds . getLocalAddress ( ) ; if ( localAddress . getHostAddress ( ) . equals ( "<STR_LIT>" ) ) { localAddress = InetAddress . getLocalHost ( ) ; } return localAddress . getHostAddress ( ) ; } } </s>
<s> package com . senseidb . util ; import java . io . UnsupportedEncodingException ; import java . net . URLDecoder ; import java . util . HashMap ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; public class HttpUtil { public static Map < String , List < String > > buildRequestMap ( String reqString ) { Map < String , List < String > > map = new HashMap < String , List < String > > ( ) ; String [ ] params = reqString . split ( "<STR_LIT:&>" ) ; for ( String param : params ) { String [ ] parts = param . split ( "<STR_LIT:=>" ) ; if ( parts . length != <NUM_LIT:2> ) continue ; String key = parts [ <NUM_LIT:0> ] ; String val = parts [ <NUM_LIT:1> ] ; if ( val != null && val . length ( ) > <NUM_LIT:0> ) { List < String > valList = map . get ( key ) ; if ( valList == null ) { valList = new LinkedList < String > ( ) ; map . put ( key , valList ) ; } try { val = URLDecoder . decode ( val , "<STR_LIT:UTF-8>" ) ; valList . add ( val ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } } } return map ; } public static void main ( String [ ] args ) { String reqstring = "<STR_LIT>" ; Map map = buildRequestMap ( reqstring ) ; System . out . println ( map ) ; } } </s>
<s> package com . senseidb . util ; public class Pair < FIRST , SECOND > { private FIRST first ; private SECOND second ; public FIRST getFirst ( ) { return first ; } public void setFirst ( FIRST first ) { this . first = first ; } public SECOND getSecond ( ) { return second ; } public void setSecond ( SECOND second ) { this . second = second ; } public Pair ( FIRST first , SECOND second ) { super ( ) ; this . first = first ; this . second = second ; } } </s>
<s> package com . senseidb . util ; import com . browseengine . bobo . api . BrowseRequest ; import com . browseengine . bobo . api . BrowseSelection ; import com . senseidb . search . node . SenseiQueryBuilder ; import com . senseidb . search . node . SenseiQueryBuilderFactory ; import com . senseidb . search . req . SenseiRequest ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . apache . commons . configuration . BaseConfiguration ; import org . apache . commons . configuration . Configuration ; import org . apache . log4j . Logger ; import org . apache . lucene . search . Filter ; import org . apache . lucene . search . Query ; public class RequestConverter { private static Logger logger = Logger . getLogger ( RequestConverter . class ) ; public static BrowseRequest convert ( SenseiRequest req , SenseiQueryBuilderFactory queryBuilderFactory ) throws Exception { BrowseRequest breq = new BrowseRequest ( ) ; breq . setTid ( req . getTid ( ) ) ; breq . setOffset ( req . getOffset ( ) ) ; breq . setCount ( req . getCount ( ) ) ; breq . setSort ( req . getSort ( ) ) ; breq . setFetchStoredFields ( req . isFetchStoredFields ( ) ) ; breq . setShowExplanation ( req . isShowExplanation ( ) ) ; breq . setTermVectorsToFetch ( req . getTermVectorsToFetch ( ) ) ; breq . setGroupBy ( req . getGroupBy ( ) ) ; breq . setMaxPerGroup ( req . getMaxPerGroup ( ) ) ; if ( breq . getGroupBy ( ) != null && breq . getMaxPerGroup ( ) > <NUM_LIT:1> ) { breq . setCollectDocIdCache ( true ) ; } SenseiQueryBuilder queryBuilder = queryBuilderFactory . getQueryBuilder ( req . getQuery ( ) ) ; Query q = null ; Filter f = null ; if ( queryBuilder != null ) { q = queryBuilder . buildQuery ( ) ; f = queryBuilder . buildFilter ( ) ; } if ( q != null ) { breq . setQuery ( q ) ; } if ( f != null ) { breq . setFilter ( f ) ; } BrowseSelection [ ] sels = req . getSelections ( ) ; for ( BrowseSelection sel : sels ) { breq . addSelection ( sel ) ; } breq . setFacetHandlerDataMap ( req . getFacetHandlerInitParamMap ( ) ) ; breq . setFacetSpecs ( req . getFacetSpecs ( ) ) ; return breq ; } public static Map < String , Configuration > parseParamConf ( Configuration params , String prefix ) { Iterator < String > keys = params . getKeys ( prefix ) ; HashMap < String , Configuration > map = new HashMap < String , Configuration > ( ) ; while ( keys . hasNext ( ) ) { try { String key = keys . next ( ) ; String [ ] values = params . getStringArray ( key ) ; String subString = key . substring ( prefix . length ( ) + <NUM_LIT:1> ) ; String [ ] parts = subString . split ( "<STR_LIT:\\.>" ) ; if ( parts . length == <NUM_LIT:2> ) { String name = parts [ <NUM_LIT:0> ] ; String paramName = parts [ <NUM_LIT:1> ] ; Configuration conf = map . get ( name ) ; if ( conf == null ) { conf = new BaseConfiguration ( ) ; map . put ( name , conf ) ; } for ( String val : values ) { conf . addProperty ( paramName , val ) ; } } else if ( parts . length == <NUM_LIT:3> ) { String facetName = parts [ <NUM_LIT:0> ] ; String paramName = parts [ <NUM_LIT:1> ] ; String paramAttrName = parts [ <NUM_LIT:2> ] ; Configuration conf = map . get ( facetName ) ; if ( conf == null ) { conf = new BaseConfiguration ( ) ; map . put ( facetName , conf ) ; } Configuration paramConf ; if ( conf . getProperty ( paramName ) == null ) { paramConf = new BaseConfiguration ( ) ; conf . addProperty ( paramName , paramConf ) ; } else { paramConf = ( Configuration ) conf . getProperty ( paramName ) ; } for ( String val : values ) { paramConf . addProperty ( paramAttrName , val ) ; } } else { logger . error ( "<STR_LIT>" + key ) ; } } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } } return map ; } } </s>
<s> package com . senseidb . util ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import org . apache . log4j . Logger ; public class JsonTemplateProcessor { public static final String TEMPLATE_MAPPING_PARAM = "<STR_LIT>" ; private final static Logger logger = Logger . getLogger ( JsonTemplateProcessor . class ) ; public Map < String , Object > getTemplates ( JSONObject request ) { Map < String , Object > ret = new HashMap < String , Object > ( ) ; JSONObject templatesJson = request . optJSONObject ( TEMPLATE_MAPPING_PARAM ) ; if ( templatesJson == null ) { return ret ; } Iterator keys = templatesJson . keys ( ) ; while ( keys . hasNext ( ) ) { String templateName = ( String ) keys . next ( ) ; Object templateValueObj = templatesJson . opt ( templateName ) ; if ( templateValueObj != null && ( templateValueObj instanceof String || templateValueObj instanceof Number || templateValueObj instanceof JSONArray ) ) { ret . put ( templateName , templateValueObj ) ; } else { throw new UnsupportedOperationException ( "<STR_LIT>" + templateName + "<STR_LIT>" ) ; } } return ret ; } public JSONObject substituteTemplates ( JSONObject request ) { try { return ( JSONObject ) process ( request , getTemplates ( request ) ) ; } catch ( JSONException ex ) { throw new RuntimeException ( ex ) ; } } public Object process ( Object src , Map < String , Object > templates ) throws JSONException { if ( src instanceof String ) { return processString ( ( String ) src , templates ) ; } if ( src instanceof JSONObject ) { return processJsonObject ( ( JSONObject ) src , templates ) ; } if ( src instanceof JSONArray ) { JSONArray arr = ( JSONArray ) src ; for ( int i = <NUM_LIT:0> ; i < arr . length ( ) ; i ++ ) { arr . put ( i , process ( arr . get ( i ) , templates ) ) ; } return arr ; } return src ; } private JSONObject processJsonObject ( JSONObject src , Map < String , Object > templates ) throws JSONException { if ( src == null ) { return null ; } String [ ] names = JSONObject . getNames ( src ) ; if ( names == null || names . length == <NUM_LIT:0> ) { return src ; } for ( String name : names ) { Object val = process ( src . get ( name ) , templates ) ; Object newName = processString ( name , templates ) ; if ( newName != name ) { src . remove ( name ) ; } src . put ( newName . toString ( ) , val ) ; } return src ; } private Object processString ( String src , Map < String , Object > templates ) { if ( ! src . contains ( "<STR_LIT:$>" ) ) { return src ; } for ( String key : templates . keySet ( ) ) { String replaceable = "<STR_LIT:$>" + key ; Object value = templates . get ( key ) ; if ( value == null ) { continue ; } if ( src . equals ( replaceable ) ) { if ( value instanceof String ) { value = ( ( String ) value ) . replaceAll ( "<STR_LIT>" , "<STR_LIT>" ) ; } return value ; } int index = - <NUM_LIT:1> ; while ( ( index = src . indexOf ( replaceable , index + <NUM_LIT:1> ) ) >= <NUM_LIT:0> ) { int numSigns = numPrecedingDollarSigns ( src , index ) ; if ( numSigns % <NUM_LIT:2> == <NUM_LIT:1> ) { src = src . substring ( <NUM_LIT:0> , index ) + value . toString ( ) + src . substring ( index + replaceable . length ( ) ) ; } } } src = src . replaceAll ( "<STR_LIT>" , "<STR_LIT>" ) ; return src ; } private int numPrecedingDollarSigns ( String replaceable , int index ) { int ret = <NUM_LIT:0> ; while ( index >= <NUM_LIT:0> && replaceable . charAt ( index ) == '<CHAR_LIT>' ) { ret ++ ; index -- ; } return ret ; } } </s>
<s> package com . senseidb . util ; public final class SenseiDefaults { public static final String SENSEI_CLUSTER_CONF_FILE = "<STR_LIT>" ; public static final String SENSEI_CLIENT_CONF_FILE = "<STR_LIT>" ; public static final String SENSEI_NODE_CONF_FILE = "<STR_LIT>" ; public static final String SENSEI_CLIENT_SVC_URL_PROP = "<STR_LIT>" ; } </s>
<s> package com . senseidb . util ; import java . net . URI ; import org . apache . hadoop . conf . Configuration ; import org . apache . hadoop . fs . FileStatus ; import org . apache . hadoop . fs . FileSystem ; import org . apache . hadoop . fs . Path ; import org . apache . log4j . Logger ; import proj . zoie . api . IndexCopier ; public class HDFSIndexCopier implements IndexCopier { public static final Logger log = Logger . getLogger ( HDFSIndexCopier . class ) ; public boolean copy ( String src , String dest ) { try { URI srcUri = new URI ( src ) , destUri = new URI ( dest ) ; Configuration config = new Configuration ( ) ; config . set ( "<STR_LIT>" , srcUri . resolve ( "<STR_LIT:/>" ) . toString ( ) ) ; FileSystem dfs = FileSystem . get ( config ) ; Path destPath = new Path ( destUri . toString ( ) ) ; FileStatus [ ] files = dfs . listStatus ( new Path ( srcUri . toString ( ) ) ) ; if ( files == null || files . length == <NUM_LIT:0> ) return false ; for ( FileStatus f : files ) { log . info ( "<STR_LIT>" + f . getPath ( ) . toString ( ) ) ; dfs . copyToLocalFile ( f . getPath ( ) , destPath ) ; } return true ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; return false ; } } } </s>
<s> package com . senseidb . util ; import java . text . DecimalFormat ; import java . text . DecimalFormatSymbols ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Locale ; import java . util . Map ; import java . util . Set ; import org . apache . commons . codec . binary . Base64 ; import org . apache . lucene . search . SortField ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import com . browseengine . bobo . api . BrowseSelection ; import com . browseengine . bobo . api . BrowseSelection . ValueOperation ; import com . browseengine . bobo . api . FacetSpec ; import com . browseengine . bobo . facets . DefaultFacetHandlerInitializerParam ; import com . browseengine . bobo . facets . impl . PathFacetHandler ; import com . senseidb . indexing . DefaultSenseiInterpreter ; import com . senseidb . indexing . MetaType ; import com . senseidb . search . req . SenseiJSONQuery ; import com . senseidb . search . req . SenseiRequest ; import com . senseidb . search . req . mapred . SenseiMapReduce ; import com . senseidb . search . req . mapred . impl . MapReduceRegistry ; public class RequestConverter2 { public static final String PAGING_SIZE = "<STR_LIT:size>" ; public static final String PAGING_FROM = "<STR_LIT>" ; public static final String GROUPBY = "<STR_LIT>" ; public static final String GROUPBY_COLUMN = "<STR_LIT>" ; public static final String GROUPBY_TOP = "<STR_LIT>" ; public static final String SELECTIONS = "<STR_LIT>" ; public static final String SELECTIONS_TERM = "<STR_LIT>" ; public static final String SELECTIONS_TERM_VALUE = "<STR_LIT:value>" ; public static final String SELECTIONS_TERMS = "<STR_LIT>" ; public static final String SELECTIONS_TERMS_VALUES = "<STR_LIT>" ; public static final String SELECTIONS_TERMS_EXCLUDES = "<STR_LIT>" ; public static final String SELECTIONS_TERMS_OPERATOR = "<STR_LIT>" ; public static final String SELECTIONS_TERMS_OPERATOR_OR = "<STR_LIT>" ; public static final String SELECTIONS_TERMS_OPERATOR_AND = "<STR_LIT>" ; public static final String SELECTIONS_RANGE = "<STR_LIT>" ; public static final String SELECTIONS_RANGE_FROM = "<STR_LIT>" ; public static final String SELECTIONS_RANGE_TO = "<STR_LIT>" ; public static final String SELECTIONS_RANGE_INCLUDE_LOWER = "<STR_LIT>" ; public static final String SELECTIONS_RANGE_INCLUDE_UPPER = "<STR_LIT>" ; public static final String SELECTIONS_PATH = "<STR_LIT:path>" ; public static final String SELECTIONS_PATH_VALUE = "<STR_LIT:value>" ; public static final String SELECTIONS_PATH_STRICT = "<STR_LIT>" ; public static final String SELECTIONS_PATH_DEPTH = "<STR_LIT>" ; public static final String SELECTIONS_CUSTOM = "<STR_LIT>" ; public static final String SELECTIONS_DEFAULT = "<STR_LIT:default>" ; public static final String FACETS = "<STR_LIT>" ; public static final String FACETS_MAX = "<STR_LIT>" ; public static final String FACETS_MINCOUNT = "<STR_LIT>" ; public static final String FACETS_EXPAND = "<STR_LIT>" ; public static final String FACETS_ORDER = "<STR_LIT>" ; public static final String FACETS_ORDER_HITS = "<STR_LIT>" ; public static final String FACETS_ORDER_VAL = "<STR_LIT>" ; public static final String FACETINIT = "<STR_LIT>" ; public static final String FACETINIT_TYPE = "<STR_LIT:type>" ; public static final String FACETINIT_TYPE_INT = "<STR_LIT:int>" ; public static final String FACETINIT_TYPE_STRING = "<STR_LIT:string>" ; public static final String FACETINIT_TYPE_BOOLEAN = "<STR_LIT:boolean>" ; public static final String FACETINIT_TYPE_LONG = "<STR_LIT:long>" ; public static final String FACETINIT_TYPE_BYTES = "<STR_LIT>" ; public static final String FACETINIT_TYPE_DOUBLE = "<STR_LIT:double>" ; public static final String FACETINIT_VALUES = "<STR_LIT>" ; public static final String SORT = "<STR_LIT>" ; public static final String SORT_ASC = "<STR_LIT>" ; public static final String SORT_DESC = "<STR_LIT>" ; public static final String SORT_SCORE = "<STR_LIT>" ; public static final String SORT_RELEVANCE = "<STR_LIT>" ; public static final String FETCH_STORED = "<STR_LIT>" ; public static final String FETCH_STORED_VALUE = "<STR_LIT>" ; public static final String TERM_VECTORS = "<STR_LIT>" ; public static final String PARTITIONS = "<STR_LIT>" ; public static final String EXPLAIN = "<STR_LIT>" ; public static final String ROUTEPARAM = "<STR_LIT>" ; public static final String MAPPINGS = "<STR_LIT>" ; private static final String MAP_REDUCE = "<STR_LIT>" ; private static final String MAP_REDUCE_FUNCTION = "<STR_LIT>" ; private static final String MAP_REDUCE_PARAMETERS = "<STR_LIT>" ; private static JsonTemplateProcessor jsonTemplateProcessor = new JsonTemplateProcessor ( ) ; public static String [ ] getStrings ( JSONObject obj , String field ) { String [ ] strArray = null ; JSONArray array = obj . optJSONArray ( field ) ; if ( array != null ) { int count = array . length ( ) ; strArray = new String [ count ] ; for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { strArray [ i ] = array . optString ( i ) ; } } return strArray ; } private static int [ ] getInts ( JSONObject obj , String field , int defaultVal ) { int [ ] intArray = null ; JSONArray array = obj . optJSONArray ( field ) ; if ( array != null ) { int count = array . length ( ) ; intArray = new int [ count ] ; for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { intArray [ i ] = array . optInt ( i , defaultVal ) ; } } return intArray ; } private static Set < Integer > getIntSet ( JSONObject obj , String field , int defaultVal ) { HashSet < Integer > intSet = null ; JSONArray array = obj . optJSONArray ( field ) ; if ( array != null ) { int count = array . length ( ) ; intSet = new HashSet < Integer > ( count ) ; for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { intSet . add ( array . optInt ( i , defaultVal ) ) ; } } return intSet ; } public static String [ ] getStrings ( JSONArray jsonArray ) throws Exception { if ( jsonArray == null ) return null ; int count = jsonArray . length ( ) ; String [ ] vals = new String [ count ] ; for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { vals [ i ] = jsonArray . getString ( i ) ; } return vals ; } public static SenseiRequest fromJSON ( JSONObject json ) throws Exception { return fromJSON ( json , null ) ; } public static SenseiRequest fromJSON ( JSONObject json , final Map < String , String [ ] > facetInfoMap ) throws Exception { json = jsonTemplateProcessor . substituteTemplates ( json ) ; SenseiRequest req = new SenseiRequest ( ) ; JSONObject meta = json . optJSONObject ( "<STR_LIT>" ) ; if ( meta != null ) { JSONArray array = meta . optJSONArray ( "<STR_LIT>" ) ; if ( array != null ) { List < String > list = new ArrayList < String > ( ) ; for ( int i = <NUM_LIT:0> ; i < array . length ( ) ; ++ i ) { list . add ( array . get ( i ) . toString ( ) ) ; } req . setSelectList ( list ) ; } } req . setQuery ( new SenseiJSONQuery ( json ) ) ; int count = json . optInt ( RequestConverter2 . PAGING_SIZE , <NUM_LIT:10> ) ; int offset = json . optInt ( RequestConverter2 . PAGING_FROM , <NUM_LIT:0> ) ; req . setCount ( count ) ; req . setOffset ( offset ) ; JSONObject groupBy = json . optJSONObject ( "<STR_LIT>" ) ; if ( groupBy != null ) { JSONArray columns = groupBy . optJSONArray ( "<STR_LIT>" ) ; if ( columns != null && columns . length ( ) >= <NUM_LIT:1> ) { String [ ] groupByArray = new String [ columns . length ( ) ] ; for ( int i = <NUM_LIT:0> ; i < columns . length ( ) ; ++ i ) groupByArray [ i ] = columns . getString ( i ) ; req . setGroupBy ( groupByArray ) ; } req . setMaxPerGroup ( groupBy . optInt ( "<STR_LIT>" , groupBy . optInt ( "<STR_LIT:count>" , <NUM_LIT:1> ) ) ) ; } Object selections = json . opt ( RequestConverter2 . SELECTIONS ) ; if ( selections == null ) { } else if ( selections instanceof JSONArray ) { JSONArray selectionArray = ( JSONArray ) selections ; for ( int i = <NUM_LIT:0> ; i < selectionArray . length ( ) ; i ++ ) { JSONObject selItem = selectionArray . optJSONObject ( i ) ; if ( selItem != null ) { Iterator < String > keyIter = selItem . keys ( ) ; while ( keyIter . hasNext ( ) ) { String type = keyIter . next ( ) ; JSONObject jsonSel = selItem . optJSONObject ( type ) ; if ( jsonSel != null ) { addSelection ( type , jsonSel , req , facetInfoMap ) ; } } } } } else if ( selections instanceof JSONObject ) { JSONObject selectionObject = ( JSONObject ) selections ; Iterator < String > keyIter = selectionObject . keys ( ) ; while ( keyIter . hasNext ( ) ) { String type = keyIter . next ( ) ; JSONObject jsonSel = selectionObject . optJSONObject ( type ) ; if ( jsonSel != null ) addSelection ( type , jsonSel , req , facetInfoMap ) ; } } JSONObject mapReduceJson = json . optJSONObject ( RequestConverter2 . MAP_REDUCE ) ; if ( mapReduceJson != null ) { String key = mapReduceJson . getString ( MAP_REDUCE_FUNCTION ) ; SenseiMapReduce senseiMapReduce = MapReduceRegistry . get ( key ) ; senseiMapReduce . init ( mapReduceJson . optJSONObject ( MAP_REDUCE_PARAMETERS ) ) ; req . setMapReduceFunction ( senseiMapReduce ) ; } JSONObject facets = json . optJSONObject ( RequestConverter2 . FACETS ) ; if ( facets != null ) { Iterator < String > keyIter = facets . keys ( ) ; while ( keyIter . hasNext ( ) ) { String field = keyIter . next ( ) ; JSONObject facetObj = facets . getJSONObject ( field ) ; if ( facetObj != null ) { FacetSpec facetSpec = new FacetSpec ( ) ; facetSpec . setMaxCount ( facetObj . optInt ( RequestConverter2 . FACETS_MAX , <NUM_LIT:10> ) ) ; facetSpec . setMinHitCount ( facetObj . optInt ( RequestConverter2 . FACETS_MINCOUNT , <NUM_LIT:1> ) ) ; facetSpec . setExpandSelection ( facetObj . optBoolean ( RequestConverter2 . FACETS_EXPAND , false ) ) ; String orderBy = facetObj . optString ( RequestConverter2 . FACETS_ORDER , RequestConverter2 . FACETS_ORDER_HITS ) ; FacetSpec . FacetSortSpec facetOrder = FacetSpec . FacetSortSpec . OrderHitsDesc ; if ( RequestConverter2 . FACETS_ORDER_VAL . equals ( orderBy ) ) { facetOrder = FacetSpec . FacetSortSpec . OrderValueAsc ; } facetSpec . setProperties ( createFacetProperties ( facetObj ) ) ; facetSpec . setOrderBy ( facetOrder ) ; req . setFacetSpec ( field , facetSpec ) ; } } } JSONObject facetInitParams = json . optJSONObject ( RequestConverter2 . FACETINIT ) ; if ( facetInitParams != null ) { Iterator < String > keyIter = facetInitParams . keys ( ) ; while ( keyIter . hasNext ( ) ) { String facetName = keyIter . next ( ) ; DefaultFacetHandlerInitializerParam param = new DefaultFacetHandlerInitializerParam ( ) ; JSONObject jsonParams = facetInitParams . getJSONObject ( facetName ) ; if ( jsonParams != null && jsonParams . length ( ) > <NUM_LIT:0> ) { Iterator < String > paramIter = jsonParams . keys ( ) ; while ( paramIter . hasNext ( ) ) { String paramName = paramIter . next ( ) ; JSONObject jsonParamValues = jsonParams . getJSONObject ( paramName ) ; String type = jsonParamValues . optString ( RequestConverter2 . FACETINIT_TYPE , RequestConverter2 . FACETINIT_TYPE_STRING ) ; JSONArray jsonValues = jsonParamValues . optJSONArray ( RequestConverter2 . FACETINIT_VALUES ) ; if ( jsonValues == null ) { Object value = jsonParamValues . opt ( RequestConverter2 . FACETINIT_VALUES ) ; if ( value != null ) { jsonValues = new JSONArray ( ) . put ( value ) ; } } if ( jsonValues != null ) { if ( type . equals ( RequestConverter2 . FACETINIT_TYPE_INT ) ) param . putIntParam ( paramName , convertJSONToIntArray ( jsonValues ) ) ; else if ( type . equals ( RequestConverter2 . FACETINIT_TYPE_STRING ) ) param . putStringParam ( paramName , convertJSONToStringArray ( jsonValues ) ) ; else if ( type . equals ( RequestConverter2 . FACETINIT_TYPE_BOOLEAN ) ) param . putBooleanParam ( paramName , convertJSONToBoolArray ( jsonValues ) ) ; else if ( type . equals ( RequestConverter2 . FACETINIT_TYPE_LONG ) ) param . putLongParam ( paramName , convertJSONToLongArray ( jsonValues ) ) ; else if ( type . equals ( RequestConverter2 . FACETINIT_TYPE_BYTES ) ) param . putByteArrayParam ( paramName , convertJSONToByteArray ( jsonValues ) ) ; else if ( type . equals ( RequestConverter2 . FACETINIT_TYPE_DOUBLE ) ) param . putDoubleParam ( paramName , convertJSONToDoubleArray ( jsonValues ) ) ; } } req . setFacetHandlerInitializerParam ( facetName , param ) ; } } } JSONArray sortArray = json . optJSONArray ( RequestConverter2 . SORT ) ; if ( sortArray != null && sortArray . length ( ) > <NUM_LIT:0> ) { ArrayList < SortField > sortFieldList = new ArrayList < SortField > ( sortArray . length ( ) ) ; for ( int i = <NUM_LIT:0> ; i < sortArray . length ( ) ; ++ i ) { Object obj = sortArray . opt ( i ) ; if ( obj instanceof JSONObject ) { String field = ( String ) ( ( JSONObject ) obj ) . keys ( ) . next ( ) ; if ( field == null || field . length ( ) == <NUM_LIT:0> ) continue ; if ( SORT_SCORE . equals ( field ) || SORT_RELEVANCE . equalsIgnoreCase ( field ) ) { sortFieldList . add ( SortField . FIELD_SCORE ) ; continue ; } String order = ( ( JSONObject ) obj ) . optString ( field ) ; boolean rev = false ; if ( RequestConverter2 . SORT_DESC . equals ( order ) ) rev = true ; sortFieldList . add ( new SortField ( field , SortField . CUSTOM , rev ) ) ; continue ; } else if ( obj instanceof String ) { if ( SORT_SCORE . equals ( obj ) ) { sortFieldList . add ( SortField . FIELD_SCORE ) ; continue ; } } } if ( sortFieldList . size ( ) > <NUM_LIT:0> ) { req . setSort ( sortFieldList . toArray ( new SortField [ sortFieldList . size ( ) ] ) ) ; } } boolean fetchStored = json . optBoolean ( RequestConverter2 . FETCH_STORED ) ; req . setFetchStoredFields ( fetchStored ) ; boolean fetchStoredValue = json . optBoolean ( RequestConverter2 . FETCH_STORED_VALUE ) ; req . setFetchStoredValue ( fetchStoredValue ) ; String [ ] termVectors = getStrings ( json , RequestConverter2 . TERM_VECTORS ) ; if ( termVectors != null && termVectors . length > <NUM_LIT:0> ) { req . setTermVectorsToFetch ( new HashSet < String > ( Arrays . asList ( termVectors ) ) ) ; } req . setPartitions ( getIntSet ( json , RequestConverter2 . PARTITIONS , <NUM_LIT:0> ) ) ; req . setShowExplanation ( json . optBoolean ( RequestConverter2 . EXPLAIN , false ) ) ; String routeParam = json . optString ( RequestConverter2 . ROUTEPARAM , null ) ; req . setRouteParam ( routeParam ) ; return req ; } private static String [ ] formatValues ( String facet , String [ ] values , final Map < String , String [ ] > facetInfoMap ) { String [ ] facetInfo = facetInfoMap == null ? null : facetInfoMap . get ( facet ) ; if ( facetInfo != null && ( "<STR_LIT>" . equals ( facetInfo [ <NUM_LIT:0> ] ) || "<STR_LIT>" . equals ( facetInfo [ <NUM_LIT:0> ] ) ) ) { MetaType metaType = null ; String formatString = null ; DecimalFormat formatter = null ; String type = facetInfo [ <NUM_LIT:1> ] ; if ( "<STR_LIT:int>" . equals ( type ) ) { metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( int . class ) ; formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; for ( int i = <NUM_LIT:0> ; i < values . length ; ++ i ) { values [ i ] = formatter . format ( Integer . parseInt ( values [ i ] ) ) ; } } else if ( "<STR_LIT>" . equals ( type ) ) { metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( short . class ) ; formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; for ( int i = <NUM_LIT:0> ; i < values . length ; ++ i ) { values [ i ] = formatter . format ( Short . parseShort ( values [ i ] ) ) ; } } else if ( "<STR_LIT:long>" . equals ( type ) ) { metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( long . class ) ; formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; for ( int i = <NUM_LIT:0> ; i < values . length ; ++ i ) { values [ i ] = formatter . format ( Long . parseLong ( values [ i ] ) ) ; } } else if ( "<STR_LIT:float>" . equals ( type ) ) { metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( float . class ) ; formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; for ( int i = <NUM_LIT:0> ; i < values . length ; ++ i ) { values [ i ] = formatter . format ( Float . parseFloat ( values [ i ] ) ) ; } } else if ( "<STR_LIT:double>" . equals ( type ) ) { metaType = DefaultSenseiInterpreter . CLASS_METATYPE_MAP . get ( double . class ) ; formatString = DefaultSenseiInterpreter . DEFAULT_FORMAT_STRING_MAP . get ( metaType ) ; formatter = new DecimalFormat ( formatString , new DecimalFormatSymbols ( Locale . US ) ) ; for ( int i = <NUM_LIT:0> ; i < values . length ; ++ i ) { values [ i ] = formatter . format ( Double . parseDouble ( values [ i ] ) ) ; } } } return values ; } private static void addSelection ( String type , JSONObject jsonSel , SenseiRequest req , final Map < String , String [ ] > facetInfoMap ) throws Exception { if ( RequestConverter2 . SELECTIONS_TERM . equals ( type ) ) { Iterator < String > iter = jsonSel . keys ( ) ; if ( iter . hasNext ( ) ) { String facet = iter . next ( ) ; JSONObject jsonParams = jsonSel . optJSONObject ( facet ) ; String value = jsonParams . optString ( RequestConverter2 . SELECTIONS_TERM_VALUE , null ) ; if ( facet != null && value != null ) { BrowseSelection sel = new BrowseSelection ( facet ) ; String [ ] vals = new String [ <NUM_LIT:1> ] ; vals [ <NUM_LIT:0> ] = value ; sel . setValues ( formatValues ( facet , vals , facetInfoMap ) ) ; req . addSelection ( sel ) ; } } } else if ( RequestConverter2 . SELECTIONS_TERMS . equals ( type ) ) { Iterator < String > iter = jsonSel . keys ( ) ; if ( iter . hasNext ( ) ) { String facet = iter . next ( ) ; JSONObject jsonParams = jsonSel . optJSONObject ( facet ) ; JSONArray values = jsonParams . optJSONArray ( RequestConverter2 . SELECTIONS_TERMS_VALUES ) ; JSONArray excludes = jsonParams . optJSONArray ( RequestConverter2 . SELECTIONS_TERMS_EXCLUDES ) ; String operator = jsonParams . optString ( RequestConverter2 . SELECTIONS_TERMS_OPERATOR , RequestConverter2 . SELECTIONS_TERMS_OPERATOR_OR ) ; if ( facet != null && ( values != null || excludes != null ) ) { BrowseSelection sel = new BrowseSelection ( facet ) ; ValueOperation op = ValueOperation . ValueOperationOr ; if ( RequestConverter2 . SELECTIONS_TERMS_OPERATOR_AND . equals ( operator ) ) op = ValueOperation . ValueOperationAnd ; if ( values != null && values . length ( ) > <NUM_LIT:0> ) { sel . setValues ( formatValues ( facet , getStrings ( values ) , facetInfoMap ) ) ; } if ( excludes != null && excludes . length ( ) > <NUM_LIT:0> ) { sel . setNotValues ( formatValues ( facet , getStrings ( excludes ) , facetInfoMap ) ) ; } sel . setSelectionOperation ( op ) ; req . addSelection ( sel ) ; } } } else if ( RequestConverter2 . SELECTIONS_RANGE . equals ( type ) ) { Iterator < String > iter = jsonSel . keys ( ) ; if ( iter . hasNext ( ) ) { String facet = iter . next ( ) ; JSONObject jsonParams = jsonSel . optJSONObject ( facet ) ; String upper = jsonParams . optString ( RequestConverter2 . SELECTIONS_RANGE_TO , "<STR_LIT:*>" ) ; String lower = jsonParams . optString ( RequestConverter2 . SELECTIONS_RANGE_FROM , "<STR_LIT:*>" ) ; boolean includeUpper = jsonParams . optBoolean ( RequestConverter2 . SELECTIONS_RANGE_INCLUDE_UPPER , true ) ; boolean includeLower = jsonParams . optBoolean ( RequestConverter2 . SELECTIONS_RANGE_INCLUDE_LOWER , true ) ; String left = "<STR_LIT:[>" , right = "<STR_LIT:]>" ; if ( includeLower == false ) left = "<STR_LIT:(>" ; if ( includeUpper == false ) right = "<STR_LIT:)>" ; String range = left + lower + "<STR_LIT>" + upper + right ; if ( facet != null ) { BrowseSelection sel = new BrowseSelection ( facet ) ; String [ ] vals = new String [ <NUM_LIT:1> ] ; vals [ <NUM_LIT:0> ] = range ; sel . setValues ( vals ) ; req . addSelection ( sel ) ; } } } else if ( RequestConverter2 . SELECTIONS_PATH . equals ( type ) ) { Iterator < String > iter = jsonSel . keys ( ) ; if ( iter . hasNext ( ) ) { String facet = iter . next ( ) ; JSONObject jsonParams = jsonSel . optJSONObject ( facet ) ; String value = jsonParams . optString ( RequestConverter2 . SELECTIONS_PATH_VALUE , null ) ; if ( facet != null && value != null ) { BrowseSelection sel = new BrowseSelection ( facet ) ; String [ ] vals = new String [ <NUM_LIT:1> ] ; vals [ <NUM_LIT:0> ] = value ; sel . setValues ( vals ) ; if ( jsonParams . has ( RequestConverter2 . SELECTIONS_PATH_STRICT ) ) { boolean strict = jsonParams . optBoolean ( RequestConverter2 . SELECTIONS_PATH_STRICT , false ) ; sel . getSelectionProperties ( ) . setProperty ( PathFacetHandler . SEL_PROP_NAME_STRICT , String . valueOf ( strict ) ) ; } if ( jsonParams . has ( RequestConverter2 . SELECTIONS_PATH_DEPTH ) ) { int depth = jsonParams . optInt ( RequestConverter2 . SELECTIONS_PATH_DEPTH , <NUM_LIT:1> ) ; sel . getSelectionProperties ( ) . setProperty ( PathFacetHandler . SEL_PROP_NAME_DEPTH , String . valueOf ( depth ) ) ; } req . addSelection ( sel ) ; } } } else if ( RequestConverter2 . SELECTIONS_CUSTOM . equals ( type ) ) { ; } else if ( RequestConverter2 . SELECTIONS_DEFAULT . equals ( type ) ) { ; } } private static Map < String , String > createFacetProperties ( JSONObject facetJson ) { Map < String , String > ret = new HashMap < String , String > ( ) ; JSONObject params = facetJson . optJSONObject ( "<STR_LIT>" ) ; if ( params == null ) { return ret ; } Iterator < String > iter = params . keys ( ) ; if ( iter . hasNext ( ) ) { String key = iter . next ( ) ; Object val = params . opt ( key ) ; if ( val != null ) { ret . put ( key , val . toString ( ) ) ; } } return ret ; } private static double [ ] convertJSONToDoubleArray ( JSONArray jsonArray ) throws JSONException { double [ ] doubleArray = new double [ jsonArray . length ( ) ] ; if ( jsonArray != null && jsonArray . length ( ) > <NUM_LIT:0> ) { for ( int i = <NUM_LIT:0> ; i < jsonArray . length ( ) ; i ++ ) { doubleArray [ i ] = jsonArray . getDouble ( i ) ; } } return doubleArray ; } private static byte [ ] convertJSONToByteArray ( JSONArray jsonArray ) throws Exception { if ( jsonArray != null && jsonArray . length ( ) == <NUM_LIT:1> ) { String base64 = jsonArray . getString ( <NUM_LIT:0> ) ; byte [ ] bytes = Base64 . decodeBase64 ( base64 ) ; return bytes ; } else throw new Exception ( "<STR_LIT>" ) ; } private static long [ ] convertJSONToLongArray ( JSONArray jsonArray ) throws JSONException { long [ ] longArray = new long [ jsonArray . length ( ) ] ; if ( jsonArray != null && jsonArray . length ( ) > <NUM_LIT:0> ) { for ( int i = <NUM_LIT:0> ; i < jsonArray . length ( ) ; i ++ ) { longArray [ i ] = Long . parseLong ( jsonArray . getString ( i ) ) ; } } return longArray ; } private static boolean [ ] convertJSONToBoolArray ( JSONArray jsonArray ) throws JSONException { boolean [ ] boolArray = new boolean [ jsonArray . length ( ) ] ; if ( jsonArray != null && jsonArray . length ( ) > <NUM_LIT:0> ) { for ( int i = <NUM_LIT:0> ; i < jsonArray . length ( ) ; i ++ ) { boolArray [ i ] = jsonArray . getBoolean ( i ) ; } } return boolArray ; } private static List < String > convertJSONToStringArray ( JSONArray jsonArray ) throws JSONException { List < String > arString = new ArrayList < String > ( ) ; if ( jsonArray != null && jsonArray . length ( ) > <NUM_LIT:0> ) { for ( int i = <NUM_LIT:0> ; i < jsonArray . length ( ) ; i ++ ) { arString . add ( jsonArray . getString ( i ) ) ; } } return arString ; } private static int [ ] convertJSONToIntArray ( JSONArray jsonArray ) throws JSONException { int [ ] intArray = new int [ jsonArray . length ( ) ] ; if ( jsonArray != null && jsonArray . length ( ) > <NUM_LIT:0> ) { for ( int i = <NUM_LIT:0> ; i < jsonArray . length ( ) ; i ++ ) { intArray [ i ] = jsonArray . getInt ( i ) ; } } return intArray ; } } </s>
<s> package com . senseidb . util ; import java . lang . Thread . UncaughtExceptionHandler ; import org . apache . log4j . Logger ; public class SenseiUncaughtExceptionHandler implements UncaughtExceptionHandler { private static Logger logger = Logger . getLogger ( SenseiUncaughtExceptionHandler . class ) ; private static SenseiUncaughtExceptionHandler instance = new SenseiUncaughtExceptionHandler ( ) ; public static SenseiUncaughtExceptionHandler getInstance ( ) { return instance ; } public static void setAsDefaultForAllThreads ( ) { synchronized ( SenseiUncaughtExceptionHandler . class ) { if ( Thread . getDefaultUncaughtExceptionHandler ( ) != instance ) { Thread . setDefaultUncaughtExceptionHandler ( instance ) ; } } } @ Override public void uncaughtException ( Thread thread , Throwable throwable ) { logger . fatal ( String . format ( "<STR_LIT>" , thread . toString ( ) ) , throwable ) ; } } </s>
<s> package com . senseidb . plugin ; import java . util . Map ; public interface SenseiPlugin { public void init ( Map < String , String > config , SenseiPluginRegistry pluginRegistry ) ; public void start ( ) ; public void stop ( ) ; } </s>
<s> package com . senseidb . plugin ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; import com . browseengine . bobo . facets . data . TermListFactory ; import com . browseengine . bobo . facets . FacetHandler ; public abstract class AbstractFacetHandlerSenseiPluginFactory implements SenseiPluginFactory < FacetHandler > { public static final String DEPENDS = "<STR_LIT>" ; public Set < String > getDepends ( Map < String , String > initProperties ) { Set < String > depends = new HashSet < String > ( ) ; String val = initProperties . get ( DEPENDS ) ; if ( val != null ) { for ( String depend : val . split ( "<STR_LIT:U+002C>" ) ) { depend = depend . trim ( ) ; if ( depend . length ( ) != <NUM_LIT:0> ) depends . add ( depend ) ; } } return depends ; } @ Override public abstract FacetHandler getBean ( Map < String , String > initProperties , String fullPrefix , SenseiPluginRegistry pluginRegistry ) ; } </s>
<s> package com . senseidb . plugin ; import java . util . Date ; import java . util . HashMap ; import java . util . Map ; import com . browseengine . bobo . facets . data . TermFixedLengthLongArrayListFactory ; import com . browseengine . bobo . facets . data . TermListFactory ; import com . senseidb . indexing . DefaultSenseiInterpreter ; public class TermListFactorySenseiPluginFactory implements SenseiPluginFactory < TermListFactory > { public static final String FIXEDLENGTHLONG = "<STR_LIT>" ; public static final String LENGTH = "<STR_LIT>" ; public static final String TYPE = "<STR_LIT:type>" ; public static final String INT = "<STR_LIT:int>" ; public static final String STRING = "<STR_LIT:string>" ; public static final String SHORT = "<STR_LIT>" ; public static final String LONG = "<STR_LIT:long>" ; public static final String FLOAT = "<STR_LIT:float>" ; public static final String DOUBLE = "<STR_LIT:double>" ; public static final String CHAR = "<STR_LIT>" ; public static final String BOOLEAN = "<STR_LIT:boolean>" ; public static final String DATE = "<STR_LIT:date>" ; private static final Map < String , Class > TYPE_CLASS_MAP = new HashMap < String , Class > ( ) ; static { TYPE_CLASS_MAP . put ( INT , int . class ) ; TYPE_CLASS_MAP . put ( STRING , String . class ) ; TYPE_CLASS_MAP . put ( SHORT , short . class ) ; TYPE_CLASS_MAP . put ( LONG , long . class ) ; TYPE_CLASS_MAP . put ( FLOAT , float . class ) ; TYPE_CLASS_MAP . put ( DOUBLE , double . class ) ; TYPE_CLASS_MAP . put ( CHAR , char . class ) ; TYPE_CLASS_MAP . put ( BOOLEAN , boolean . class ) ; TYPE_CLASS_MAP . put ( DATE , Date . class ) ; } public static TermListFactory getFactory ( String type ) { Class cls = TYPE_CLASS_MAP . get ( type ) ; if ( cls != null ) { return DefaultSenseiInterpreter . getTermListFactory ( cls ) ; } return null ; } @ Override public TermListFactory getBean ( Map < String , String > initProperties , String fullPrefix , SenseiPluginRegistry pluginRegistry ) { String type = initProperties . get ( TYPE ) ; if ( FIXEDLENGTHLONG . equals ( type ) ) { return new TermFixedLengthLongArrayListFactory ( Integer . parseInt ( initProperties . get ( LENGTH ) ) ) ; } return getFactory ( type ) ; } } </s>
<s> package com . senseidb . plugin ; import java . util . Map ; public class AbstractSenseiPlugin implements SenseiPlugin { protected Map < String , String > config ; protected SenseiPluginRegistry pluginRegistry ; @ Override public void init ( Map < String , String > config , SenseiPluginRegistry pluginRegistry ) { this . config = config ; this . pluginRegistry = pluginRegistry ; } @ Override public void start ( ) { } @ Override public void stop ( ) { } } </s>
<s> package com . senseidb . plugin ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . IdentityHashMap ; import java . util . Iterator ; import java . util . LinkedHashMap ; import java . util . List ; import java . util . Map ; import org . apache . commons . configuration . Configuration ; import com . browseengine . bobo . facets . FacetHandler ; import com . browseengine . bobo . facets . RuntimeFacetHandlerFactory ; public class SenseiPluginRegistry { public static final String FACET_CONF_PREFIX = "<STR_LIT>" ; private Map < String , PluginHolder > pluginsByPrefix = new LinkedHashMap < String , PluginHolder > ( ) ; private Map < String , PluginHolder > pluginsByNames = new LinkedHashMap < String , PluginHolder > ( ) ; private List < PluginHolder > plugins = new ArrayList < PluginHolder > ( ) ; private Configuration configuration ; private static Map < Configuration , SenseiPluginRegistry > cachedRegistries = new IdentityHashMap < Configuration , SenseiPluginRegistry > ( ) ; private SenseiPluginRegistry ( ) { } public static synchronized SenseiPluginRegistry get ( Configuration conf ) { return cachedRegistries . get ( conf ) ; } public static String getNameByPrefix ( String prefix ) { if ( prefix != null ) { if ( prefix . contains ( "<STR_LIT:.>" ) ) return prefix . substring ( prefix . lastIndexOf ( "<STR_LIT:.>" ) + <NUM_LIT:1> ) ; else return prefix ; } return null ; } public static synchronized SenseiPluginRegistry build ( Configuration conf ) { if ( cachedRegistries . containsKey ( conf ) ) { return cachedRegistries . get ( conf ) ; } SenseiPluginRegistry ret = new SenseiPluginRegistry ( ) ; ret . configuration = conf ; Iterator keysIterator = conf . getKeys ( ) ; while ( keysIterator . hasNext ( ) ) { String key = ( String ) keysIterator . next ( ) ; if ( key . endsWith ( "<STR_LIT:.class>" ) ) { String prefix = key . substring ( <NUM_LIT:0> , key . indexOf ( "<STR_LIT:.class>" ) ) ; String pluginName = getNameByPrefix ( prefix ) ; String pluginCLass = conf . getString ( key ) ; ret . plugins . add ( new PluginHolder ( ret , pluginCLass , pluginName , prefix ) ) ; } if ( key . endsWith ( "<STR_LIT>" ) ) { String prefix = key . substring ( <NUM_LIT:0> , key . indexOf ( "<STR_LIT>" ) ) ; String pluginName = getNameByPrefix ( prefix ) ; Object pluginInstance = conf . getProperty ( key ) ; ret . plugins . add ( new PluginHolder ( ret , pluginInstance , pluginName , prefix ) ) ; } } for ( PluginHolder pluginHolder : ret . plugins ) { ret . pluginsByPrefix . put ( pluginHolder . fullPrefix , pluginHolder ) ; ret . pluginsByNames . put ( pluginHolder . pluginName , pluginHolder ) ; Iterator propertyIterator = conf . getKeys ( pluginHolder . fullPrefix ) ; while ( propertyIterator . hasNext ( ) ) { String propertyName = ( String ) propertyIterator . next ( ) ; if ( propertyName . endsWith ( "<STR_LIT:.class>" ) ) { continue ; } String property = propertyName ; if ( propertyName . contains ( pluginHolder . fullPrefix ) ) { property = propertyName . substring ( pluginHolder . fullPrefix . length ( ) + <NUM_LIT:1> ) ; } pluginHolder . properties . put ( property , conf . getProperty ( propertyName ) . toString ( ) ) ; } } cachedRegistries . put ( conf , ret ) ; return ret ; } public < T > T getBeanByName ( String name , Class < T > type ) { PluginHolder holder = pluginsByNames . get ( name ) ; if ( holder == null ) { return null ; } return ( T ) holder . getInstance ( ) ; } public < T > List < T > getBeansByType ( Class < T > type ) { List < T > ret = new ArrayList < T > ( ) ; for ( PluginHolder pluginHolder : plugins ) { if ( pluginHolder . getInstance ( ) != null && type . isAssignableFrom ( pluginHolder . getInstance ( ) . getClass ( ) ) ) { ret . add ( ( T ) pluginHolder . getInstance ( ) ) ; } } return ret ; } public < T > Map < String , T > getNamedBeansByType ( Class < T > type ) { Map < String , T > ret = new HashMap < String , T > ( ) ; for ( PluginHolder pluginHolder : plugins ) { if ( pluginHolder . getInstance ( ) != null && type . isAssignableFrom ( pluginHolder . getInstance ( ) . getClass ( ) ) ) { ret . put ( pluginHolder . pluginName , ( T ) pluginHolder . getInstance ( ) ) ; } } return ret ; } public List < ? > getBeansByPrefix ( String prefix ) { List < Object > ret = new ArrayList < Object > ( ) ; for ( PluginHolder pluginHolder : plugins ) { if ( pluginHolder . getInstance ( ) != null && pluginHolder . fullPrefix . startsWith ( prefix ) ) { ret . add ( pluginHolder . getInstance ( ) ) ; } } return ret ; } public FacetHandler < ? > getFacet ( String name ) { for ( Object handlerObject : resolveBeansByListKey ( FACET_CONF_PREFIX , Object . class ) ) { if ( ! ( handlerObject instanceof FacetHandler ) ) { continue ; } FacetHandler handler = ( FacetHandler ) handlerObject ; if ( handler . getName ( ) . equals ( name ) ) { return handler ; } } return null ; } public RuntimeFacetHandlerFactory getRuntimeFacet ( String name ) { for ( Object handlerObject : resolveBeansByListKey ( FACET_CONF_PREFIX , Object . class ) ) { if ( ! ( handlerObject instanceof RuntimeFacetHandlerFactory ) ) { continue ; } RuntimeFacetHandlerFactory handler = ( RuntimeFacetHandlerFactory ) handlerObject ; if ( handler . getName ( ) . equals ( name ) ) { return handler ; } } return null ; } public < T > T getBeanByFullPrefix ( String fullPrefix , Class < T > type ) { PluginHolder holder = pluginsByPrefix . get ( fullPrefix ) ; if ( holder == null ) { return null ; } return ( T ) holder . getInstance ( ) ; } public < T > List < T > resolveBeansByListKey ( String paramKey , Class < T > returnedClass ) { if ( ! paramKey . endsWith ( "<STR_LIT>" ) ) { paramKey = paramKey + "<STR_LIT>" ; } List < T > ret = new ArrayList < T > ( ) ; String strList = configuration . getString ( paramKey ) ; if ( strList == null ) { return new ArrayList < T > ( ) ; } String [ ] keys = strList . split ( "<STR_LIT:U+002C>" ) ; if ( keys == null || keys . length == <NUM_LIT:0> ) { return null ; } for ( String key : keys ) { if ( key . trim ( ) . length ( ) == <NUM_LIT:0> ) { continue ; } Object bean = getBeanByName ( key . trim ( ) , Object . class ) ; if ( bean == null ) { bean = getBeanByFullPrefix ( key . trim ( ) , Object . class ) ; } if ( bean == null ) { throw new IllegalStateException ( "<STR_LIT>" + key + "<STR_LIT>" ) ; } if ( bean instanceof Collection ) { ret . addAll ( ( Collection ) bean ) ; } else { ret . add ( ( T ) bean ) ; } } return ret ; } public synchronized void start ( ) { for ( PluginHolder pluginHolder : plugins ) { Object instance = pluginHolder . getInstance ( ) ; if ( instance instanceof SenseiPlugin ) { ( ( SenseiPlugin ) instance ) . start ( ) ; } } } public synchronized void stop ( ) { for ( PluginHolder pluginHolder : plugins ) { Object instance = pluginHolder . getInstance ( ) ; if ( instance instanceof SenseiPlugin ) { ( ( SenseiPlugin ) instance ) . stop ( ) ; } } pluginsByPrefix . clear ( ) ; pluginsByNames . clear ( ) ; plugins . clear ( ) ; cachedRegistries . remove ( configuration ) ; configuration = null ; } public Configuration getConfiguration ( ) { return configuration ; } } </s>
<s> package com . senseidb . plugin ; import java . util . Map ; import com . browseengine . bobo . facets . data . FacetDataFetcher ; import com . browseengine . bobo . facets . data . TermListFactory ; import com . browseengine . bobo . facets . FacetHandler ; import com . browseengine . bobo . facets . impl . VirtualSimpleFacetHandler ; public class VirtualSimpleFacetHandlerSenseiPluginFactory extends AbstractFacetHandlerSenseiPluginFactory { public static final String TERMLISTFACTORY = "<STR_LIT>" ; public static final String FACETDATAFETCHER = "<STR_LIT>" ; @ Override public FacetHandler getBean ( Map < String , String > initProperties , String fullPrefix , SenseiPluginRegistry pluginRegistry ) { FacetDataFetcher facetDataFetcher = pluginRegistry . getBeanByName ( initProperties . get ( FACETDATAFETCHER ) , FacetDataFetcher . class ) ; if ( facetDataFetcher == null ) throw new IllegalArgumentException ( FACETDATAFETCHER + "<STR_LIT>" ) ; TermListFactory termListFactory = TermListFactorySenseiPluginFactory . getFactory ( initProperties . get ( TERMLISTFACTORY ) ) ; if ( termListFactory == null ) { termListFactory = pluginRegistry . getBeanByName ( initProperties . get ( TERMLISTFACTORY ) , TermListFactory . class ) ; } return new VirtualSimpleFacetHandler ( SenseiPluginRegistry . getNameByPrefix ( fullPrefix ) , termListFactory , facetDataFetcher , getDepends ( initProperties ) ) ; } } </s>
<s> package com . senseidb . plugin ; import java . util . LinkedHashMap ; import java . util . Map ; class PluginHolder { private final SenseiPluginRegistry senseiPluginRegistry ; String pluginCLass ; String pluginName ; String fullPrefix ; Object instance ; private Object factoryCreatedInstance ; Map < String , String > properties = new LinkedHashMap < String , String > ( ) ; public PluginHolder ( SenseiPluginRegistry senseiPluginRegistry , String pluginCLass , String pluginName , String fullPrefix ) { this . senseiPluginRegistry = senseiPluginRegistry ; this . pluginCLass = pluginCLass ; this . pluginName = pluginName ; this . fullPrefix = fullPrefix ; } public PluginHolder ( SenseiPluginRegistry senseiPluginRegistry , Object instance , String pluginName , String fullPrefix ) { this . senseiPluginRegistry = senseiPluginRegistry ; this . instance = instance ; this . pluginName = pluginName ; this . fullPrefix = fullPrefix ; } public Object getInstance ( ) { if ( instance == null ) { synchronized ( this ) { try { instance = Class . forName ( pluginCLass ) . newInstance ( ) ; if ( instance instanceof SenseiPlugin ) { ( ( SenseiPlugin ) instance ) . init ( properties , senseiPluginRegistry ) ; } } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } } if ( instance instanceof SenseiPluginFactory ) { if ( factoryCreatedInstance == null ) { synchronized ( instance ) { factoryCreatedInstance = ( ( SenseiPluginFactory ) instance ) . getBean ( properties , fullPrefix , this . senseiPluginRegistry ) ; } } return factoryCreatedInstance ; } return instance ; } } </s>
<s> package com . senseidb . plugin ; import java . util . Map ; public interface SenseiPluginFactory < T > { T getBean ( Map < String , String > initProperties , String fullPrefix , SenseiPluginRegistry pluginRegistry ) ; } </s>