target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testHandlerIsNotExecutedWithIndexingRequestWithTooManyProducts() { String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ \"1\",\"2\",\"3\",\"4\",\"5\" ]"+ "}"; processor.processRequest(configuation, ByteBuffer.wrap(json.getBytes())); assertEquals(0,handler.getNumberOfCalls()); }
@Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); @Override IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data); @PreDestroy void shutdown(); }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); @Override IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data); @PreDestroy void shutdown(); }
@Test public void testHandlerIsNotExecutedWithIndexingRequestWithNoProducts() { String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ ]"+ "}"; processor.processRequest(configuation, ByteBuffer.wrap(json.getBytes())); assertEquals(0,handler.getNumberOfCalls()); }
@Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); @Override IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data); @PreDestroy void shutdown(); }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); @Override IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data); @PreDestroy void shutdown(); }
@Test public void testHandlerIsCalled() { String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ \"1\" ]"+ "}"; processor.processRequest(configuation, ByteBuffer.wrap(json.getBytes())); try { handler.getLatch().await(5000, TimeUnit.MILLISECONDS); } catch(Exception e) { fail("Failed waiting for disruptor to call the handler"); } assertEquals(1,handler.getNumberOfCalls()); }
@Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); @Override IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data); @PreDestroy void shutdown(); }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); @Override IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data); @PreDestroy void shutdown(); }
@Test public void testSearchHandlerSize() { System.setProperty(ConfigurationConstants.PROPNAME_SIZE_OF_RELATED_CONTENT_SEARCH_REQUEST_QUEUE, "32768"); SystemPropertiesConfiguration config = new SystemPropertiesConfiguration(); System.out.println(Util.ceilingNextPowerOfTwo(config.getSizeOfRelatedItemSearchRequestHandlerQueue())); }
public int getSizeOfRelatedItemSearchRequestHandlerQueue() { return SIZE_OF_RELATED_CONTENT_SEARCH_REQUEST_HANDLER_QUEUE; }
SystemPropertiesConfiguration implements Configuration { public int getSizeOfRelatedItemSearchRequestHandlerQueue() { return SIZE_OF_RELATED_CONTENT_SEARCH_REQUEST_HANDLER_QUEUE; } }
SystemPropertiesConfiguration implements Configuration { public int getSizeOfRelatedItemSearchRequestHandlerQueue() { return SIZE_OF_RELATED_CONTENT_SEARCH_REQUEST_HANDLER_QUEUE; } SystemPropertiesConfiguration(); protected SystemPropertiesConfiguration(Map<String,Object> properties); }
SystemPropertiesConfiguration implements Configuration { public int getSizeOfRelatedItemSearchRequestHandlerQueue() { return SIZE_OF_RELATED_CONTENT_SEARCH_REQUEST_HANDLER_QUEUE; } SystemPropertiesConfiguration(); protected SystemPropertiesConfiguration(Map<String,Object> properties); static Map<String,Object> mergeProperties(Map<String,Object> defaultProperties, Map<String,Object> overrides); static Map<String,Object> replaceProperties(Map<String,Object> defaultProperties, Map<String,Object> overrides); static Map<String,Object> parseSystemProperties(); static Map<String,Object> parseProperties(Map<String,String> propertiesToConvert); WaitStrategyFactory getWaitStrategyFactory(); int getMaxNumberOfSearchCriteriaForRelatedContent(); int getSizeOfRelatedItemSearchRequestHandlerQueue(); int getSizeOfRelatedItemSearchRequestQueue(); @Override int getSizeOfRelatedItemSearchRequestAndResponseQueue(); @Override int getSizeOfResponseProcessingQueue(); @Override int getNumberOfSearchingRequestProcessors(); @Override int getNumberOfExpectedLikeForLikeRequests(); @Override String getKeyForFrequencyResultOccurrence(); @Override String getKeyForFrequencyResultId(); @Override String getKeyForFrequencyResults(); @Override String getKeyForFrequencyResultOverallResultsSize(); @Override String getKeyForFrequencyResultSource(); @Override String getKeyForIndexRequestRelatedWithAttr(); @Override String getKeyForIndexRequestDateAttr(); @Override String getKeyForIndexRequestIdAttr(); @Override String getKeyForIndexRequestProductArrayAttr(); @Override String getRequestParameterForSize(); @Override String getRequestParameterForId(); @Override int getDefaultNumberOfResults(); @Override String getStorageIndexNamePrefix(); @Override String getStorageIndexNameAlias(); @Override String getStorageContentTypeName(); @Override String getStorageClusterName(); @Override String getStorageFrequentlyRelatedItemsFacetResultsFacetName(); @Override String getElasticSearchClientDefaultNodeSettingFileName(); @Override String getElasticSearchClientDefaultTransportSettingFileName(); @Override String getElasticSearchClientOverrideSettingFileName(); @Override String getStorageLocationMapper(); @Override long getFrequentlyRelatedItemsSearchTimeoutInMillis(); @Override int getResponseCode(SearchResultsOutcome type); @Override int getTimedOutSearchRequestStatusCode(); @Override int getFailedSearchRequestStatusCode(); @Override int getNoFoundSearchResultsStatusCode(); @Override int getFoundSearchResultsStatusCode(); @Override int getMissingSearchResultsHandlerStatusCode(); @Override int getNumberOfIndexingRequestProcessors(); @Override int getMaxNumberOfRelatedItemProperties(); @Override int getMaxNumberOfRelatedItemsPerItem(); @Override int getRelatedItemIdLength(); @Override int getMaxRelatedItemPostDataSizeInBytes(); @Override int getMinRelatedItemPostDataSizeInBytes(); @Override int getRelatedItemAdditionalPropertyKeyLength(); @Override int getRelatedItemAdditionalPropertyValueLength(); @Override boolean isSearchResponseDebugOutputEnabled(); @Override int getIndexBatchSize(); @Override int getSizeOfBatchIndexingRequestQueue(); @Override int getSizeOfIncomingMessageQueue(); @Override String getPropertyEncoding(); @Override boolean isIndexNameDateCachingEnabled(); @Override int getNumberOfIndexNamesToCache(); @Override boolean getShouldReplaceOldContentIfExists(); @Override boolean getShouldUseSeparateIndexStorageThread(); @Override boolean shouldDiscardIndexRequestWithTooManyRelations(); @Override ElasticeSearchClientType getElasticSearchClientType(); @Override String getElasticSearchTransportHosts(); @Override int getDefaultElasticSearchPort(); @Override String getElasticSearchHttpHosts(); @Override int getElasticSearchHttpPort(); @Override String getKeyForStorageResponseTime(); @Override String getKeyForStorageGetResponseTime(); @Override String getKeyForSearchProcessingResponseTime(); @Override boolean useSharedSearchRepository(); @Override boolean isSafeToOutputRequestData(); @Override String getStorageFacetExecutionHint(); int getElasticSearchHttpRequestTimeoutMs(); int getElasticSearchHttpConnectionTimeoutMs(); int getElasticSearchHttpNoOfRetries(); boolean getElasticSearchHttpFollowRedirects(); boolean getElasticSearchHttpConnectionPoolingEnabled(); boolean getElasticSearchHttpCompressionEnabled(); int getElasticSearchNodeSniffingHttpRequestTimeoutMs(); int getElasticSearchNodeSniffingHttpConnectionTimeoutMs(); int getElasticSearchNodeSniffingHttpNoOfRetries(); @Override String getElasticSearchNodesSniffingHttpAdminEndpoint(); @Override int getElasticSearchNodesSniffingHttpRetryInterval(); @Override TimeUnit getElasticSearchNodesSniffingRetryIntervalUnit(); @Override boolean getElasticSearchNodesSniffingEnabled(); @Override int getHttpAsyncIndexingRequestTimeout(); @Override int getHttpAsyncSearchingRequestTimeout(); @Override String getRelatedItemsDocumentIndexName(); @Override String getRelatedItemsDocumentTypeName(); @Override String getRelatedItemsDocumentMergingScriptName(); @Override boolean getRelatedItemsDocumentIndexingEnabled(); @Override String getRelatedItemsDocumentComparisonKeyName(); @Override boolean getRemoveRelatedItemsDocumentDateAttribute(); String getElasticSearchMultiSearchEndpoint(); String getElasticSearchMultiGetEndpoint(); }
SystemPropertiesConfiguration implements Configuration { public int getSizeOfRelatedItemSearchRequestHandlerQueue() { return SIZE_OF_RELATED_CONTENT_SEARCH_REQUEST_HANDLER_QUEUE; } SystemPropertiesConfiguration(); protected SystemPropertiesConfiguration(Map<String,Object> properties); static Map<String,Object> mergeProperties(Map<String,Object> defaultProperties, Map<String,Object> overrides); static Map<String,Object> replaceProperties(Map<String,Object> defaultProperties, Map<String,Object> overrides); static Map<String,Object> parseSystemProperties(); static Map<String,Object> parseProperties(Map<String,String> propertiesToConvert); WaitStrategyFactory getWaitStrategyFactory(); int getMaxNumberOfSearchCriteriaForRelatedContent(); int getSizeOfRelatedItemSearchRequestHandlerQueue(); int getSizeOfRelatedItemSearchRequestQueue(); @Override int getSizeOfRelatedItemSearchRequestAndResponseQueue(); @Override int getSizeOfResponseProcessingQueue(); @Override int getNumberOfSearchingRequestProcessors(); @Override int getNumberOfExpectedLikeForLikeRequests(); @Override String getKeyForFrequencyResultOccurrence(); @Override String getKeyForFrequencyResultId(); @Override String getKeyForFrequencyResults(); @Override String getKeyForFrequencyResultOverallResultsSize(); @Override String getKeyForFrequencyResultSource(); @Override String getKeyForIndexRequestRelatedWithAttr(); @Override String getKeyForIndexRequestDateAttr(); @Override String getKeyForIndexRequestIdAttr(); @Override String getKeyForIndexRequestProductArrayAttr(); @Override String getRequestParameterForSize(); @Override String getRequestParameterForId(); @Override int getDefaultNumberOfResults(); @Override String getStorageIndexNamePrefix(); @Override String getStorageIndexNameAlias(); @Override String getStorageContentTypeName(); @Override String getStorageClusterName(); @Override String getStorageFrequentlyRelatedItemsFacetResultsFacetName(); @Override String getElasticSearchClientDefaultNodeSettingFileName(); @Override String getElasticSearchClientDefaultTransportSettingFileName(); @Override String getElasticSearchClientOverrideSettingFileName(); @Override String getStorageLocationMapper(); @Override long getFrequentlyRelatedItemsSearchTimeoutInMillis(); @Override int getResponseCode(SearchResultsOutcome type); @Override int getTimedOutSearchRequestStatusCode(); @Override int getFailedSearchRequestStatusCode(); @Override int getNoFoundSearchResultsStatusCode(); @Override int getFoundSearchResultsStatusCode(); @Override int getMissingSearchResultsHandlerStatusCode(); @Override int getNumberOfIndexingRequestProcessors(); @Override int getMaxNumberOfRelatedItemProperties(); @Override int getMaxNumberOfRelatedItemsPerItem(); @Override int getRelatedItemIdLength(); @Override int getMaxRelatedItemPostDataSizeInBytes(); @Override int getMinRelatedItemPostDataSizeInBytes(); @Override int getRelatedItemAdditionalPropertyKeyLength(); @Override int getRelatedItemAdditionalPropertyValueLength(); @Override boolean isSearchResponseDebugOutputEnabled(); @Override int getIndexBatchSize(); @Override int getSizeOfBatchIndexingRequestQueue(); @Override int getSizeOfIncomingMessageQueue(); @Override String getPropertyEncoding(); @Override boolean isIndexNameDateCachingEnabled(); @Override int getNumberOfIndexNamesToCache(); @Override boolean getShouldReplaceOldContentIfExists(); @Override boolean getShouldUseSeparateIndexStorageThread(); @Override boolean shouldDiscardIndexRequestWithTooManyRelations(); @Override ElasticeSearchClientType getElasticSearchClientType(); @Override String getElasticSearchTransportHosts(); @Override int getDefaultElasticSearchPort(); @Override String getElasticSearchHttpHosts(); @Override int getElasticSearchHttpPort(); @Override String getKeyForStorageResponseTime(); @Override String getKeyForStorageGetResponseTime(); @Override String getKeyForSearchProcessingResponseTime(); @Override boolean useSharedSearchRepository(); @Override boolean isSafeToOutputRequestData(); @Override String getStorageFacetExecutionHint(); int getElasticSearchHttpRequestTimeoutMs(); int getElasticSearchHttpConnectionTimeoutMs(); int getElasticSearchHttpNoOfRetries(); boolean getElasticSearchHttpFollowRedirects(); boolean getElasticSearchHttpConnectionPoolingEnabled(); boolean getElasticSearchHttpCompressionEnabled(); int getElasticSearchNodeSniffingHttpRequestTimeoutMs(); int getElasticSearchNodeSniffingHttpConnectionTimeoutMs(); int getElasticSearchNodeSniffingHttpNoOfRetries(); @Override String getElasticSearchNodesSniffingHttpAdminEndpoint(); @Override int getElasticSearchNodesSniffingHttpRetryInterval(); @Override TimeUnit getElasticSearchNodesSniffingRetryIntervalUnit(); @Override boolean getElasticSearchNodesSniffingEnabled(); @Override int getHttpAsyncIndexingRequestTimeout(); @Override int getHttpAsyncSearchingRequestTimeout(); @Override String getRelatedItemsDocumentIndexName(); @Override String getRelatedItemsDocumentTypeName(); @Override String getRelatedItemsDocumentMergingScriptName(); @Override boolean getRelatedItemsDocumentIndexingEnabled(); @Override String getRelatedItemsDocumentComparisonKeyName(); @Override boolean getRemoveRelatedItemsDocumentDateAttribute(); String getElasticSearchMultiSearchEndpoint(); String getElasticSearchMultiGetEndpoint(); }
@Test public void testCopy() { Configuration c = new SystemPropertiesConfiguration(); RelatedItemSearch searchObject = new RelatedItemSearch(new SystemPropertiesConfiguration()); searchObject.getAdditionalSearchCriteria().addProperty("key","value"); searchObject.getAdditionalSearchCriteria().addProperty("request","response"); searchObject.setRelatedItemId("I am a unique identifier"); searchObject.setMaxResults(1); searchObject.setRelatedItemSearchType(RelatedItemSearchType.FREQUENTLY_RELATED_WITH); RelatedItemSearchLookupKeyGenerator factory = new KeyFactoryBasedRelatedItemSearchLookupKeyGenerator(c,new SipHashSearchRequestLookupKeyFactory()); factory.setSearchRequestLookupKeyOn(searchObject); RelatedItemSearch copy = searchObject.copy(c); assertNotSame(copy,searchObject); assertEquals(copy.getMaxResults(),searchObject.getMaxResults()); assertEquals(copy.getRelatedItemId(),searchObject.getRelatedItemId()); assertEquals(copy.getRelatedItemSearchType(),searchObject.getRelatedItemSearchType()); assertEquals(copy.getLookupKey(),searchObject.getLookupKey()); assertEquals(copy.getAdditionalSearchCriteria().getNumberOfProperties(),searchObject.getAdditionalSearchCriteria().getNumberOfProperties()); assertEquals(copy.getAdditionalSearchCriteria().getPropertyName(0),searchObject.getAdditionalSearchCriteria().getPropertyName(0)); assertEquals(copy.getAdditionalSearchCriteria().getPropertyName(1),searchObject.getAdditionalSearchCriteria().getPropertyName(1)); assertEquals(copy.getAdditionalSearchCriteria().getPropertyValue(0),searchObject.getAdditionalSearchCriteria().getPropertyValue(0)); assertEquals(copy.getAdditionalSearchCriteria().getPropertyValue(1),searchObject.getAdditionalSearchCriteria().getPropertyValue(1)); assertNotSame(copy.getRelatedContentIdentifier(),searchObject.getRelatedContentIdentifier()); assertEquals(copy.getRelatedContentIdentifier().toString(),searchObject.getRelatedContentIdentifier().toString()); }
public RelatedItemSearch copy(Configuration config) { RelatedItemSearch newCopy = new RelatedItemSearch(config,this.getAdditionalSearchCriteria().getNumberOfProperties()); newCopy.setRelatedItemId(this.relatedItemId); newCopy.setMaxResults(this.maxResults); newCopy.setRelatedItemSearchType(this.searchType); newCopy.setLookupKey(this.getLookupKey()); newCopy.setStartOfRequestNanos(this.getStartOfRequestNanos()); this.additionalSearchCriteria.copyTo(newCopy.additionalSearchCriteria); return newCopy; }
RelatedItemSearch { public RelatedItemSearch copy(Configuration config) { RelatedItemSearch newCopy = new RelatedItemSearch(config,this.getAdditionalSearchCriteria().getNumberOfProperties()); newCopy.setRelatedItemId(this.relatedItemId); newCopy.setMaxResults(this.maxResults); newCopy.setRelatedItemSearchType(this.searchType); newCopy.setLookupKey(this.getLookupKey()); newCopy.setStartOfRequestNanos(this.getStartOfRequestNanos()); this.additionalSearchCriteria.copyTo(newCopy.additionalSearchCriteria); return newCopy; } }
RelatedItemSearch { public RelatedItemSearch copy(Configuration config) { RelatedItemSearch newCopy = new RelatedItemSearch(config,this.getAdditionalSearchCriteria().getNumberOfProperties()); newCopy.setRelatedItemId(this.relatedItemId); newCopy.setMaxResults(this.maxResults); newCopy.setRelatedItemSearchType(this.searchType); newCopy.setLookupKey(this.getLookupKey()); newCopy.setStartOfRequestNanos(this.getStartOfRequestNanos()); this.additionalSearchCriteria.copyTo(newCopy.additionalSearchCriteria); return newCopy; } RelatedItemSearch(Configuration config); RelatedItemSearch(Configuration config,int numberOfAdditionalSearchCriteria); }
RelatedItemSearch { public RelatedItemSearch copy(Configuration config) { RelatedItemSearch newCopy = new RelatedItemSearch(config,this.getAdditionalSearchCriteria().getNumberOfProperties()); newCopy.setRelatedItemId(this.relatedItemId); newCopy.setMaxResults(this.maxResults); newCopy.setRelatedItemSearchType(this.searchType); newCopy.setLookupKey(this.getLookupKey()); newCopy.setStartOfRequestNanos(this.getStartOfRequestNanos()); this.additionalSearchCriteria.copyTo(newCopy.additionalSearchCriteria); return newCopy; } RelatedItemSearch(Configuration config); RelatedItemSearch(Configuration config,int numberOfAdditionalSearchCriteria); void setMaxResults(int maxResults); int getMaxResults(); RelatedItemAdditionalProperties getAdditionalSearchCriteria(); void setRelatedItemId(String id); String getRelatedItemId(); RelatedItemInfoIdentifier getRelatedContentIdentifier(); RelatedItemSearchType getRelatedItemSearchType(); void setRelatedItemSearchType(RelatedItemSearchType searchType); RelatedItemSearch copy(Configuration config); void setLookupKey(SearchRequestLookupKey key); SearchRequestLookupKey getLookupKey(); long getStartOfRequestNanos(); void setStartOfRequestNanos(long startOfRequestNanos); }
RelatedItemSearch { public RelatedItemSearch copy(Configuration config) { RelatedItemSearch newCopy = new RelatedItemSearch(config,this.getAdditionalSearchCriteria().getNumberOfProperties()); newCopy.setRelatedItemId(this.relatedItemId); newCopy.setMaxResults(this.maxResults); newCopy.setRelatedItemSearchType(this.searchType); newCopy.setLookupKey(this.getLookupKey()); newCopy.setStartOfRequestNanos(this.getStartOfRequestNanos()); this.additionalSearchCriteria.copyTo(newCopy.additionalSearchCriteria); return newCopy; } RelatedItemSearch(Configuration config); RelatedItemSearch(Configuration config,int numberOfAdditionalSearchCriteria); void setMaxResults(int maxResults); int getMaxResults(); RelatedItemAdditionalProperties getAdditionalSearchCriteria(); void setRelatedItemId(String id); String getRelatedItemId(); RelatedItemInfoIdentifier getRelatedContentIdentifier(); RelatedItemSearchType getRelatedItemSearchType(); void setRelatedItemSearchType(RelatedItemSearchType searchType); RelatedItemSearch copy(Configuration config); void setLookupKey(SearchRequestLookupKey key); SearchRequestLookupKey getLookupKey(); long getStartOfRequestNanos(); void setStartOfRequestNanos(long startOfRequestNanos); static final String RESULTS_SET_SIZE_KEY; static final String ID_KEY; static final int RESULTS_SET_SIZE_KEY_LENGTH; static final int ID_KEY_LENGTH; }
@Test public void testCreateSearchObject() throws Exception { assertNotNull(factory.createSearchObject()); }
@Override public RelatedItemSearch createSearchObject() { return new RelatedItemSearch(configuration); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch createSearchObject() { return new RelatedItemSearch(configuration); } }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch createSearchObject() { return new RelatedItemSearch(configuration); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch createSearchObject() { return new RelatedItemSearch(configuration); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedItemSearch createSearchObject(); @Override void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties); @Override RelatedItemSearch newInstance(); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch createSearchObject() { return new RelatedItemSearch(configuration); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedItemSearch createSearchObject(); @Override void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties); @Override RelatedItemSearch newInstance(); }
@Test public void testNewInstance() throws Exception { assertNotNull(factory.newInstance()); }
@Override public RelatedItemSearch newInstance() { return createSearchObject(); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch newInstance() { return createSearchObject(); } }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch newInstance() { return createSearchObject(); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch newInstance() { return createSearchObject(); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedItemSearch createSearchObject(); @Override void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties); @Override RelatedItemSearch newInstance(); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch newInstance() { return createSearchObject(); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedItemSearch createSearchObject(); @Override void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties); @Override RelatedItemSearch newInstance(); }
@Test public void testPopulateSearchObject() throws Exception { String[][] props = new String[4][2]; props[0] = new String[]{"channel","one"}; props[1] = new String[]{"type","computer"}; props[2] = new String[]{"attributed_to","user1"}; props[3] = new String[]{config.getRequestParameterForSize(),"3"}; Map properties = getProperties("1",props); RelatedItemSearch objectToPopulate = factory.createSearchObject(); assertEquals(0,objectToPopulate.getMaxResults()); assertEquals("",objectToPopulate.getRelatedItemId()); assertEquals(0,objectToPopulate.getAdditionalSearchCriteria().getNumberOfProperties()); factory.populateSearchObject(objectToPopulate, RelatedItemSearchType.FREQUENTLY_RELATED_WITH,properties); assertEquals(3,objectToPopulate.getMaxResults()); assertEquals("1",objectToPopulate.getRelatedItemId()); assertEquals(3,objectToPopulate.getAdditionalSearchCriteria().getNumberOfProperties()); assertEquals("attributed_to",objectToPopulate.getAdditionalSearchCriteria().getPropertyName(0)); assertEquals("user1",objectToPopulate.getAdditionalSearchCriteria().getPropertyValue(0)); assertEquals("channel",objectToPopulate.getAdditionalSearchCriteria().getPropertyName(1)); assertEquals("one",objectToPopulate.getAdditionalSearchCriteria().getPropertyValue(1)); assertEquals("type",objectToPopulate.getAdditionalSearchCriteria().getPropertyName(2)); assertEquals("computer",objectToPopulate.getAdditionalSearchCriteria().getPropertyValue(2)); }
@Override public void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties) { objectToPopulate.setStartOfRequestNanos(System.nanoTime()); String sizeKey = configuration.getRequestParameterForSize(); String idKey = configuration.getRequestParameterForId(); try { String size = properties.remove(sizeKey); if(size!=null) { objectToPopulate.setMaxResults(Integer.parseInt(size)); } else { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } } catch(NumberFormatException e) { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } objectToPopulate.setRelatedItemId(properties.remove(idKey)); RelatedItemAdditionalProperties props = objectToPopulate.getAdditionalSearchCriteria(); int maxPropertiesToCopy = Math.min(props.getMaxNumberOfAvailableProperties(),properties.size()); log.debug("max properties to copy {}, from properties {}",maxPropertiesToCopy,properties); int i=0; List<String> sortedParameters = new ArrayList<String>(properties.keySet()); Collections.sort(sortedParameters); for(String key : sortedParameters) { if(i==maxPropertiesToCopy) break; props.setProperty(key,properties.get(key),i++); } props.setNumberOfProperties(i); objectToPopulate.setRelatedItemSearchType(type); lookupKeyGenerator.setSearchRequestLookupKeyOn(objectToPopulate); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties) { objectToPopulate.setStartOfRequestNanos(System.nanoTime()); String sizeKey = configuration.getRequestParameterForSize(); String idKey = configuration.getRequestParameterForId(); try { String size = properties.remove(sizeKey); if(size!=null) { objectToPopulate.setMaxResults(Integer.parseInt(size)); } else { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } } catch(NumberFormatException e) { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } objectToPopulate.setRelatedItemId(properties.remove(idKey)); RelatedItemAdditionalProperties props = objectToPopulate.getAdditionalSearchCriteria(); int maxPropertiesToCopy = Math.min(props.getMaxNumberOfAvailableProperties(),properties.size()); log.debug("max properties to copy {}, from properties {}",maxPropertiesToCopy,properties); int i=0; List<String> sortedParameters = new ArrayList<String>(properties.keySet()); Collections.sort(sortedParameters); for(String key : sortedParameters) { if(i==maxPropertiesToCopy) break; props.setProperty(key,properties.get(key),i++); } props.setNumberOfProperties(i); objectToPopulate.setRelatedItemSearchType(type); lookupKeyGenerator.setSearchRequestLookupKeyOn(objectToPopulate); } }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties) { objectToPopulate.setStartOfRequestNanos(System.nanoTime()); String sizeKey = configuration.getRequestParameterForSize(); String idKey = configuration.getRequestParameterForId(); try { String size = properties.remove(sizeKey); if(size!=null) { objectToPopulate.setMaxResults(Integer.parseInt(size)); } else { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } } catch(NumberFormatException e) { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } objectToPopulate.setRelatedItemId(properties.remove(idKey)); RelatedItemAdditionalProperties props = objectToPopulate.getAdditionalSearchCriteria(); int maxPropertiesToCopy = Math.min(props.getMaxNumberOfAvailableProperties(),properties.size()); log.debug("max properties to copy {}, from properties {}",maxPropertiesToCopy,properties); int i=0; List<String> sortedParameters = new ArrayList<String>(properties.keySet()); Collections.sort(sortedParameters); for(String key : sortedParameters) { if(i==maxPropertiesToCopy) break; props.setProperty(key,properties.get(key),i++); } props.setNumberOfProperties(i); objectToPopulate.setRelatedItemSearchType(type); lookupKeyGenerator.setSearchRequestLookupKeyOn(objectToPopulate); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties) { objectToPopulate.setStartOfRequestNanos(System.nanoTime()); String sizeKey = configuration.getRequestParameterForSize(); String idKey = configuration.getRequestParameterForId(); try { String size = properties.remove(sizeKey); if(size!=null) { objectToPopulate.setMaxResults(Integer.parseInt(size)); } else { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } } catch(NumberFormatException e) { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } objectToPopulate.setRelatedItemId(properties.remove(idKey)); RelatedItemAdditionalProperties props = objectToPopulate.getAdditionalSearchCriteria(); int maxPropertiesToCopy = Math.min(props.getMaxNumberOfAvailableProperties(),properties.size()); log.debug("max properties to copy {}, from properties {}",maxPropertiesToCopy,properties); int i=0; List<String> sortedParameters = new ArrayList<String>(properties.keySet()); Collections.sort(sortedParameters); for(String key : sortedParameters) { if(i==maxPropertiesToCopy) break; props.setProperty(key,properties.get(key),i++); } props.setNumberOfProperties(i); objectToPopulate.setRelatedItemSearchType(type); lookupKeyGenerator.setSearchRequestLookupKeyOn(objectToPopulate); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedItemSearch createSearchObject(); @Override void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties); @Override RelatedItemSearch newInstance(); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties) { objectToPopulate.setStartOfRequestNanos(System.nanoTime()); String sizeKey = configuration.getRequestParameterForSize(); String idKey = configuration.getRequestParameterForId(); try { String size = properties.remove(sizeKey); if(size!=null) { objectToPopulate.setMaxResults(Integer.parseInt(size)); } else { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } } catch(NumberFormatException e) { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } objectToPopulate.setRelatedItemId(properties.remove(idKey)); RelatedItemAdditionalProperties props = objectToPopulate.getAdditionalSearchCriteria(); int maxPropertiesToCopy = Math.min(props.getMaxNumberOfAvailableProperties(),properties.size()); log.debug("max properties to copy {}, from properties {}",maxPropertiesToCopy,properties); int i=0; List<String> sortedParameters = new ArrayList<String>(properties.keySet()); Collections.sort(sortedParameters); for(String key : sortedParameters) { if(i==maxPropertiesToCopy) break; props.setProperty(key,properties.get(key),i++); } props.setNumberOfProperties(i); objectToPopulate.setRelatedItemSearchType(type); lookupKeyGenerator.setSearchRequestLookupKeyOn(objectToPopulate); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedItemSearch createSearchObject(); @Override void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties); @Override RelatedItemSearch newInstance(); }
@Test public void testConvertFromSingleItemIndexingMessage() throws Exception { RelatedItemIndexingMessageConverter converter = getConverter(); RelatedItemIndexingMessage message = getIndexingMessageWithOneRelatedItem(); RelatedItem[] products = converter.convertFrom(message); assertEquals("Should only have found a single product",1,products.length); RelatedItem product = products[0]; assertEquals(DATE, product.getDate()); assertEquals("1",new String(product.getId())); assertEquals("the related product should have 3 properties, two inherited, one for itself",3,product.getAdditionalProperties().getNumberOfProperties()); Map<String,String> props = new HashMap<String,String>(); product.getAdditionalProperties().convertTo(props); assertEquals(SITE, props.get("site")); assertEquals(CHANNEL,props.get("channel")); assertEquals(DEPARTMENT,props.get("department")); }
public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); RelatedItem[] convertFrom(RelatedItemIndexingMessage message); static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length); }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); RelatedItem[] convertFrom(RelatedItemIndexingMessage message); static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length); }
@Test public void testConvertFromTwoItemsIndexingMessage() throws Exception { RelatedItemIndexingMessageConverter converter = getConverter(); RelatedItemIndexingMessage message = getIndexingMessageWithTwoRelatedItem(); RelatedItem[] products = converter.convertFrom(message); Arrays.sort(products, new RelatedItemComparator()); assertEquals("Should only have found a single product",2,products.length); RelatedItem product1 = products[0]; RelatedItem product2 = products[1]; assertEquals(DATE, product1.getDate()); assertEquals("1",new String(product1.getId())); assertEquals("the related product should have 3 properties, two inherited, one for itself",5,product1.getAdditionalProperties().getNumberOfProperties()); assertEquals(DATE, product2.getDate()); assertEquals("2",new String(product2.getId())); assertEquals("the related product should have 3 properties, two inherited, one for itself",5,product2.getAdditionalProperties().getNumberOfProperties()); Map<String,String> props = new HashMap<String,String>(); product1.getAdditionalProperties().convertTo(props); assertEquals(SITE,props.get("site")); assertEquals(CHANNEL,props.get("channel")); assertEquals(DEPARTMENT,props.get("department")); assertEquals("laptops",props.get("subcategory")); assertEquals("apple mac",props.get("name")); }
public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); RelatedItem[] convertFrom(RelatedItemIndexingMessage message); static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length); }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); RelatedItem[] convertFrom(RelatedItemIndexingMessage message); static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length); }
@Test public void testHttpParseFoundTwoSourcesOneWithAnError() { System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_HTTP_HOSTS, "http: Configuration configuration = new SystemPropertiesConfiguration(); HttpElasticSearchClientFactory factory = new AHCHttpElasticSearchClientFactory(configuration); repository = new ElasticSearchRelatedItemHttpGetRepository(configuration,factory); Map<String,String> map = repository.getRelatedItemDocument(new String[]{"1","2"}); assertEquals("Should have parsed to items",3,map.size()); assertTrue("Document id 1 contains correct hash values",map.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); assertTrue("Document id 2 contains correct hash values",map.get("2").contains("{}")); }
@Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void testRelatedItemIds() { RelatedItemInfo info1 = createRelatedItemInfoObj("1"); RelatedItemInfo info2 = createRelatedItemInfoObj("2"); RelatedItemInfo info3 = createRelatedItemInfoObj("3"); RelatedItemInfo info4 = createRelatedItemInfoObj("4"); RelatedItemInfo info5 = createRelatedItemInfoObj("5"); RelatedItemInfo[][] relatedItemIds = BasicRelatedItemIndexingMessageConverter.relatedIds(new RelatedItemInfo[]{info1, info2, info3, info4, info5}, 5); String[] concatIds = new String[relatedItemIds.length]; for(int i = 0;i<relatedItemIds.length;i++) { StringBuilder b = new StringBuilder(5); for(int j=0;j<relatedItemIds[i].length;j++) { b.append(relatedItemIds[i][j].getId().toString()); } concatIds[i] = b.toString(); } System.out.println(Arrays.toString(concatIds)); assertSame(info5, relatedItemIds[0][4]); assertSame(info1, relatedItemIds[1][4]); assertSame(info2, relatedItemIds[2][4]); assertSame(info3, relatedItemIds[3][4]); assertSame(info4, relatedItemIds[4][4]); assertEquals("12345",concatIds[0]); assertEquals("23451",concatIds[1]); assertEquals("34512",concatIds[2]); assertEquals("45123",concatIds[3]); assertEquals("51234",concatIds[4]); }
public static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length) { int len = length; RelatedItemInfo[][] idSets = new RelatedItemInfo[len][len]; for(int j = 0;j<len;j++) { idSets[0][j] = ids[j]; } for(int i=1;i<len;i++) { int k=0; for(int j=i;j<len;j++) { idSets[i][k++] = ids[j]; } for(int j=0;j<i;j++) { idSets[i][k++] = ids[j]; } } return idSets; }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length) { int len = length; RelatedItemInfo[][] idSets = new RelatedItemInfo[len][len]; for(int j = 0;j<len;j++) { idSets[0][j] = ids[j]; } for(int i=1;i<len;i++) { int k=0; for(int j=i;j<len;j++) { idSets[i][k++] = ids[j]; } for(int j=0;j<i;j++) { idSets[i][k++] = ids[j]; } } return idSets; } }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length) { int len = length; RelatedItemInfo[][] idSets = new RelatedItemInfo[len][len]; for(int j = 0;j<len;j++) { idSets[0][j] = ids[j]; } for(int i=1;i<len;i++) { int k=0; for(int j=i;j<len;j++) { idSets[i][k++] = ids[j]; } for(int j=0;j<i;j++) { idSets[i][k++] = ids[j]; } } return idSets; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length) { int len = length; RelatedItemInfo[][] idSets = new RelatedItemInfo[len][len]; for(int j = 0;j<len;j++) { idSets[0][j] = ids[j]; } for(int i=1;i<len;i++) { int k=0; for(int j=i;j<len;j++) { idSets[i][k++] = ids[j]; } for(int j=0;j<i;j++) { idSets[i][k++] = ids[j]; } } return idSets; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); RelatedItem[] convertFrom(RelatedItemIndexingMessage message); static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length); }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length) { int len = length; RelatedItemInfo[][] idSets = new RelatedItemInfo[len][len]; for(int j = 0;j<len;j++) { idSets[0][j] = ids[j]; } for(int i=1;i<len;i++) { int k=0; for(int j=i;j<len;j++) { idSets[i][k++] = ids[j]; } for(int j=0;j<i;j++) { idSets[i][k++] = ids[j]; } } return idSets; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); RelatedItem[] convertFrom(RelatedItemIndexingMessage message); static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length); }
@Test public void testConvertFromThreeProductsIndexingMessage() throws Exception { RelatedItemIndexingMessageConverter converter = getConverter(); RelatedItemIndexingMessage message = getIndexingMessageWithThreeRelatedItem(); RelatedItem[] products = converter.convertFrom(message); Arrays.sort(products, new RelatedItemComparator()); assertEquals("Should only have found a single product", 3, products.length); RelatedItem product1 = products[0]; RelatedItem product2 = products[1]; RelatedItem product3 = products[2]; assertEquals(DATE, product1.getDate()); assertEquals("1",new String(product1.getId())); assertEquals("the related product should have 5 properties, two inherited, one for itself",5,product1.getAdditionalProperties().getNumberOfProperties()); assertEquals(DATE, product2.getDate()); assertEquals("2",new String(product2.getId())); assertEquals("the related product should have 5 properties, two inherited, one for itself",5,product2.getAdditionalProperties().getNumberOfProperties()); assertEquals(DATE, product3.getDate()); assertEquals("3",new String(product3.getId())); assertEquals("the related product should have 5 properties, two inherited, one for itself",5,product3.getAdditionalProperties().getNumberOfProperties()); Map<String,String> props = new HashMap<String,String>(); product1.getAdditionalProperties().convertTo(props); assertEquals(SITE,props.get("site")); assertEquals(CHANNEL,props.get("channel")); assertEquals(DEPARTMENT,props.get("department")); assertEquals("laptops",props.get("subcategory")); assertEquals("apple mac",props.get("name")); assertEquals(2, product1.getRelatedItemPids().length); String id1 = new String(product1.getRelatedItemPids()[0]); String id2 = new String(product1.getRelatedItemPids()[1]); if(id1.equals("2")) { assertEquals("3",id2); } else if(id1.equals("3")) { assertEquals("2",id2); } else { fail("related ids for product2 are incorrect"); } props = new HashMap<String,String>(); product2.getAdditionalProperties().convertTo(props); assertEquals(SITE,props.get("site")); assertEquals(CHANNEL,props.get("channel")); assertEquals(DEPARTMENT,props.get("department")); assertEquals(SUBCATEGORY,props.get("subcategory")); assertEquals("apple care insurance",props.get("name")); assertEquals(2, product2.getRelatedItemPids().length); id1 = new String(product2.getRelatedItemPids()[0]); id2 = new String(product2.getRelatedItemPids()[1]); if(id1.equals("1")) { assertEquals("3",id2); } else if(id1.equals("3")) { assertEquals("1",id2); } else { fail("related ids for product2 are incorrect"); } props = new HashMap<String,String>(); product3.getAdditionalProperties().convertTo(props); assertEquals(SITE,props.get("site")); assertEquals(CHANNEL,props.get("channel")); assertEquals(DEPARTMENT,props.get("department")); assertEquals(SUBCATEGORY,props.get("subcategory")); assertEquals("microsoft word",props.get("name")); assertEquals(2, product3.getRelatedItemPids().length); id1 = new String(product3.getRelatedItemPids()[0]); id2 = new String(product3.getRelatedItemPids()[1]); if(id1.equals("2")) { assertEquals("1",id2); } else if(id1.equals("1")) { assertEquals("2",id2); } else { fail("related ids for product2 are incorrect"); } }
public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); RelatedItem[] convertFrom(RelatedItemIndexingMessage message); static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length); }
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numberOfRelatedItems]; RelatedItemInfo[][] idLists = relatedIds(items.getListOfRelatedItemInfomation(), items.getNumberOfRelatedItems()); int length = numberOfRelatedItems-1; for(int i =0;i<numberOfRelatedItems;i++) { RelatedItemInfo id = idLists[i][length]; relatedItems[i] = createRelatedItem(message, id, idLists[i], message.getIndexingMessageProperties()); } return relatedItems; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); RelatedItem[] convertFrom(RelatedItemIndexingMessage message); static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length); }
@Test public void testRelatedItemIndexingMessageWith4RelatedItems() throws Exception { System.setProperty(PROPNAME_MAX_NO_OF_RELATED_ITEMS_PER_INDEX_REQUEST,"4"); Configuration config = new SystemPropertiesConfiguration(); RelatedItemIndexingMessageFactory factory = new RelatedItemIndexingMessageFactory(config); RelatedItemIndexingMessage message = factory.newInstance(); assertEquals(4, message.getMaxNumberOfRelatedItemsAllowed()); }
@Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); @Override RelatedItemIndexingMessage newInstance(); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); @Override RelatedItemIndexingMessage newInstance(); }
@Test public void testRelatedItemIndexingMessage() { System.setProperty(PROPNAME_MAX_NO_OF_RELATED_ITEMS_PER_INDEX_REQUEST,"2"); Configuration config = new SystemPropertiesConfiguration(); RelatedItemIndexingMessageFactory factory = new RelatedItemIndexingMessageFactory(config); RelatedItemIndexingMessage message = factory.newInstance(); assertEquals(2, message.getMaxNumberOfRelatedItemsAllowed()); }
@Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); @Override RelatedItemIndexingMessage newInstance(); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); @Override RelatedItemIndexingMessage newInstance(); }
@Test public void testRelatedItemIndexingMessageRestrictsNumberOfProperties() { System.setProperty(PROPNAME_MAX_NO_OF_RELATED_ITEMS_PER_INDEX_REQUEST,"2"); System.setProperty(PROPNAME_MAX_NO_OF_RELATED_ITEM_PROPERTES,"3"); Configuration config = new SystemPropertiesConfiguration(); RelatedItemIndexingMessageFactory factory = new RelatedItemIndexingMessageFactory(config); RelatedItemIndexingMessage message = factory.newInstance(); assertEquals(2, message.getMaxNumberOfRelatedItemsAllowed()); assertEquals(3, message.getIndexingMessageProperties().getMaxNumberOfAvailableProperties()); }
@Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); @Override RelatedItemIndexingMessage newInstance(); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); @Override RelatedItemIndexingMessage newInstance(); }
@Test public void testCanCreateReferenceObject() { EventFactory<RelatedItemReference> factory = new RelatedItemReferenceMessageFactory(); assertNotNull(factory.newInstance()); assertTrue(factory.newInstance() instanceof RelatedItemReference); }
@Override public RelatedItemReference newInstance() { return new RelatedItemReference(); }
RelatedItemReferenceMessageFactory implements EventFactory<RelatedItemReference> { @Override public RelatedItemReference newInstance() { return new RelatedItemReference(); } }
RelatedItemReferenceMessageFactory implements EventFactory<RelatedItemReference> { @Override public RelatedItemReference newInstance() { return new RelatedItemReference(); } RelatedItemReferenceMessageFactory(); }
RelatedItemReferenceMessageFactory implements EventFactory<RelatedItemReference> { @Override public RelatedItemReference newInstance() { return new RelatedItemReference(); } RelatedItemReferenceMessageFactory(); @Override RelatedItemReference newInstance(); }
RelatedItemReferenceMessageFactory implements EventFactory<RelatedItemReference> { @Override public RelatedItemReference newInstance() { return new RelatedItemReference(); } RelatedItemReferenceMessageFactory(); @Override RelatedItemReference newInstance(); }
@Test public void testRequestTimeoutIsCaught() { stubFor(get(urlEqualTo("/my/resource")) .willReturn(aResponse().withFixedDelay(3000) .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody("<response>Some content</response>"))); HttpResult httpResult = AHCRequestExecutor.executeSearch(client, HttpMethod.GET,"http: assertTrue(httpResult.getStatus()== HttpSearchExecutionStatus.REQUEST_TIMEOUT); }
public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery); }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery); }
@Test public void testResponseBodyIsReturned() { String response = "<response>Some content</response>"; stubFor(get(urlEqualTo("/my/resource")) .willReturn(aResponse().withFixedDelay(1000) .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(response))); HttpResult httpResult = AHCRequestExecutor.executeSearch(client, HttpMethod.GET,"http: assertTrue(httpResult.getStatus()== HttpSearchExecutionStatus.OK); assertEquals(response,httpResult.getResult()); }
public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery); }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery); }
@Test public void testMultiSearch() { AsyncHttpClient client = new AsyncHttpClient(); String s = "{\n" + " \"size\" : 0,\n" + " \"timeout\" : 5000,\n" + " \"query\" : {\n" + " \"constant_score\" : {\n" + " \"filter\" : {\n" + " \"bool\" : {\n" + " \"must\" : {\n" + " \"term\" : {\n" + " \"related-with\" : \"9da7320e-acd7-4f49-9b3f-4818f4afc67b\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + " },\n" + " \"facets\" : {\n" + " \"frequently-related-with\" : {\n" + " \"terms\" : {\n" + " \"field\" : \"id\",\n" + " \"size\" : 10,\n" + " \"execution_hint\" : \"map\"\n" + " }\n" + " }\n" + " }\n" + "}\n"; HttpResult httpResult = AHCRequestExecutor.executeSearch(client, HttpMethod.GET,"http: System.out.println(httpResult.getResult()); try { SearchResponse r = SearchResponse.readSearchResponse(new ByteBufferStreamInput(ByteBuffer.wrap(httpResult.getResult().getBytes()))); System.out.println(r); } catch (IOException e) { e.printStackTrace(); } }
public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery); }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery); }
@Test public void testConnectionException() { HttpResult httpResult = AHCRequestExecutor.executeSearch(client, HttpMethod.GET,"http: assertTrue(httpResult.getStatus()== HttpSearchExecutionStatus.CONNECTION_FAILURE); }
public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery); }
AHCRequestExecutor { public static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery) { RequestBuilder requestBuilder = new RequestBuilder(method.name()); log.debug("Executing request against host {} with path {}",host,path); if(searchQuery!=null) { requestBuilder.setBody(searchQuery); } requestBuilder.setUrl(host + path); try { Response res = client.executeRequest(requestBuilder.build(),new AsyncCompletionHandlerBase()).get(); return new HttpResult(HttpSearchExecutionStatus.OK,res.getResponseBody()); } catch (Exception e) { Throwable cause = e.getCause(); if(cause!=null) { if(cause instanceof ConnectException) { log.error("Unable to connect to {}",host,e); return HttpResult.CONNECTION_FAILURE; } else if (cause instanceof TimeoutException) { log.error("Request timeout talking to {}",host,e); return HttpResult.REQUEST_TIMEOUT_FAILURE; } else if (cause instanceof IOException && cause.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } else { if (e instanceof IOException && e.getMessage().equalsIgnoreCase("closed")) { log.warn("Unable to use client, client is closed"); return HttpResult.CLIENT_CLOSED; } else { log.error("Exception talking to {}",host,e); return new HttpResult(HttpSearchExecutionStatus.REQUEST_FAILURE,null); } } } } static HttpResult executeSearch(AsyncHttpClient client, HttpMethod method, String host, String path, String searchQuery); }
@Test public void parseFoundTwoAndOneNotFound() { Map<String,String> parsedDoc = ElasticSearchRelatedItemHttpGetRepository.processResults(FOUND_TWO_ONE_NOT_FOUND); assertTrue(parsedDoc.size()==2); assertTrue(parsedDoc.containsKey("1")); assertTrue(parsedDoc.containsKey("2")); assertTrue(parsedDoc.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); assertTrue(parsedDoc.get("2").contains("71a5120bdf4d998c2b043a681b1bd211")); }
public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void testOneHostIsContacted() { Set<String> hosts = nodeSniffer.getAvailableNodes(new String[]{"http: assertEquals("Should be one host",1,hosts.size()); assertEquals("parsed host should be: http: wireMockRule1.verify(1,getRequestedFor(urlMatching(ConfigurationConstants.DEFAULT_ELASTIC_SEARCH_HTTP_NODE_SNIFFING_ENDPOINT))); wireMockRule2.verify(0,getRequestedFor(urlMatching(ConfigurationConstants.DEFAULT_ELASTIC_SEARCH_HTTP_NODE_SNIFFING_ENDPOINT))); }
@Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; }
AHCHttpSniffAvailableNodes implements SniffAvailableNodes { @Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; } }
AHCHttpSniffAvailableNodes implements SniffAvailableNodes { @Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; } AHCHttpSniffAvailableNodes(Configuration configuration); }
AHCHttpSniffAvailableNodes implements SniffAvailableNodes { @Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; } AHCHttpSniffAvailableNodes(Configuration configuration); @Override Set<String> getAvailableNodes(String[] hosts); @Override void shutdown(); }
AHCHttpSniffAvailableNodes implements SniffAvailableNodes { @Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; } AHCHttpSniffAvailableNodes(Configuration configuration); @Override Set<String> getAvailableNodes(String[] hosts); @Override void shutdown(); final String NODE_ENDPOINT; }
@Test public void testBothHostIsContacted() { Set<String> hosts = nodeSniffer.getAvailableNodes(new String[]{"http: assertEquals("Should be one host",3,hosts.size()); assertEquals("parsed host should be: http: assertEquals("parsed host should be: http: assertEquals("parsed host should be: http: wireMockRule1.verify(1,getRequestedFor(urlMatching(ConfigurationConstants.DEFAULT_ELASTIC_SEARCH_HTTP_NODE_SNIFFING_ENDPOINT))); wireMockRule2.verify(1,getRequestedFor(urlMatching(ConfigurationConstants.DEFAULT_ELASTIC_SEARCH_HTTP_NODE_SNIFFING_ENDPOINT))); }
@Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; }
AHCHttpSniffAvailableNodes implements SniffAvailableNodes { @Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; } }
AHCHttpSniffAvailableNodes implements SniffAvailableNodes { @Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; } AHCHttpSniffAvailableNodes(Configuration configuration); }
AHCHttpSniffAvailableNodes implements SniffAvailableNodes { @Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; } AHCHttpSniffAvailableNodes(Configuration configuration); @Override Set<String> getAvailableNodes(String[] hosts); @Override void shutdown(); }
AHCHttpSniffAvailableNodes implements SniffAvailableNodes { @Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; } AHCHttpSniffAvailableNodes(Configuration configuration); @Override Set<String> getAvailableNodes(String[] hosts); @Override void shutdown(); final String NODE_ENDPOINT; }
@Test public void testHttpParseFoundThreeSourcesOneWithAnError() { System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_HTTP_HOSTS, "http: Configuration configuration = new SystemPropertiesConfiguration(); HttpElasticSearchClientFactory factory = new AHCHttpElasticSearchClientFactory(configuration); repository = new ElasticSearchRelatedItemHttpGetRepository(configuration,factory); Map<String,String> map = repository.getRelatedItemDocument(new String[]{"1","2","3"}); assertEquals("Should have parsed to items", 4, map.size()); assertTrue("Document id 1 contains correct hash values",map.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); assertTrue("Document id 2 contains correct hash values", map.get("2").contains("71a5120bdf4d998c2b043a681b1bd211")); assertEquals("Document id 3 contains no source","{}",map.get("3")); }
@Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void testHttpParseWithNoDocsReturned() { System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_HTTP_HOSTS, "http: Configuration configuration = new SystemPropertiesConfiguration(); HttpElasticSearchClientFactory factory = new AHCHttpElasticSearchClientFactory(configuration); repository = new ElasticSearchRelatedItemHttpGetRepository(configuration,factory); Map<String,String> map = repository.getRelatedItemDocument(new String[]{"5","6"}); assertEquals("Should have parsed to items",3,map.size()); assertEquals("Document id 5 contains no source", "{}", map.get("5")); assertEquals("Document id 6 contains no source","{}",map.get("6")); }
@Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void testHttpParseWithNoDocsReturnedOnA404() { System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_HTTP_HOSTS, "http: Configuration configuration = new SystemPropertiesConfiguration(); HttpElasticSearchClientFactory factory = new AHCHttpElasticSearchClientFactory(configuration); repository = new ElasticSearchRelatedItemHttpGetRepository(configuration,factory); Map<String,String> map = repository.getRelatedItemDocument(new String[]{"9","10"}); assertEquals("Should have parsed to items",3,map.size()); assertEquals("Document id 9 contains no source","{}",map.get("9")); assertEquals("Document id 10 contains no source","{}",map.get("10")); }
@Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void testHttpParseWith500Error() { System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_HTTP_HOSTS, "http: Configuration configuration = new SystemPropertiesConfiguration(); HttpElasticSearchClientFactory factory = new AHCHttpElasticSearchClientFactory(configuration); repository = new ElasticSearchRelatedItemHttpGetRepository(configuration,factory); Map<String,String> map = repository.getRelatedItemDocument(new String[]{"11","12"}); assertEquals("Should have parsed to items",3,map.size()); assertEquals("Document id 11 contains no source","{}",map.get("11")); assertEquals("Document id 12 contains no source","{}",map.get("12")); }
@Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void testHttpParseWithError() { System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_HTTP_HOSTS, "http: Configuration configuration = new SystemPropertiesConfiguration(); HttpElasticSearchClientFactory factory = new AHCHttpElasticSearchClientFactory(configuration); repository = new ElasticSearchRelatedItemHttpGetRepository(configuration,factory); Map<String,String> map = repository.getRelatedItemDocument(new String[]{"14","15"}); assertEquals("Should have parsed to items",3,map.size()); assertEquals("Document id 14 contains no source","{}",map.get("14")); assertEquals("Document id 15 contains no source","{}",map.get("15")); }
@Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void testHttpParseWithTimeout() { System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_HTTP_HOSTS, "http: Configuration configuration = new SystemPropertiesConfiguration(); HttpElasticSearchClientFactory factory = new AHCHttpElasticSearchClientFactory(configuration); repository = new ElasticSearchRelatedItemHttpGetRepository(configuration,factory); Map<String,String> map = repository.getRelatedItemDocument(new String[]{"22","23"}); assertEquals("Should have parsed to items",3,map.size()); assertEquals("Document id 22 contains no source","{}",map.get("22")); assertEquals("Document id 23 contains no source","{}",map.get("23")); }
@Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void testEmptyResultsAreReturnedWhenNoIndexExists() { repository = searchRepositoryFactory.createRelatedItemSearchRepository(configuration,builder); SearchResultEventWithSearchRequestKey[] results = repository.findRelatedItems(configuration, createSearch()); assertEquals(2,results.length); System.out.println("testFailedResultsAreReturnedWhenNoIndexExists, Results 0 outcometype: " + results[0].getResponse().getOutcomeType()); System.out.println("testFailedResultsAreReturnedWhenNoIndexExists, Results 1 outcometype: " + results[1].getResponse().getOutcomeType()); assertSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); }
@Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemHttpSearchRepository(Configuration configuration, HttpElasticSearchClientFactory factory, ElasticSearchFrequentlyRelatedItemHttpSearchProcessor builder); }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemHttpSearchRepository(Configuration configuration, HttpElasticSearchClientFactory factory, ElasticSearchFrequentlyRelatedItemHttpSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemHttpSearchRepository(Configuration configuration, HttpElasticSearchClientFactory factory, ElasticSearchFrequentlyRelatedItemHttpSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
@Test public void testEmptyResultsAreReturnedWhenIndexIsEmpty() { server.createIndex(configuration.getStorageIndexNamePrefix()); repository = searchRepositoryFactory.createRelatedItemSearchRepository(configuration,builder); SearchResultEventWithSearchRequestKey[] results = repository.findRelatedItems(configuration, createSearch()); assertEquals(2,results.length); System.out.println("testFailedResultsAreReturnedWhenIndexIsEmpty, Results 0 outcometype: " + results[0].getResponse().getOutcomeType()); System.out.println("testFailedResultsAreReturnedWhenIndexIsEmpty, Results 1 outcometype: " + results[1].getResponse().getOutcomeType()); assertSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); }
@Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemHttpSearchRepository(Configuration configuration, HttpElasticSearchClientFactory factory, ElasticSearchFrequentlyRelatedItemHttpSearchProcessor builder); }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemHttpSearchRepository(Configuration configuration, HttpElasticSearchClientFactory factory, ElasticSearchFrequentlyRelatedItemHttpSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemHttpSearchRepository(Configuration configuration, HttpElasticSearchClientFactory factory, ElasticSearchFrequentlyRelatedItemHttpSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
@Test public void testIdParameterReturnsValidMessage() { ValidationMessage message = validator.validateParameters(new HashMap<String, String>(){{ put(configuration.getKeyForFrequencyResultId(),"11111");}}); assertSame(message,validator.VALID_ID_MESSAGE); }
@Override public ValidationMessage validateParameters(Map<String, String> requestParameters) { String id = requestParameters.get(idParameter); if(id == null || id.length()==0) return INVALID_ID_MESSAGE; else return VALID_ID_MESSAGE; }
FrequentlyRelatedContentRequestParameterValidator implements SearchRequestParameterValidator { @Override public ValidationMessage validateParameters(Map<String, String> requestParameters) { String id = requestParameters.get(idParameter); if(id == null || id.length()==0) return INVALID_ID_MESSAGE; else return VALID_ID_MESSAGE; } }
FrequentlyRelatedContentRequestParameterValidator implements SearchRequestParameterValidator { @Override public ValidationMessage validateParameters(Map<String, String> requestParameters) { String id = requestParameters.get(idParameter); if(id == null || id.length()==0) return INVALID_ID_MESSAGE; else return VALID_ID_MESSAGE; } FrequentlyRelatedContentRequestParameterValidator(Configuration configuration); }
FrequentlyRelatedContentRequestParameterValidator implements SearchRequestParameterValidator { @Override public ValidationMessage validateParameters(Map<String, String> requestParameters) { String id = requestParameters.get(idParameter); if(id == null || id.length()==0) return INVALID_ID_MESSAGE; else return VALID_ID_MESSAGE; } FrequentlyRelatedContentRequestParameterValidator(Configuration configuration); @Override ValidationMessage validateParameters(Map<String, String> requestParameters); }
FrequentlyRelatedContentRequestParameterValidator implements SearchRequestParameterValidator { @Override public ValidationMessage validateParameters(Map<String, String> requestParameters) { String id = requestParameters.get(idParameter); if(id == null || id.length()==0) return INVALID_ID_MESSAGE; else return VALID_ID_MESSAGE; } FrequentlyRelatedContentRequestParameterValidator(Configuration configuration); @Override ValidationMessage validateParameters(Map<String, String> requestParameters); final ValidationMessage VALID_ID_MESSAGE; final ValidationMessage INVALID_ID_MESSAGE; }
@Test public void testFindRelatedItems() throws Exception { try { server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-14",RELATED_CONTENT_BLADES1_PURCHASEa); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-14",RELATED_CONTENT_BLADES1_PURCHASEb); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-15",RELATED_CONTENT_BLADES2_PURCHASEa); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-15",RELATED_CONTENT_BLADES2_PURCHASEb); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-15",RELATED_CONTENT_BLADES2_PURCHASEc); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-24",RELATED_CONTENT_THERAID_PURCHASEa); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-24",RELATED_CONTENT_THERAID_PURCHASEb); assertEquals(3,server.getIndexCount()); assertEquals(2,server.getDocCount(configuration.getStorageIndexNamePrefix()+"-2013-12-14")); assertEquals(3,server.getDocCount(configuration.getStorageIndexNamePrefix()+"-2013-12-15")); assertEquals(2,server.getDocCount(configuration.getStorageIndexNamePrefix()+"-2013-12-24")); } catch(Exception e) { fail("Cannot create test date for search test"); } repository = searchRepositoryFactory.createRelatedItemSearchRepository(configuration,builder); RelatedItemSearch[] searches = createSearch(); SearchResultEventWithSearchRequestKey<FrequentlyRelatedSearchResult[]>[] results = repository.findRelatedItems(configuration, searches); assertEquals(2,results.length); assertNotSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); assertEquals(1, results[0].getResponse().getSearchResults().length); assertEquals("blades of glory",results[0].getResponse().getSearchResults()[0].getRelatedItemId()); assertEquals("enter the dragon",results[1].getResponse().getSearchResults()[0].getRelatedItemId()); }
@Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemHttpSearchRepository(Configuration configuration, HttpElasticSearchClientFactory factory, ElasticSearchFrequentlyRelatedItemHttpSearchProcessor builder); }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemHttpSearchRepository(Configuration configuration, HttpElasticSearchClientFactory factory, ElasticSearchFrequentlyRelatedItemHttpSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = frequentlyRelatedWithSearchBuilder.executeSearch(searches, elasticClient); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("Processing results for search {} request(s)", searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches, sr); log.debug("Search Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { long time = (System.nanoTime() - startNanos) / 1000000; log.warn("Exception executing search request"); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } else { long time = (System.nanoTime() - startNanos) / 1000000; if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for (int i = 0; i < size; i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, key, time, searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemHttpSearchRepository(Configuration configuration, HttpElasticSearchClientFactory factory, ElasticSearchFrequentlyRelatedItemHttpSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
@Test public void testTransportBasedClientCanConnectToES() { esServer = new ElasticSearchServer(clusterName,true); assertTrue("Unable to start in memory elastic search", esServer.isSetup()); System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_TRANSPORT_HOSTS, "localhost:" + esServer.getPort()); System.setProperty(ConfigurationConstants.PROPNAME_ES_CLIENT_TYPE, "transport"); Configuration config = new SystemPropertiesConfiguration(); try { ElasticSearchClientFactory factory = clientFactoryCreator.getElasticSearchClientConnectionFactory(config); Client c = factory.getClient(); assertEquals(config.getStorageClusterName(), c.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getClusterName().value()); assertNotNull(c.index(new IndexRequest("test", "test").source("name", "a")).actionGet().getId()); c.admin().indices().refresh(new RefreshRequest("test").force(true)).actionGet(); assertEquals(1,c.admin().indices().stats(new IndicesStatsRequest().indices("test")).actionGet().getTotal().docs.getCount()); } catch(Exception e) { fail("Unable to connect to elasticsearch: " + e.getMessage()); } try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }
@Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; }
NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; } }
NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; } }
NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; } @Override ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration); }
NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; } @Override ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration); static final ElasticSearchClientFactoryCreator INSTANCE; }
@Test public void testNodeBasedClientCanConnectToES() { System.setProperty(ConfigurationConstants.PROPNAME_ES_CLIENT_TYPE, "node"); Configuration config = new SystemPropertiesConfiguration(); esServer = new ElasticSearchServer(clusterName,false); assertTrue("Unable to start in memory elastic search", esServer.isSetup()); try { ElasticSearchClientFactory factory = clientFactoryCreator.getElasticSearchClientConnectionFactory(config); Client c = factory.getClient(); assertEquals(config.getStorageClusterName(), c.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getClusterName().value()); assertNotNull(c.index(new IndexRequest("test", "test").source("name", "a")).actionGet().getId()); c.admin().indices().refresh(new RefreshRequest("test").force(true)).actionGet(); assertEquals(1, c.admin().indices().stats(new IndicesStatsRequest().indices("test")).actionGet().getTotal().docs.getCount()); } catch(Exception e) { e.printStackTrace(); fail("Unable to connect to elasticsearch: " + e.getMessage()); } }
@Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; }
NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; } }
NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; } }
NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; } @Override ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration); }
NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; } @Override ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration); static final ElasticSearchClientFactoryCreator INSTANCE; }
@Test public void testFailedResultsAreReturnedWhenNoIndexExists() { SearchResultEventWithSearchRequestKey[] results = repository.findRelatedItems(configuration, createSearch()); assertEquals(2,results.length); System.out.println("testFailedResultsAreReturnedWhenNoIndexExists, Results 0 outcometype: " + results[0].getResponse().getOutcomeType()); System.out.println("testFailedResultsAreReturnedWhenNoIndexExists, Results 1 outcometype: " + results[1].getResponse().getOutcomeType()); assertSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); }
@Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
@Test public void testFailedResultsAreReturnedWhenIndexIsEmpty() { server.createIndex(configuration.getStorageIndexNamePrefix()); SearchResultEventWithSearchRequestKey[] results = repository.findRelatedItems(configuration, createSearch()); assertEquals(2,results.length); System.out.println("testFailedResultsAreReturnedWhenIndexIsEmpty, Results 0 outcometype: " + results[0].getResponse().getOutcomeType()); System.out.println("testFailedResultsAreReturnedWhenIndexIsEmpty, Results 1 outcometype: " + results[1].getResponse().getOutcomeType()); assertSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); }
@Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
@Test public void testTimeoutResultsAreReturned() { server.createIndex(configuration.getStorageIndexNamePrefix()); System.setProperty(ConfigurationConstants.PROPNAME_FREQUENTLY_RELATED_SEARCH_TIMEOUT_IN_MILLIS, "0"); try { Configuration config = new SystemPropertiesConfiguration(); ElasticSearchRelatedItemSearchRepository repository = new ElasticSearchRelatedItemSearchRepository(factory,new ElasticSearchFrequentlyRelatedItemSearchProcessor(config,new FrequentRelatedSearchRequestBuilder(config),RelatedItemNoopGetRepository.INSTANCE)); SearchResultEventWithSearchRequestKey[] results = repository.findRelatedItems(configuration, createSearch()); assertEquals(2,results.length); System.out.println("testTimeoutResultsAreReturned, Results 0 outcometype: " + results[0].getResponse().getOutcomeType()); System.out.println("testTimeoutResultsAreReturned, Results 1 outcometype: " + results[1].getResponse().getOutcomeType()); assertSame(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertSame(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); } finally { System.clearProperty(ConfigurationConstants.PROPNAME_FREQUENTLY_RELATED_SEARCH_TIMEOUT_IN_MILLIS); } }
@Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
@Test public void testFailureIsReturnedOnException() { ElasticSearchFrequentlyRelatedItemSearchProcessor processor = mock(ElasticSearchFrequentlyRelatedItemSearchProcessor.class); doThrow(new RuntimeException()).when(processor).executeSearch(any(Client.class), any(RelatedItemSearch[].class)); ElasticSearchRelatedItemSearchRepository repository = new ElasticSearchRelatedItemSearchRepository(factory,processor); RelatedItemSearch[] searches = createSearch(); SearchResultEventWithSearchRequestKey[] results = repository.findRelatedItems(configuration, searches); assertEquals(2,results.length); System.out.println("testFailureIsReturnedOnException, Results 0 outcometype: " + results[0].getResponse().getOutcomeType()); System.out.println("testFailureIsReturnedOnException, Results 1 outcometype: " + results[1].getResponse().getOutcomeType()); assertSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); reset(processor); MultiSearchResponse res1 = mock(MultiSearchResponse.class); when(processor.executeSearch(any(Client.class), any(RelatedItemSearch[].class))).thenReturn(res1); doThrow(new RuntimeException()).when(processor).processMultiSearchResponse(searches, res1); results = repository.findRelatedItems(configuration, searches); assertEquals(2,results.length); System.out.println("testFailureIsReturnedOnException, Results 0 outcometype: " + results[0].getResponse().getOutcomeType()); System.out.println("testFailureIsReturnedOnException, Results 1 outcometype: " + results[1].getResponse().getOutcomeType()); assertSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); }
@Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
@Test public void testFindRelatedItems() throws Exception { try { server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-14",RELATED_CONTENT_BLADES1_PURCHASEa); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-14",RELATED_CONTENT_BLADES1_PURCHASEb); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-15",RELATED_CONTENT_BLADES2_PURCHASEa); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-15",RELATED_CONTENT_BLADES2_PURCHASEb); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-15",RELATED_CONTENT_BLADES2_PURCHASEc); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-24",RELATED_CONTENT_THERAID_PURCHASEa); server.indexDocument(configuration.getStorageIndexNamePrefix()+"-2013-12-24",RELATED_CONTENT_THERAID_PURCHASEb); assertEquals(3,server.getIndexCount()); assertEquals(2,server.getDocCount(configuration.getStorageIndexNamePrefix()+"-2013-12-14")); assertEquals(3,server.getDocCount(configuration.getStorageIndexNamePrefix()+"-2013-12-15")); assertEquals(2,server.getDocCount(configuration.getStorageIndexNamePrefix()+"-2013-12-24")); } catch(Exception e) { fail("Cannot create test date for search test"); } RelatedItemSearch[] searches = createSearch(); SearchResultEventWithSearchRequestKey<FrequentlyRelatedSearchResult[]>[] results = repository.findRelatedItems(configuration, searches); assertEquals(2,results.length); assertNotSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, results[0].getResponse()); assertNotSame(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS, results[1].getResponse()); assertEquals(1, results[0].getResponse().getSearchResults().length); assertEquals("blades of glory",results[0].getResponse().getSearchResults()[0].getRelatedItemId()); assertEquals("enter the dragon",results[1].getResponse().getSearchResults()[0].getRelatedItemId()); }
@Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchResultEventWithSearchRequestKey[] results; MultiSearchResponse sr; long startNanos = System.nanoTime(); try { sr = frequentlyRelatedWithSearchBuilder.executeSearch(elasticClient,searches); log.debug("Processing results for search {} request(s)",searches.length); results = frequentlyRelatedWithSearchBuilder.processMultiSearchResponse(searches,sr); log.debug("Search Completed, returning processed results."); } catch(ElasticsearchTimeoutException timeoutException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Timeout exception executing search request: ",timeoutException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_TIMED_OUT_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } catch(Exception searchException) { long time = (System.nanoTime()-startNanos)/1000000; log.warn("Exception executing search request: ",searchException); int size = searches.length; results = new SearchResultEventWithSearchRequestKey[size]; for(int i=0;i<size;i++) { SearchRequestLookupKey key = searches[i].getLookupKey(); results[i] = new SearchResultEventWithSearchRequestKey(SearchResultsEvent.EMPTY_FAILED_FREQUENTLY_RELATED_SEARCH_RESULTS,key,time,searches[i].getStartOfRequestNanos()); } } return results; } ElasticSearchRelatedItemSearchRepository(ElasticSearchClientFactory searchClientFactory, ElasticSearchFrequentlyRelatedItemSearchProcessor builder); @Override SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches); @Override void shutdown(); }
@Test public void testProcessRequestThatFailsValidationIsCaughtAndNotProcessed() throws Exception { Configuration configuration = new SystemPropertiesConfiguration(); IncomingSearchRequestTranslator translator = mock(IncomingSearchRequestTranslator.class); RelatedContentSearchRequestProcessorHandler hanlder = mock(RelatedContentSearchRequestProcessorHandler.class); SearchRequestParameterValidatorLocator validatorFactory = mock(SearchRequestParameterValidatorLocator.class); SearchRequestParameterValidator validator = mock(SearchRequestParameterValidator.class); ValidationMessage message = mock(ValidationMessage.class); when(message.isValid()).thenReturn(false); when(validator.validateParameters(anyMap())).thenReturn(message); when(validatorFactory.getValidatorForType(RelatedItemSearchType.FREQUENTLY_RELATED_WITH)).thenReturn(validator); processor = new DisruptorBasedSearchRequestProcessor(translator, hanlder,new RelatedItemSearchRequestFactory(configuration),configuration,validatorFactory); SearchRequestSubmissionStatus status = processor.processRequest(RelatedItemSearchType.FREQUENTLY_RELATED_WITH,new HashMap<String,String>(),null); assertEquals(SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE,status); verify(translator, times(0)).translateTo(any(RelatedItemSearchRequest.class), anyLong(), any(RelatedItemSearchType.class), anyMap(), any(SearchResponseContext[].class)); }
@Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } DisruptorBasedSearchRequestProcessor(IncomingSearchRequestTranslator searchRequestTranslator , RelatedContentSearchRequestProcessorHandler eventHandler, RelatedItemSearchRequestFactory relatedItemSearchRequestFactory, Configuration configuration, SearchRequestParameterValidatorLocator searchRequestValidator); }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } DisruptorBasedSearchRequestProcessor(IncomingSearchRequestTranslator searchRequestTranslator , RelatedContentSearchRequestProcessorHandler eventHandler, RelatedItemSearchRequestFactory relatedItemSearchRequestFactory, Configuration configuration, SearchRequestParameterValidatorLocator searchRequestValidator); @Override SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context); @PreDestroy void shutdown(); }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } DisruptorBasedSearchRequestProcessor(IncomingSearchRequestTranslator searchRequestTranslator , RelatedContentSearchRequestProcessorHandler eventHandler, RelatedItemSearchRequestFactory relatedItemSearchRequestFactory, Configuration configuration, SearchRequestParameterValidatorLocator searchRequestValidator); @Override SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context); @PreDestroy void shutdown(); }
@Test public void testProcessRequestFailsValidationDueToMissingId() { Configuration configuration = new SystemPropertiesConfiguration(); IncomingSearchRequestTranslator translator = mock(IncomingSearchRequestTranslator.class); RelatedContentSearchRequestProcessorHandler hanlder = mock(RelatedContentSearchRequestProcessorHandler.class); SearchRequestParameterValidatorLocator validatorFactory = new MapBasedSearchRequestParameterValidatorLookup(configuration); processor = new DisruptorBasedSearchRequestProcessor(translator, hanlder,new RelatedItemSearchRequestFactory(configuration),configuration,validatorFactory); SearchRequestSubmissionStatus status = processor.processRequest(RelatedItemSearchType.FREQUENTLY_RELATED_WITH,new HashMap<String,String>(),null); assertEquals(SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE,status); verify(translator, times(0)).translateTo(any(RelatedItemSearchRequest.class), anyLong(), any(RelatedItemSearchType.class), anyMap(), any(SearchResponseContext[].class)); }
@Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } DisruptorBasedSearchRequestProcessor(IncomingSearchRequestTranslator searchRequestTranslator , RelatedContentSearchRequestProcessorHandler eventHandler, RelatedItemSearchRequestFactory relatedItemSearchRequestFactory, Configuration configuration, SearchRequestParameterValidatorLocator searchRequestValidator); }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } DisruptorBasedSearchRequestProcessor(IncomingSearchRequestTranslator searchRequestTranslator , RelatedContentSearchRequestProcessorHandler eventHandler, RelatedItemSearchRequestFactory relatedItemSearchRequestFactory, Configuration configuration, SearchRequestParameterValidatorLocator searchRequestValidator); @Override SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context); @PreDestroy void shutdown(); }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } DisruptorBasedSearchRequestProcessor(IncomingSearchRequestTranslator searchRequestTranslator , RelatedContentSearchRequestProcessorHandler eventHandler, RelatedItemSearchRequestFactory relatedItemSearchRequestFactory, Configuration configuration, SearchRequestParameterValidatorLocator searchRequestValidator); @Override SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context); @PreDestroy void shutdown(); }
@Test public void testParseSingleError() throws Exception { FrequentlyRelatedItemSearchResponse[] responses = parser.parse(SINGLE_ERROR_RESULTS); assertEquals("Should only have one result",1,responses.length); assertTrue("Result should be an error", responses[0].hasErrored()); assertEquals("error message not read from response","IndexMissingException[[testddddd] missing]",responses[0].getErrorMessage()); }
@Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
@Test public void testProcessorCalledAfterValidationSuccess() { Configuration configuration = new SystemPropertiesConfiguration(); IncomingSearchRequestTranslator translator = mock(IncomingSearchRequestTranslator.class); RelatedContentSearchRequestProcessorHandler hanlder = mock(RelatedContentSearchRequestProcessorHandler.class); SearchRequestParameterValidatorLocator validatorFactory = new MapBasedSearchRequestParameterValidatorLookup(configuration); processor = new DisruptorBasedSearchRequestProcessor(translator, hanlder,new RelatedItemSearchRequestFactory(configuration),configuration,validatorFactory); Map<String,String> requestParameters = new HashMap<String,String>(); requestParameters.put(configuration.getRequestParameterForId(),"1"); SearchRequestSubmissionStatus status = processor.processRequest(RelatedItemSearchType.FREQUENTLY_RELATED_WITH,requestParameters,null); assertEquals(SearchRequestSubmissionStatus.PROCESSING,status); verify(translator, times(1)).translateTo(any(RelatedItemSearchRequest.class), anyLong(), any(RelatedItemSearchType.class), anyMap(), any(SearchResponseContext[].class)); }
@Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } DisruptorBasedSearchRequestProcessor(IncomingSearchRequestTranslator searchRequestTranslator , RelatedContentSearchRequestProcessorHandler eventHandler, RelatedItemSearchRequestFactory relatedItemSearchRequestFactory, Configuration configuration, SearchRequestParameterValidatorLocator searchRequestValidator); }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } DisruptorBasedSearchRequestProcessor(IncomingSearchRequestTranslator searchRequestTranslator , RelatedContentSearchRequestProcessorHandler eventHandler, RelatedItemSearchRequestFactory relatedItemSearchRequestFactory, Configuration configuration, SearchRequestParameterValidatorLocator searchRequestValidator); @Override SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context); @PreDestroy void shutdown(); }
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidatorForType(requestType); if(validator !=null) { ValidationMessage isValid = validator.validateParameters(parameters); if(!isValid.isValid()) { log.warn("Invalid parameter :{} for search request type {}",isValid.getInvalidProperty(), requestType); return SearchRequestSubmissionStatus.REQUEST_VALIDATION_FAILURE; } } log.debug("Processing requesttype {} with parameters {}",requestType,parameters); boolean published = ringBuffer.tryPublishEvent(searchRequestTranslator, requestType, parameters, context); if(published) return SearchRequestSubmissionStatus.PROCESSING; else return SearchRequestSubmissionStatus.PROCESSING_REJECTED_AT_MAX_CAPACITY; } DisruptorBasedSearchRequestProcessor(IncomingSearchRequestTranslator searchRequestTranslator , RelatedContentSearchRequestProcessorHandler eventHandler, RelatedItemSearchRequestFactory relatedItemSearchRequestFactory, Configuration configuration, SearchRequestParameterValidatorLocator searchRequestValidator); @Override SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context); @PreDestroy void shutdown(); }
@Test public void testCallingOnEventThatEachExecutorIsCalledInRoundRobinFashion() throws Exception { Configuration config = new SystemPropertiesConfiguration(); RelatedItemSearchExecutor executor1 = mock(RelatedItemSearchExecutor.class); RelatedItemSearchExecutor executor2 = mock(RelatedItemSearchExecutor.class); RelatedItemSearchExecutor executor3 = mock(RelatedItemSearchExecutor.class); RelatedItemSearchExecutor executor4 = mock(RelatedItemSearchExecutor.class); RelatedItemSearchResultsToResponseGateway gateway = mock(RelatedItemSearchResultsToResponseGateway.class); handler = new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,new RelatedItemSearchExecutor[]{executor1,executor2,executor3,executor4}); RelatedItemSearchRequest r1 = new RelatedItemSearchRequest(config); r1.getSearchRequest().setLookupKey(new SipHashSearchRequestLookupKey("1")); handler.onEvent(r1,1,true); r1.getSearchRequest().setLookupKey(new SipHashSearchRequestLookupKey("2")); handler.onEvent(r1,1,true); r1.getSearchRequest().setLookupKey(new SipHashSearchRequestLookupKey("3")); handler.onEvent(r1,1,true); r1.getSearchRequest().setLookupKey(new SipHashSearchRequestLookupKey("4")); handler.onEvent(r1,1,true); verify(executor1,times(1)).executeSearch(any(RelatedItemSearch.class)); verify(executor2,times(1)).executeSearch(any(RelatedItemSearch.class)); verify(executor3,times(1)).executeSearch(any(RelatedItemSearch.class)); verify(executor4,times(1)).executeSearch(any(RelatedItemSearch.class)); }
@Override public void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch) throws Exception { handleRequest(event,searchRequestExecutor[this.currentIndex++ & mask]); }
RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler implements RelatedContentSearchRequestProcessorHandler { @Override public void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch) throws Exception { handleRequest(event,searchRequestExecutor[this.currentIndex++ & mask]); } }
RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler implements RelatedContentSearchRequestProcessorHandler { @Override public void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch) throws Exception { handleRequest(event,searchRequestExecutor[this.currentIndex++ & mask]); } RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(RelatedItemSearchResultsToResponseGateway contextStorage, RelatedItemSearchExecutor[] searchExecutor); }
RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler implements RelatedContentSearchRequestProcessorHandler { @Override public void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch) throws Exception { handleRequest(event,searchRequestExecutor[this.currentIndex++ & mask]); } RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(RelatedItemSearchResultsToResponseGateway contextStorage, RelatedItemSearchExecutor[] searchExecutor); @Override void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch); void handleRequest(RelatedItemSearchRequest searchRequest, RelatedItemSearchExecutor searchExecutor); void shutdown(); }
RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler implements RelatedContentSearchRequestProcessorHandler { @Override public void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch) throws Exception { handleRequest(event,searchRequestExecutor[this.currentIndex++ & mask]); } RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(RelatedItemSearchResultsToResponseGateway contextStorage, RelatedItemSearchExecutor[] searchExecutor); @Override void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch); void handleRequest(RelatedItemSearchRequest searchRequest, RelatedItemSearchExecutor searchExecutor); void shutdown(); }
@Test public void testTranslateTo() throws Exception { Configuration config = new SystemPropertiesConfiguration(); RelatedItemSearchRequest request = new RelatedItemSearchRequest(config); Map<String,String> properties = new HashMap<String,String>(); properties.put(config.getRequestParameterForId(),"id1"); properties.put("channel","com"); SearchResponseContext[] contexts = new SearchResponseContext[] {new AsyncServletSearchResponseContext(mock(AsyncContext.class))}; RelatedItemSearchRequestTranslator translator = new RelatedItemSearchRequestTranslator( new RelatedItemSearchFactoryWithSearchLookupKeyFactory(config,new KeyFactoryBasedRelatedItemSearchLookupKeyGenerator(config,new SipHashSearchRequestLookupKeyFactory()))); translator.translateTo(request, 1, RelatedItemSearchType.FREQUENTLY_RELATED_WITH,properties,contexts); assertSame(request.getRequestContexts(), contexts); assertEquals(request.getSearchRequest().getRelatedItemId(),"id1"); assertEquals(1,request.getSearchRequest().getAdditionalSearchCriteria().getNumberOfProperties()); assertEquals("channel",request.getSearchRequest().getAdditionalSearchCriteria().getPropertyName(0)); assertEquals("com",request.getSearchRequest().getAdditionalSearchCriteria().getPropertyValue(0)); }
@Override public void translateTo(RelatedItemSearchRequest event, long sequence, RelatedItemSearchType type, Map<String,String> params, SearchResponseContext[] contexts) { log.debug("Creating Related Product Search Request {}, {}",event.getSearchRequest().getLookupKey(),params); event.setRequestContexts(contexts); relatedItemSearchFactory.populateSearchObject(event.getSearchRequest(), type,params); }
RelatedItemSearchRequestTranslator implements IncomingSearchRequestTranslator { @Override public void translateTo(RelatedItemSearchRequest event, long sequence, RelatedItemSearchType type, Map<String,String> params, SearchResponseContext[] contexts) { log.debug("Creating Related Product Search Request {}, {}",event.getSearchRequest().getLookupKey(),params); event.setRequestContexts(contexts); relatedItemSearchFactory.populateSearchObject(event.getSearchRequest(), type,params); } }
RelatedItemSearchRequestTranslator implements IncomingSearchRequestTranslator { @Override public void translateTo(RelatedItemSearchRequest event, long sequence, RelatedItemSearchType type, Map<String,String> params, SearchResponseContext[] contexts) { log.debug("Creating Related Product Search Request {}, {}",event.getSearchRequest().getLookupKey(),params); event.setRequestContexts(contexts); relatedItemSearchFactory.populateSearchObject(event.getSearchRequest(), type,params); } RelatedItemSearchRequestTranslator(RelatedItemSearchFactory relatedItemSearchFactory); }
RelatedItemSearchRequestTranslator implements IncomingSearchRequestTranslator { @Override public void translateTo(RelatedItemSearchRequest event, long sequence, RelatedItemSearchType type, Map<String,String> params, SearchResponseContext[] contexts) { log.debug("Creating Related Product Search Request {}, {}",event.getSearchRequest().getLookupKey(),params); event.setRequestContexts(contexts); relatedItemSearchFactory.populateSearchObject(event.getSearchRequest(), type,params); } RelatedItemSearchRequestTranslator(RelatedItemSearchFactory relatedItemSearchFactory); @Override void translateTo(RelatedItemSearchRequest event, long sequence, RelatedItemSearchType type, Map<String,String> params, SearchResponseContext[] contexts); }
RelatedItemSearchRequestTranslator implements IncomingSearchRequestTranslator { @Override public void translateTo(RelatedItemSearchRequest event, long sequence, RelatedItemSearchType type, Map<String,String> params, SearchResponseContext[] contexts) { log.debug("Creating Related Product Search Request {}, {}",event.getSearchRequest().getLookupKey(),params); event.setRequestContexts(contexts); relatedItemSearchFactory.populateSearchObject(event.getSearchRequest(), type,params); } RelatedItemSearchRequestTranslator(RelatedItemSearchFactory relatedItemSearchFactory); @Override void translateTo(RelatedItemSearchRequest event, long sequence, RelatedItemSearchType type, Map<String,String> params, SearchResponseContext[] contexts); }
@Test public void testSingleRelatedContentSearchRequestProcessorHandlerIsCreated() { System.setProperty(ConfigurationConstants.PROPNAME_NUMBER_OF_SEARCHING_REQUEST_PROCESSORS,"1"); Configuration config = new SystemPropertiesConfiguration(); RoundRobinRelatedContentSearchRequestProcessorHandlerFactory factory = new RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); RelatedContentSearchRequestProcessorHandler handler = factory.createHandler(config,mock(RelatedItemSearchResultsToResponseGateway.class),mock(RelatedItemSearchExecutorFactory.class)); assertTrue(handler instanceof DisruptorBasedRelatedContentSearchRequestProcessorHandler); }
@Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } }
RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } } }
RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } } RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); }
RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } } RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); @Override RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ); }
RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } } RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); @Override RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ); }
@Test public void testRoundRobinRelatedContentSearchRequestProcessorHandlerIsCreated() { System.setProperty(ConfigurationConstants.PROPNAME_NUMBER_OF_SEARCHING_REQUEST_PROCESSORS,"2"); Configuration config = new SystemPropertiesConfiguration(); RoundRobinRelatedContentSearchRequestProcessorHandlerFactory factory = new RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); RelatedContentSearchRequestProcessorHandler handler = factory.createHandler(config,mock(RelatedItemSearchResultsToResponseGateway.class),mock(RelatedItemSearchExecutorFactory.class)); assertTrue(handler instanceof RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler); }
@Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } }
RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } } }
RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } } RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); }
RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } } RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); @Override RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ); }
RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } } RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); @Override RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ); }
@Test public void testStoreResponseContextForSearchRequest() throws Exception { Configuration config = new SystemPropertiesConfiguration(); RequestCountingContextLookup contextLookup = new RequestCountingContextLookup(new MultiMapSearchResponseContextLookup(config),1,1); ResponseEventHandler responseHandler = mock(ResponseEventHandler.class); gateway = new DisruptorRelatedItemSearchResultsToResponseGateway(new SystemPropertiesConfiguration(), new RequestSearchEventProcessor(contextLookup), new ResponseSearchEventProcessor(contextLookup,responseHandler)); SearchResponseContext[] holder = new SearchResponseContext[] { LogDebuggingSearchResponseContext.INSTANCE}; gateway.storeResponseContextForSearchRequest(new SipHashSearchRequestLookupKey("1"),holder); boolean added = contextLookup.waitOnAddContexts(1000); assertTrue(added); List<SearchResponseContext> holders = contextLookup.removeContexts(new SipHashSearchRequestLookupKey("1")); assertEquals(1, holders.size()); assertSame(holders.get(0),holder[0]); contextLookup.reset(1,3); gateway.storeResponseContextForSearchRequest(new SipHashSearchRequestLookupKey("1"),holder); gateway.storeResponseContextForSearchRequest(new SipHashSearchRequestLookupKey("1"),holder); gateway.storeResponseContextForSearchRequest(new SipHashSearchRequestLookupKey("1"),holder); added = contextLookup.waitOnAddContexts(1000); assertTrue(added); holders = contextLookup.removeContexts(new SipHashSearchRequestLookupKey("1")); assertEquals(3, holders.size()); }
@Override public void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context) { ringBuffer.publishEvent(storeResponseContextTranslator,key,context); }
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context) { ringBuffer.publishEvent(storeResponseContextTranslator,key,context); } }
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context) { ringBuffer.publishEvent(storeResponseContextTranslator,key,context); } DisruptorRelatedItemSearchResultsToResponseGateway(Configuration configuration, SearchEventProcessor requestProcessor, SearchEventProcessor responseProcessor ); }
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context) { ringBuffer.publishEvent(storeResponseContextTranslator,key,context); } DisruptorRelatedItemSearchResultsToResponseGateway(Configuration configuration, SearchEventProcessor requestProcessor, SearchEventProcessor responseProcessor ); @Override void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context); @Override void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults); @Override void shutdown(); }
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context) { ringBuffer.publishEvent(storeResponseContextTranslator,key,context); } DisruptorRelatedItemSearchResultsToResponseGateway(Configuration configuration, SearchEventProcessor requestProcessor, SearchEventProcessor responseProcessor ); @Override void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context); @Override void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults); @Override void shutdown(); }
@Test public void testSendSearchResultsToResponseContexts() throws Exception { Configuration config = new SystemPropertiesConfiguration(); RequestCountingContextLookup contextLookup = new RequestCountingContextLookup(new MultiMapSearchResponseContextLookup(config),1,1); ResponseEventHandler responseHandler = mock(ResponseEventHandler.class); gateway = new DisruptorRelatedItemSearchResultsToResponseGateway(new SystemPropertiesConfiguration(), new RequestSearchEventProcessor(contextLookup), new ResponseSearchEventProcessor(contextLookup,responseHandler)); SearchResponseContextHolder holder = new SearchResponseContextHolder(); gateway.storeResponseContextForSearchRequest(new SipHashSearchRequestLookupKey("1"),null); boolean added = contextLookup.waitOnAddContexts(1000); assertTrue(added); SearchResultEventWithSearchRequestKey results = new SearchResultEventWithSearchRequestKey(mock(SearchResultsEvent.class),new SipHashSearchRequestLookupKey("1"),0,0); gateway.sendSearchResultsToResponseContexts(new SearchResultEventWithSearchRequestKey[]{results}); added = contextLookup.waitOnRemoveContexts(1000); assertTrue(added); assertEquals(0,contextLookup.removeContexts(new SipHashSearchRequestLookupKey("1")).size()); }
@Override public void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults) { ringBuffer.publishEvent(processSearchResultsTranslator,multipleSearchResults); }
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults) { ringBuffer.publishEvent(processSearchResultsTranslator,multipleSearchResults); } }
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults) { ringBuffer.publishEvent(processSearchResultsTranslator,multipleSearchResults); } DisruptorRelatedItemSearchResultsToResponseGateway(Configuration configuration, SearchEventProcessor requestProcessor, SearchEventProcessor responseProcessor ); }
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults) { ringBuffer.publishEvent(processSearchResultsTranslator,multipleSearchResults); } DisruptorRelatedItemSearchResultsToResponseGateway(Configuration configuration, SearchEventProcessor requestProcessor, SearchEventProcessor responseProcessor ); @Override void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context); @Override void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults); @Override void shutdown(); }
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults) { ringBuffer.publishEvent(processSearchResultsTranslator,multipleSearchResults); } DisruptorRelatedItemSearchResultsToResponseGateway(Configuration configuration, SearchEventProcessor requestProcessor, SearchEventProcessor responseProcessor ); @Override void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context); @Override void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults); @Override void shutdown(); }
@Test public void testHandleFrequentlyRelatedSearchResultResponseEvent() throws Exception { SearchResultsConverterFactory resultsConverterFactory = mock(SearchResultsConverterFactory.class); NumberOfSearchResultsConverter searchResultsConverter = new NumberOfSearchResultsConverter("application/json"); when(resultsConverterFactory.getConverter(FrequentlyRelatedSearchResult[].class)).thenReturn(searchResultsConverter); CountingSearchResponseContextHandler contextHandler = new CountingSearchResponseContextHandler(); CountingSearchResponseContextHandler defaultHandler = new CountingSearchResponseContextHandler(); Map<Class,SearchResponseContextHandler> mappings = new HashMap<Class,SearchResponseContextHandler>(4); mappings.put(AsyncContext.class,contextHandler); CountDownLatch latch = new CountDownLatch(1); eventHandler = createResponseEventHandler(configuration,new MapBasedSearchResponseContextHandlerLookup(defaultHandler,mappings),resultsConverterFactory,latch); SearchResponseContext<AsyncContext> context = mock(AsyncServletSearchResponseContext.class); when(context.getContextType()).thenReturn(AsyncContext.class); List<SearchResponseContext> holder = new ArrayList<SearchResponseContext>(1); holder.add(context); SearchResultsEvent searchResultsEvent = createFrequentlyRelatedSearchResultResponse(new String[]{"1", "2", "3"}, new long[]{1, 2, 3}); List<List<SearchResponseContext>> contexts = new ArrayList<List<SearchResponseContext>>(1); contexts.add(holder); eventHandler.handleResponseEvents(createSearchResultsEvent(new SearchResultsEvent[]{searchResultsEvent}),contexts); try { boolean handled = latch.await(2000, TimeUnit.MILLISECONDS); if(handled==false) fail("Failed waiting for latch in testHandleFrequentlyRelatedSearchResultResponseEvent"); } catch(Exception e) { fail("Failed waiting for latch"); } assertEquals(1, contextHandler.getMethodInvocationCount()); assertEquals(searchResultsConverter.convertToString(createSearchResultsEvent(new SearchResultsEvent[]{searchResultsEvent})[0]),contextHandler.getResultsString()); assertEquals(0,defaultHandler.getMethodInvocationCount()); assertEquals(2, searchResultsConverter.getNoOfExecutions()); verify(context, times(1)).close(); }
@Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); @Override void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts); @Override void shutdown(); void handleResponseEvent(SearchResultEventWithSearchRequestKey results,List<SearchResponseContext> awaitingResponses); }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); @Override void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts); @Override void shutdown(); void handleResponseEvent(SearchResultEventWithSearchRequestKey results,List<SearchResponseContext> awaitingResponses); static final String ERROR_RESPONSE; static final String ERROR_MEDIA_TYPE; }
@Test public void testHandlingSearchResultsEventWithNoConverterResponseEvent() throws Exception { SearchResultsConverterFactory resultsConverterFactory = mock(SearchResultsConverterFactory.class); NumberOfSearchResultsConverter searchResultsConverter = new NumberOfSearchResultsConverter("application/json"); when(resultsConverterFactory.getConverter(FrequentlyRelatedSearchResult[].class)).thenReturn(searchResultsConverter); SearchResponseContextHandler contextHandler = mock(SearchResponseContextHandler.class); SearchResponseContextHandler defaultHandler = mock(SearchResponseContextHandler.class); Map<Class,SearchResponseContextHandler> mappings = new HashMap<Class,SearchResponseContextHandler>(4); mappings.put(AsyncContext.class,contextHandler); CountDownLatch latch = new CountDownLatch(1); eventHandler = createResponseEventHandler(configuration,new MapBasedSearchResponseContextHandlerLookup(defaultHandler,mappings),resultsConverterFactory,latch); SearchResponseContext<AsyncContext> context = mock(AsyncServletSearchResponseContext.class); when(context.getContextType()).thenReturn(AsyncContext.class); List<SearchResponseContext> holder = new ArrayList<SearchResponseContext>(1); holder.add(context); SearchResultsEvent searchResultsEvent = createStringResponse(); List<List<SearchResponseContext>> list= new ArrayList<List<SearchResponseContext>>(1); list.add(holder); eventHandler.handleResponseEvents(createSearchResultsEvent(new SearchResultsEvent[] {searchResultsEvent}),list); try { boolean handled = latch.await(2000, TimeUnit.MILLISECONDS); if(handled==false) fail("Failed waiting for latch"); } catch(Exception e) { fail("Failed waiting for latch"); } assertEquals(0, searchResultsConverter.getNoOfExecutions()); verify(contextHandler,times(1)).sendResults(eq(ResponseContextTypeBasedResponseEventHandler.ERROR_RESPONSE),eq(ResponseContextTypeBasedResponseEventHandler.ERROR_MEDIA_TYPE),any(SearchResultsEvent.class),any(SearchResponseContext.class)); verify(defaultHandler,times(0)).sendResults(anyString(),anyString(),any(SearchResultsEvent.class),any(SearchResponseContext.class)); verify(context, times(1)).close(); }
@Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); @Override void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts); @Override void shutdown(); void handleResponseEvent(SearchResultEventWithSearchRequestKey results,List<SearchResponseContext> awaitingResponses); }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); @Override void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts); @Override void shutdown(); void handleResponseEvent(SearchResultEventWithSearchRequestKey results,List<SearchResponseContext> awaitingResponses); static final String ERROR_RESPONSE; static final String ERROR_MEDIA_TYPE; }
@Test public void testContextIsClosedWhenNoHandlerIsAvailable() { SearchResultsConverterFactory resultsConverterFactory = mock(SearchResultsConverterFactory.class); NumberOfSearchResultsConverter searchResultsConverter = new NumberOfSearchResultsConverter("application/json"); when(resultsConverterFactory.getConverter(FrequentlyRelatedSearchResult[].class)).thenReturn(searchResultsConverter); SearchResponseContextHandlerLookup handlerLookup = mock(SearchResponseContextHandlerLookup.class); when(handlerLookup.getHandler(any(Class.class))).thenReturn(null); CountDownLatch latch = new CountDownLatch(1); eventHandler = createResponseEventHandler(configuration,handlerLookup,resultsConverterFactory,latch); SearchResponseContext<AsyncContext> context = mock(AsyncServletSearchResponseContext.class); when(context.getContextType()).thenReturn(AsyncContext.class); List<SearchResponseContext> holder = new ArrayList<SearchResponseContext>(1); holder.add(context); List<List<SearchResponseContext>> list= new ArrayList<List<SearchResponseContext>>(1); list.add(holder); eventHandler.handleResponseEvents(createSearchResultsEvent(new SearchResultsEvent[]{createStringResponse()}),list); try { boolean handled = latch.await(2000, TimeUnit.MILLISECONDS); if(handled==false) fail("Failed waiting for latch"); } catch(Exception e) { fail("Failed waiting for latch"); } assertEquals(0, searchResultsConverter.getNoOfExecutions()); verify(context, times(1)).close(); }
@Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); @Override void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts); @Override void shutdown(); void handleResponseEvent(SearchResultEventWithSearchRequestKey results,List<SearchResponseContext> awaitingResponses); }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); @Override void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts); @Override void shutdown(); void handleResponseEvent(SearchResultEventWithSearchRequestKey results,List<SearchResponseContext> awaitingResponses); static final String ERROR_RESPONSE; static final String ERROR_MEDIA_TYPE; }
@Test public void testParseSingleResult() { FrequentlyRelatedItemSearchResponse[] responses = parser.parse(SINGLE_RESULT); assertEquals("Should only have one result",1,responses.length); assertFalse("Result should not be an error", responses[0].hasErrored()); assertEquals("Result should have 1 terms",1,responses[0].getNumberOfFacets()); assertEquals("Result should have 1 terms of '4'","4",responses[0].getFacetResult(0).name); assertEquals("Result should have 1 terms with count of '1002'",1002,responses[0].getFacetResult(0).count); }
@Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
@Test public void testHandlingSearchResultsEventWithNoAwaitingContext() throws Exception { SearchResultsConverterFactory resultsConverterFactory = mock(SearchResultsConverterFactory.class); NumberOfSearchResultsConverter searchResultsConverter = new NumberOfSearchResultsConverter("application/json"); when(resultsConverterFactory.getConverter(FrequentlyRelatedSearchResult[].class)).thenReturn(searchResultsConverter); SearchResponseContextHandler contextHandler = mock(SearchResponseContextHandler.class); SearchResponseContextHandler defaultHandler = mock(SearchResponseContextHandler.class); Map<Class,SearchResponseContextHandler> mappings = new HashMap<Class,SearchResponseContextHandler>(4); mappings.put(AsyncContext.class,contextHandler); CountDownLatch latch = new CountDownLatch(1); eventHandler = createResponseEventHandler(configuration,new MapBasedSearchResponseContextHandlerLookup(defaultHandler,mappings),resultsConverterFactory,latch); SearchResponseContext<AsyncContext> context = mock(AsyncServletSearchResponseContext.class); when(context.getContextType()).thenReturn(AsyncContext.class); List<SearchResponseContext> holder = new ArrayList<SearchResponseContext>(0); List<List<SearchResponseContext>> list= new ArrayList<List<SearchResponseContext>>(1); list.add(holder); eventHandler.handleResponseEvents(createSearchResultsEvent(new SearchResultsEvent[]{createStringResponse()}),list); assertEquals(0, searchResultsConverter.getNoOfExecutions()); try { boolean handled = latch.await(2000, TimeUnit.MILLISECONDS); if(handled==false) fail("Failed waiting for latch"); } catch(Exception e) { fail("Failed waiting for latch"); } verify(contextHandler,times(0)).sendResults(eq(ResponseContextTypeBasedResponseEventHandler.ERROR_RESPONSE),eq(ResponseContextTypeBasedResponseEventHandler.ERROR_MEDIA_TYPE),any(SearchResultsEvent.class),any(SearchResponseContext.class)); verify(defaultHandler,times(0)).sendResults(anyString(),anyString(),any(SearchResultsEvent.class),any(SearchResponseContext.class)); reset(contextHandler,defaultHandler); eventHandler.handleResponseEvents(createSearchResultsEvent(new SearchResultsEvent[]{createStringResponse()}),list); try { boolean handled = latch.await(2000, TimeUnit.MILLISECONDS); if(handled==false) fail("Failed waiting for latch in"); } catch(Exception e) { fail("Failed waiting for latch"); } assertEquals(0, searchResultsConverter.getNoOfExecutions()); verify(contextHandler,times(0)).sendResults(eq(ResponseContextTypeBasedResponseEventHandler.ERROR_RESPONSE),eq(ResponseContextTypeBasedResponseEventHandler.ERROR_MEDIA_TYPE),any(SearchResultsEvent.class),any(SearchResponseContext.class)); verify(defaultHandler,times(0)).sendResults(anyString(),anyString(),any(SearchResultsEvent.class),any(SearchResponseContext.class)); }
@Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); @Override void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts); @Override void shutdown(); void handleResponseEvent(SearchResultEventWithSearchRequestKey results,List<SearchResponseContext> awaitingResponses); }
ResponseContextTypeBasedResponseEventHandler implements ResponseEventHandler { @Override public void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts) { for(int i=0;i<searchResults.length;i++) { log.debug("handling search result {}",i); handleResponseEvent(searchResults[i],responseContexts.get(i)); } } ResponseContextTypeBasedResponseEventHandler(SearchResponseContextHandlerLookup responseContextHandler, SearchResultsConverterFactory factory); @Override void handleResponseEvents(SearchResultEventWithSearchRequestKey[] searchResults,List<List<SearchResponseContext>> responseContexts); @Override void shutdown(); void handleResponseEvent(SearchResultEventWithSearchRequestKey results,List<SearchResponseContext> awaitingResponses); static final String ERROR_RESPONSE; static final String ERROR_MEDIA_TYPE; }
@Test public void testGetHandlerReturnsDefaultMapping() throws Exception { SearchResponseContextHandler h = defaultLookup.getHandler(Long.class); assertSame(DebugSearchResponseContextHandler.INSTANCE,h); }
@Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSearchResponseContextHandlerLookup(final Configuration config); MapBasedSearchResponseContextHandlerLookup(SearchResponseContextHandler defaultMapping, Map<Class,SearchResponseContextHandler> mappings); }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSearchResponseContextHandlerLookup(final Configuration config); MapBasedSearchResponseContextHandlerLookup(SearchResponseContextHandler defaultMapping, Map<Class,SearchResponseContextHandler> mappings); static Map<Class, SearchResponseContextHandler> createDefaultHandlerMap(SearchResponseContextHandler defaultHandler, Configuration config); @Override SearchResponseContextHandler getHandler(Class responseClassToHandle); }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSearchResponseContextHandlerLookup(final Configuration config); MapBasedSearchResponseContextHandlerLookup(SearchResponseContextHandler defaultMapping, Map<Class,SearchResponseContextHandler> mappings); static Map<Class, SearchResponseContextHandler> createDefaultHandlerMap(SearchResponseContextHandler defaultHandler, Configuration config); @Override SearchResponseContextHandler getHandler(Class responseClassToHandle); }
@Test public void testDefaultHandlerReturnedForCustomLookup() { assertSame(mockHandler1, customMappingsLookup.getHandler(Long.class)); assertSame(mockHandler2,customMappingsLookup.getHandler(String.class)); assertSame(DebugSearchResponseContextHandler.INSTANCE,customMappingsLookup.getHandler(AsyncContext.class)); }
@Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSearchResponseContextHandlerLookup(final Configuration config); MapBasedSearchResponseContextHandlerLookup(SearchResponseContextHandler defaultMapping, Map<Class,SearchResponseContextHandler> mappings); }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSearchResponseContextHandlerLookup(final Configuration config); MapBasedSearchResponseContextHandlerLookup(SearchResponseContextHandler defaultMapping, Map<Class,SearchResponseContextHandler> mappings); static Map<Class, SearchResponseContextHandler> createDefaultHandlerMap(SearchResponseContextHandler defaultHandler, Configuration config); @Override SearchResponseContextHandler getHandler(Class responseClassToHandle); }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSearchResponseContextHandlerLookup(final Configuration config); MapBasedSearchResponseContextHandlerLookup(SearchResponseContextHandler defaultMapping, Map<Class,SearchResponseContextHandler> mappings); static Map<Class, SearchResponseContextHandler> createDefaultHandlerMap(SearchResponseContextHandler defaultHandler, Configuration config); @Override SearchResponseContextHandler getHandler(Class responseClassToHandle); }
@Test public void testDefaultMappings() { assertTrue(defaultLookup.getHandler(AsyncContext.class) instanceof SearchResponseContextHandler); assertSame(DebugSearchResponseContextHandler.INSTANCE,defaultLookup.getHandler(LogDebuggingSearchResponseContext.class)); }
@Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSearchResponseContextHandlerLookup(final Configuration config); MapBasedSearchResponseContextHandlerLookup(SearchResponseContextHandler defaultMapping, Map<Class,SearchResponseContextHandler> mappings); }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSearchResponseContextHandlerLookup(final Configuration config); MapBasedSearchResponseContextHandlerLookup(SearchResponseContextHandler defaultMapping, Map<Class,SearchResponseContextHandler> mappings); static Map<Class, SearchResponseContextHandler> createDefaultHandlerMap(SearchResponseContextHandler defaultHandler, Configuration config); @Override SearchResponseContextHandler getHandler(Class responseClassToHandle); }
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSearchResponseContextHandlerLookup(final Configuration config); MapBasedSearchResponseContextHandlerLookup(SearchResponseContextHandler defaultMapping, Map<Class,SearchResponseContextHandler> mappings); static Map<Class, SearchResponseContextHandler> createDefaultHandlerMap(SearchResponseContextHandler defaultHandler, Configuration config); @Override SearchResponseContextHandler getHandler(Class responseClassToHandle); }
@Test public void testResultsSent() { Configuration configuration = mock(Configuration.class); when(configuration.getResponseCode(any(SearchResultsOutcome.class))).thenReturn(200); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); ServletOutputStream out = new ServletOutputStream() { public OutputStream getOutputStream() { return stream; } @Override public void write(int b) throws IOException { stream.write(b); } }; StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); try { when(response.getOutputStream()).thenReturn(out); } catch (IOException e) { e.printStackTrace(); } try { when(response.getWriter()).thenReturn(writer); } catch (IOException e) { e.printStackTrace(); } AsyncContext userResponse = getAsyncContext(request,response); SearchResponseContext responseHolder = new AsyncServletSearchResponseContext(userResponse,System.nanoTime()); SearchResponseContextHandler handler = getHandler(configuration); handler.sendResults("results","appplication/json",createSearchResultEvent(),responseHolder); String s = new String(stream.toByteArray()); if(s.length()==0) { s = stringWriter.toString(); } assertEquals("results",s); responseHolder.close(); verify(userResponse,times(1)).complete(); }
@Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); @Override void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx); }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); @Override void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx); }
@Test public void testResultsNotSentWhenRequestOrResponseNotAvailable() { Configuration configuration = mock(Configuration.class); when(configuration.getResponseCode(any(SearchResultsOutcome.class))).thenReturn(200); AsyncContext userResponse = getAsyncContext(null,null); SearchResponseContext responseHolder = new AsyncServletSearchResponseContext(userResponse,System.nanoTime()); SearchResponseContextHandler handler = getHandler(configuration); handler.sendResults("results","appplication/json",null,responseHolder); verify(configuration,times(0)).getResponseCode(any(SearchResultsOutcome.class)); responseHolder.close(); verify(userResponse,times(1)).complete(); }
@Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); @Override void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx); }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); @Override void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx); }
@Test public void testIOExceptionIsHandled() { Configuration configuration = mock(Configuration.class); when(configuration.getResponseCode(any(SearchResultsOutcome.class))).thenReturn(200); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); try { doThrow(new IOException()).when(response).getWriter(); } catch (IOException e) { e.printStackTrace(); } AsyncContext userResponse = getAsyncContext(request,response); SearchResponseContext responseHolder = new AsyncServletSearchResponseContext(userResponse,System.nanoTime()); SearchResponseContextHandler handler = getHandler(configuration); handler.sendResults("results","appplication/json",mock(SearchResultsEvent.class),responseHolder); verify(response,times(1)).setStatus(500); responseHolder.close(); verify(userResponse, times(1)).complete(); }
@Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); @Override void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx); }
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); @Override void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx); }
@Test public void testJsonSmartConverterIsCreated() { JsonSmartIndexingRequestConverterFactory factory = new JsonSmartIndexingRequestConverterFactory(new JodaISO8601UTCCurrentDateAndTimeFormatter()); try { factory.createConverter(new SystemPropertiesConfiguration(), ByteBuffer.wrap(new byte[0])); fail("Should not be able to create a converter that deals with no data"); } catch(InvalidIndexingRequestException e) { } String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ \"B009S4IJCK\", \"B0076UICIO\" ,\"B0096TJCXW\" ]"+ "}"; IndexingRequestConverter converter = factory.createConverter(new SystemPropertiesConfiguration(), ByteBuffer.wrap(json.getBytes())); assertTrue(converter instanceof JsonSmartIndexingRequestConverter); }
@Override public IndexingRequestConverter createConverter(Configuration configuration, ByteBuffer convertFrom) throws InvalidIndexingRequestException { return new JsonSmartIndexingRequestConverter(configuration,dateCreator,convertFrom); }
JsonSmartIndexingRequestConverterFactory implements IndexingRequestConverterFactory { @Override public IndexingRequestConverter createConverter(Configuration configuration, ByteBuffer convertFrom) throws InvalidIndexingRequestException { return new JsonSmartIndexingRequestConverter(configuration,dateCreator,convertFrom); } }
JsonSmartIndexingRequestConverterFactory implements IndexingRequestConverterFactory { @Override public IndexingRequestConverter createConverter(Configuration configuration, ByteBuffer convertFrom) throws InvalidIndexingRequestException { return new JsonSmartIndexingRequestConverter(configuration,dateCreator,convertFrom); } JsonSmartIndexingRequestConverterFactory(ISO8601UTCCurrentDateAndTimeFormatter formatter); }
JsonSmartIndexingRequestConverterFactory implements IndexingRequestConverterFactory { @Override public IndexingRequestConverter createConverter(Configuration configuration, ByteBuffer convertFrom) throws InvalidIndexingRequestException { return new JsonSmartIndexingRequestConverter(configuration,dateCreator,convertFrom); } JsonSmartIndexingRequestConverterFactory(ISO8601UTCCurrentDateAndTimeFormatter formatter); @Override IndexingRequestConverter createConverter(Configuration configuration, ByteBuffer convertFrom); }
JsonSmartIndexingRequestConverterFactory implements IndexingRequestConverterFactory { @Override public IndexingRequestConverter createConverter(Configuration configuration, ByteBuffer convertFrom) throws InvalidIndexingRequestException { return new JsonSmartIndexingRequestConverter(configuration,dateCreator,convertFrom); } JsonSmartIndexingRequestConverterFactory(ISO8601UTCCurrentDateAndTimeFormatter formatter); @Override IndexingRequestConverter createConverter(Configuration configuration, ByteBuffer convertFrom); }
@Test public void testANonStringPropertyIsIgnored() { String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ \"B009S4IJCK\", \"B0076UICIO\" ,\"B0096TJCXW\" ]"+ "}"; IndexingRequestConverter converter = createConverter(ByteBuffer.wrap(json.getBytes())); RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(new SystemPropertiesConfiguration()); converter.translateTo(message,1); assertEquals(1,message.getIndexingMessageProperties().getNumberOfProperties()); }
@Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); }
JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); } }
JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); } JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData); JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData, int maxNumberOfAllowedProperties,int maxNumberOfRelatedItems); }
JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); } JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData); JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData, int maxNumberOfAllowedProperties,int maxNumberOfRelatedItems); @Override void translateTo(RelatedItemIndexingMessage convertedTo, long sequence); }
JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); } JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData); JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData, int maxNumberOfAllowedProperties,int maxNumberOfRelatedItems); @Override void translateTo(RelatedItemIndexingMessage convertedTo, long sequence); }
@Test public void testExceptionIsNotThrownWhenJsonContainsTooManyProducts() { System.setProperty(ConfigurationConstants.PROPNAME_DISCARD_INDEXING_REQUESTS_WITH_TOO_MANY_ITEMS,"false"); System.setProperty(ConfigurationConstants.PROPNAME_MAX_NO_OF_RELATED_ITEMS_PER_INDEX_REQUEST,"2"); String json = "{" + " \"channel\" : \"uk\"," + " \"site\" : \"amazon\"," + " \"date\" : \"2013-05-02T15:31:31\"," + " \"items\" : [ \"B009S4IJCK\", \"B0076UICIO\" ,\"B0096TJCXW\" ]"+ "}"; try { IndexingRequestConverter converter = createConverter(ByteBuffer.wrap(json.getBytes())); RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(new SystemPropertiesConfiguration()); converter.translateTo(message,1); assertEquals(2, message.getRelatedItems().getNumberOfRelatedItems()); if(message.getRelatedItems().getRelatedItemAtIndex(0).getId().toString().equals("B009S4IJCK")) { assertEquals("B0076UICIO",message.getRelatedItems().getRelatedItemAtIndex(1).getId().toString()); } else if(message.getRelatedItems().getRelatedItemAtIndex(0).getId().toString().equals("B0076UICIO")) { assertEquals("B009S4IJCK",message.getRelatedItems().getRelatedItemAtIndex(1).getId().toString()); } else { fail("Json message should have thrown away the last id."); } } catch(InvalidIndexingRequestException e) { fail("Should be able to parse json, just that some related items are not stored"); } }
@Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); }
JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); } }
JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); } JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData); JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData, int maxNumberOfAllowedProperties,int maxNumberOfRelatedItems); }
JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); } JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData); JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData, int maxNumberOfAllowedProperties,int maxNumberOfRelatedItems); @Override void translateTo(RelatedItemIndexingMessage convertedTo, long sequence); }
JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); } JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData); JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData, int maxNumberOfAllowedProperties,int maxNumberOfRelatedItems); @Override void translateTo(RelatedItemIndexingMessage convertedTo, long sequence); }
@Test public void testParseTwoResultsOneErrorOneOk() { FrequentlyRelatedItemSearchResponse[] responses = parser.parse(TWO_RESULTS_ONE_WITH_ERROR); assertEquals("Should only have two results",2,responses.length); assertEquals("Result should have 3 terms",3,responses[0].getNumberOfFacets()); assertEquals("Result should have 3 terms with term 1 of '4'","4",responses[0].getFacetResult(0).name); assertEquals("Result should have 3 terms with term 1 of '4'","3",responses[0].getFacetResult(1).name); assertEquals("Result should have 3 terms with term 1 of '4'","2",responses[0].getFacetResult(2).name); assertEquals("Result should have 1st term with count of '1'",1,responses[0].getFacetResult(0).count); assertEquals("Result should have 2nd term with count of '1'",1,responses[0].getFacetResult(1).count); assertEquals("Result should have 3rd term with count of '1'",1,responses[0].getFacetResult(2).count); assertTrue("Result should not be an error", responses[1].hasErrored()); assertEquals("Result should have 0 terms",0,responses[1].getNumberOfFacets()); assertEquals("error message not read from response","IndexMissingException[[bob] missing]",responses[1].getErrorMessage()); }
@Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
@Test public void testCurrentTimeDayAndHour() { String before = getNow(); String s = formatter.getCurrentDayAndHourAndMinute(); String after = getNow(); checkEquals(s,before,after); }
@Override public String getCurrentDayAndHourAndMinute() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String getCurrentDayAndHourAndMinute() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String getCurrentDayAndHourAndMinute() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String getCurrentDayAndHourAndMinute() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String getCurrentDayAndHourAndMinute() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
@Test public void testDateHasCurrentHour() { String s = formatter.parseToDateAndHourAndMinute("2008-02-07"); assertEquals("2008-02-07_00:00", s); }
@Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
@Test public void testDateIsOneDayBehind() { String s = formatter.parseToDateAndHourAndMinute("2008-02-07T09:30:00.000+11:00"); assertEquals("2008-02-06_22:30",s); }
@Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
@Test public void testTimeIsAdapted() { String s = formatter.parseToDateAndHourAndMinute("2008-02-07T09:30:00+09:00"); assertEquals("2008-02-07_00:30",s); }
@Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
@Test public void testTimeWithMillisIsAdapted() { String s = formatter.parseToDateAndHourAndMinute("2008-02-07T09:30:00.000+09:00"); assertEquals("2008-02-07_00:30",s); }
@Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
@Test public void testTimeWithNoSeparatorsIsParsed() { String s = formatter.parseToDateAndHourAndMinute("20080207T093000+0900"); assertEquals("2008-02-07_00:30",s); }
@Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }
@Test public void testCurrentDayReturned() { SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:"); Date d = new Date(); System.out.println(formatter.getCurrentDay()); assertTrue(formatter.getCurrentDay().startsWith(f.format(d))); }
@Override public String getCurrentDay() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); StringBuilderWriter b = new StringBuilderWriter(24); try { formatter.printTo(b,utc); } catch (IOException e) { } return b.toString(); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String getCurrentDay() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); StringBuilderWriter b = new StringBuilderWriter(24); try { formatter.printTo(b,utc); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String getCurrentDay() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); StringBuilderWriter b = new StringBuilderWriter(24); try { formatter.printTo(b,utc); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String getCurrentDay() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); StringBuilderWriter b = new StringBuilderWriter(24); try { formatter.printTo(b,utc); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String getCurrentDay() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); StringBuilderWriter b = new StringBuilderWriter(24); try { formatter.printTo(b,utc); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
@Test public void testParseDatesToUTCTimeGoesBackADay() { assertEquals("2008-02-06T22:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00.000+11:00")); }
@Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
@Test public void testParseDatesToUTCTimeGoesBackInCurrentDay() { assertEquals("2008-02-07T00:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00.000+09:00")); }
@Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
@Test public void testParseDateToUTCTimeGoesBackInCurrentDayWithNoMillis() { assertEquals("2008-02-07T00:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00+09:00")); }
@Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
@Test public void testParseTwoResultsWithOneTimedOut() { FrequentlyRelatedItemSearchResponse[] responses = parser.parse(TWO_RESULTS_ONE_TIMED_OUT); assertEquals("Should only have two results",2,responses.length); assertEquals("Result should have 4 terms",4,responses[0].getNumberOfFacets()); assertEquals("Result should have 3 terms with term 1 of '4'","4",responses[0].getFacetResult(0).name); assertEquals("Result should have 3 terms with term 2 of '4'","15",responses[0].getFacetResult(1).name); assertEquals("Result should have 3 terms with term 3 of '4'","3",responses[0].getFacetResult(2).name); assertEquals("Result should have 3 terms with term 4 of '4'","2",responses[0].getFacetResult(3).name); assertEquals("Result should have 1st term with count of '1'",721,responses[0].getFacetResult(0).count); assertEquals("Result should have 2nd term with count of '1'",163,responses[0].getFacetResult(1).count); assertEquals("Result should have 3rd term with count of '1'",1,responses[0].getFacetResult(2).count); assertEquals("Result should have 3rd term with count of '1'",1,responses[0].getFacetResult(3).count); assertFalse("Result should not be an error", responses[0].hasErrored()); assertTrue("Result should timed out", responses[0].hasTimedOut()); assertFalse("Result should not be an error", responses[1].hasErrored()); assertFalse("Result should timed out", responses[1].hasTimedOut()); assertEquals("Result should have 3 terms with term 1 of '4'","1",responses[1].getFacetResult(0).name); assertEquals("Result should have 3 terms with term 2 of '4'","15",responses[1].getFacetResult(1).name); assertEquals("Result should have 3 terms with term 3 of '4'","3",responses[1].getFacetResult(2).name); assertEquals("Result should have 3 terms with term 4 of '4'","2",responses[1].getFacetResult(3).name); assertEquals("Result should have 1st term with count of '1'",1002,responses[1].getFacetResult(0).count); assertEquals("Result should have 2nd term with count of '1'",1001,responses[1].getFacetResult(1).count); assertEquals("Result should have 3rd term with count of '1'",1,responses[1].getFacetResult(2).count); assertEquals("Result should have 3rd term with count of '1'",1,responses[1].getFacetResult(3).count); }
@Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
@Test public void testParseDateToUTCTimeGoesBackInCurrentDayWithNoSeparators() { assertEquals("2008-02-07T00:30:00.000Z",formatter.formatToUTC("20080207T093000+0900")); }
@Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
@Test public void testParseDateToUTCTimeWithNoTimeZoneIsTakenAsUTC() { assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("20080207T093000+0000")); assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00")); assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00+00:00")); assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00.000+00:00")); assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00+00:00")); }
@Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
@Test public void testParseDateToUTCWithNoTimeInformation() { assertEquals("2008-02-07T00:00:00.000Z",formatter.formatToUTC("2008-02-07")); }
@Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }
@Test public void testCurrentTimeDayAndHour() { String before = getNow(); String s = formatter.getCurrentDayAndHour(); String after = getNow(); checkEquals(s,before,after); }
@Override public String getCurrentDayAndHour() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String getCurrentDayAndHour() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String getCurrentDayAndHour() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String getCurrentDayAndHour() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String getCurrentDayAndHour() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
@Test public void testDateHasCurrentHour() { String s = formatter.parseToDateAndHour("2008-02-07"); assertEquals("2008-02-07_00", s); }
@Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
@Test public void testDateIsOneDayBehind() { String s = formatter.parseToDateAndHour("2008-02-07T09:30:00.000+11:00"); assertEquals("2008-02-06_22",s); }
@Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
@Test public void testTimeIsAdapted() { String s = formatter.parseToDateAndHour("2008-02-07T09:30:00+09:00"); assertEquals("2008-02-07_00",s); }
@Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
@Test public void testTimeWithMillisIsAdapted() { String s = formatter.parseToDateAndHour("2008-02-07T09:30:00.000+09:00"); assertEquals("2008-02-07_00",s); }
@Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
@Test public void testTimeWithNoSeparatorsIsParsed() { String s = formatter.parseToDateAndHour("20080207T093000+0900"); assertEquals("2008-02-07_00",s); }
@Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }
@Test public void testIntegerWidthIsCaught() { assumeTrue(Boolean.parseBoolean(System.getProperty("RunLargeHeapTests","false"))); ResizableByteBuffer buffer = new ResizableByteBufferWithMaxArraySizeChecking(1,Integer.MAX_VALUE); byte[] bigArray = new byte[Integer.MAX_VALUE-8]; try { buffer.append(bigArray); bigArray=null; } catch(BufferOverflowException e) { fail(); } try{ buffer.append(new byte[]{1,2,3,4,5,6,7,8,9,10}); fail("Should overflow"); } catch (BufferOverflowException e) { } }
@Override public void append(byte b) { checkSizeAndGrow(1); appendNoResize(b); }
ResizableByteBufferWithMaxArraySizeChecking implements ResizableByteBuffer { @Override public void append(byte b) { checkSizeAndGrow(1); appendNoResize(b); } }
ResizableByteBufferWithMaxArraySizeChecking implements ResizableByteBuffer { @Override public void append(byte b) { checkSizeAndGrow(1); appendNoResize(b); } ResizableByteBufferWithMaxArraySizeChecking(int initialCapacity, int maxCapacity); }
ResizableByteBufferWithMaxArraySizeChecking implements ResizableByteBuffer { @Override public void append(byte b) { checkSizeAndGrow(1); appendNoResize(b); } ResizableByteBufferWithMaxArraySizeChecking(int initialCapacity, int maxCapacity); @Override int size(); @Override void reset(); @Override byte[] getBuf(); @Override ByteBuffer toByteBuffer(); @Override void append(byte b); @Override void append(byte[] bytes); @Override void append(byte[] b, int off, int len); }
ResizableByteBufferWithMaxArraySizeChecking implements ResizableByteBuffer { @Override public void append(byte b) { checkSizeAndGrow(1); appendNoResize(b); } ResizableByteBufferWithMaxArraySizeChecking(int initialCapacity, int maxCapacity); @Override int size(); @Override void reset(); @Override byte[] getBuf(); @Override ByteBuffer toByteBuffer(); @Override void append(byte b); @Override void append(byte[] bytes); @Override void append(byte[] b, int off, int len); }
@Test public void testParseThreeResultsOneNoTerms() { FrequentlyRelatedItemSearchResponse[] responses = parser.parse(THREE_RESULTS_ONE_NO_RESULTS); assertEquals("Should only have 3 results",3,responses.length); assertEquals("Result should have 2 terms",2,responses[0].getNumberOfFacets()); assertEquals("Result should have 3 terms with term 1 of '4'","4",responses[0].getFacetResult(0).name); assertEquals("Result should have 3 terms with term 2 of '4'","15",responses[0].getFacetResult(1).name); assertEquals("Result should have 1st term with count of '1'",299,responses[0].getFacetResult(0).count); assertEquals("Result should have 2nd term with count of '1'",198,responses[0].getFacetResult(1).count); assertFalse("Result should not be an error", responses[1].hasErrored()); assertFalse("Result should not timed out", responses[1].hasTimedOut()); assertEquals("Result should have 4 terms",4,responses[1].getNumberOfFacets()); assertEquals("Result should have 3 terms with term 1 of '4'","1",responses[1].getFacetResult(0).name); assertEquals("Result should have 3 terms with term 2 of '4'","15",responses[1].getFacetResult(1).name); assertEquals("Result should have 3 terms with term 3 of '4'","3",responses[1].getFacetResult(2).name); assertEquals("Result should have 3 terms with term 4 of '4'","2",responses[1].getFacetResult(3).name); assertEquals("Result should have 1st term with count of '1'",1002,responses[1].getFacetResult(0).count); assertEquals("Result should have 2nd term with count of '1'",1001,responses[1].getFacetResult(1).count); assertEquals("Result should have 3rd term with count of '1'",1,responses[1].getFacetResult(2).count); assertEquals("Result should have 3rd term with count of '1'",1,responses[1].getFacetResult(3).count); assertEquals("Result should have 0 terms",0,responses[2].getNumberOfFacets()); assertFalse("Result should not be an error", responses[2].hasErrored()); assertFalse("Result should not timed out", responses[2].hasTimedOut()); }
@Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
JsonSmartFrequentlyRelatedItemHttpResponseParser implements FrequentlyRelatedItemHttpResponseParser { @Override public FrequentlyRelatedItemSearchResponse[] parse(String json) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(json); Object responses = object.get(RESPONSES_KEY); if(responses==null) return parseError; else { JSONArray responsesArray = (JSONArray)responses; int numberOfResponses = responsesArray.size(); FrequentlyRelatedItemSearchResponse[] results = new FrequentlyRelatedItemSearchResponse[numberOfResponses]; for(int i=0;i<numberOfResponses;i++) { Object response = (responsesArray).get(i); if(response instanceof JSONObject) { results[i] = parseResponseObject((JSONObject)response); } else { results[i] = FrequentlyRelatedItemSearchResponse.JSON_RESPONSE_PARSING_ERROR; } } return results; } } catch (Exception e){ return parseError; } } JsonSmartFrequentlyRelatedItemHttpResponseParser(Configuration configuration); @Override FrequentlyRelatedItemSearchResponse[] parse(String json); }
@Test public void testShutdown() throws Exception { }
@Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticSearchClientFactory.shutdown(); } catch(Exception e) { } }
ElasticSearchRelatedItemIndexingRepository implements RelatedItemStorageRepository { @Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticSearchClientFactory.shutdown(); } catch(Exception e) { } } }
ElasticSearchRelatedItemIndexingRepository implements RelatedItemStorageRepository { @Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticSearchClientFactory.shutdown(); } catch(Exception e) { } } ElasticSearchRelatedItemIndexingRepository(Configuration configuration, ElasticSearchClientFactory factory); }
ElasticSearchRelatedItemIndexingRepository implements RelatedItemStorageRepository { @Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticSearchClientFactory.shutdown(); } catch(Exception e) { } } ElasticSearchRelatedItemIndexingRepository(Configuration configuration, ElasticSearchClientFactory factory); @Override void store(RelatedItemStorageLocationMapper indexLocationMapper, List<RelatedItem> relatedItems); @Override @PreDestroy void shutdown(); }
ElasticSearchRelatedItemIndexingRepository implements RelatedItemStorageRepository { @Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticSearchClientFactory.shutdown(); } catch(Exception e) { } } ElasticSearchRelatedItemIndexingRepository(Configuration configuration, ElasticSearchClientFactory factory); @Override void store(RelatedItemStorageLocationMapper indexLocationMapper, List<RelatedItem> relatedItems); @Override @PreDestroy void shutdown(); }
@Test public void testShutdown() throws Exception { }
@Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticClient.shutdown(); } catch(Exception e) { } }
ElasticSearchRelatedItemHttpIndexingRepository implements RelatedItemStorageRepository { @Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticClient.shutdown(); } catch(Exception e) { } } }
ElasticSearchRelatedItemHttpIndexingRepository implements RelatedItemStorageRepository { @Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticClient.shutdown(); } catch(Exception e) { } } ElasticSearchRelatedItemHttpIndexingRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpIndexingRepository implements RelatedItemStorageRepository { @Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticClient.shutdown(); } catch(Exception e) { } } ElasticSearchRelatedItemHttpIndexingRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override void store(RelatedItemStorageLocationMapper indexLocationMapper, List<RelatedItem> relatedItems); @Override @PreDestroy void shutdown(); }
ElasticSearchRelatedItemHttpIndexingRepository implements RelatedItemStorageRepository { @Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticClient.shutdown(); } catch(Exception e) { } } ElasticSearchRelatedItemHttpIndexingRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override void store(RelatedItemStorageLocationMapper indexLocationMapper, List<RelatedItem> relatedItems); @Override @PreDestroy void shutdown(); }
@Test public void testEmptyDateReturnsToday() { RelatedItem product = new RelatedItem("1".toCharArray(),null,null,new RelatedItemAdditionalProperties()); String name = cachingDayBasedMapper.getLocationName(product); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd"); assertEquals(cachingDayConfig.getStorageIndexNamePrefix() + "-" + today.format(new Date()),name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
@Test public void testSetDateReturnsIndexNameWithGivenDate() { Date now = new Date(); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); SimpleDateFormat todayDate = new SimpleDateFormat("yyyy-MM-dd"); RelatedItem product = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); try { Thread.sleep(2000); } catch(Exception e) { } RelatedItem product2 = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); String name = cachingDayBasedMapper.getLocationName(product); String name2 = cachingDayBasedMapper.getLocationName(product2); assertEquals(cachingDayConfig.getStorageIndexNamePrefix() + "-" + todayDate.format(new Date()),name); assertEquals(cachingDayConfig.getStorageIndexNamePrefix() + "-" + todayDate.format(new Date()),name2); product = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); try { Thread.sleep(2000); } catch(Exception e) { } product2 = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); name = nonCachingDayBasedMapper.getLocationName(product); name2 = nonCachingDayBasedMapper.getLocationName(product2); assertEquals(noncachingDayConfig.getStorageIndexNamePrefix() + "-" + todayDate.format(new Date()),name); assertEquals(noncachingDayConfig.getStorageIndexNamePrefix() + "-" + todayDate.format(new Date()),name2); RelatedItem product3 = new RelatedItem("1".toCharArray(),"1920-01-02T23:59:59+00:00",null,new RelatedItemAdditionalProperties()); name = nonCachingDayBasedMapper.getLocationName(product3); assertEquals(noncachingDayConfig.getStorageIndexNamePrefix() + "-1920-01-02",name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
@Test public void testTimeZoneDate() { RelatedItem product = new RelatedItem("1".toCharArray(),"1920-01-02T01:59:59+02:00",null,new RelatedItemAdditionalProperties()); String name = nonCachingDayBasedMapper.getLocationName(product); assertEquals(noncachingDayConfig.getStorageIndexNamePrefix() + "-1920-01-01",name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
@Test public void testCacheDoesNotGrowOverMaxCached() { RelatedItem product1 = new RelatedItem("1".toCharArray(),"1920-01-03T01:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product2 = new RelatedItem("1".toCharArray(),"1920-01-04T02:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product3 = new RelatedItem("1".toCharArray(),"1920-01-05T03:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product4 = new RelatedItem("1".toCharArray(),"1920-01-06T04:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product5 = new RelatedItem("1".toCharArray(),"1920-01-07T05:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product6 = new RelatedItem("1".toCharArray(),"1920-01-08T06:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product7 = new RelatedItem("1".toCharArray(),"1920-01-09T07:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product8 = new RelatedItem("1".toCharArray(),"1920-01-10T01:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product9 = new RelatedItem("1".toCharArray(),"1920-01-11T01:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product10 = new RelatedItem("1".toCharArray(),"1920-01-12T01:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product11 = new RelatedItem("1".toCharArray(),"1920-01-13T01:59:59+00:00",null,new RelatedItemAdditionalProperties()); RelatedItem product12 = new RelatedItem("1".toCharArray(),"1920-01-14T01:59:59+00:00",null,new RelatedItemAdditionalProperties()); String name = cachingDayBasedMapper.getLocationName(product1); name = cachingDayBasedMapper.getLocationName(product2); name = cachingDayBasedMapper.getLocationName(product3); name = cachingDayBasedMapper.getLocationName(product4); name = cachingDayBasedMapper.getLocationName(product5); name = cachingDayBasedMapper.getLocationName(product6); name = cachingDayBasedMapper.getLocationName(product7); name = cachingDayBasedMapper.getLocationName(product8); name = cachingDayBasedMapper.getLocationName(product9); name = cachingDayBasedMapper.getLocationName(product10); name = cachingDayBasedMapper.getLocationName(product11); name = cachingDayBasedMapper.getLocationName(product12); try { Field cache = null; cache = DayBasedStorageLocationMapper.class.getDeclaredField("dayCache"); cache.setAccessible(true); ConcurrentMap m = (ConcurrentMap) cache.get(cachingDayBasedMapper); assertEquals(10, m.size()); } catch (NoSuchFieldException e) { fail(); } catch (IllegalAccessException e) { fail(); } assertEquals(cachingDayConfig.getStorageIndexNamePrefix() + "-1920-01-14",name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
DayBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDay(); } else { date = currentDayFormatter.parseToDate(dateStr); } if(dateCachingEnabled) { String cachedIndexName = dayCache.get(date); if(cachedIndexName==null) { StringBuilder indexName = new StringBuilder(indexNameSize); String theIndexName = indexName.append(this.indexPrefixName).append(date).toString(); String previous = dayCache.putIfAbsent(date,theIndexName); if(previous!=null) { return previous; } else { return theIndexName; } } else { return cachedIndexName; } } else { StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } } DayBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
@Test public void testEmptyDateReturnsToday() { RelatedItem product = new RelatedItem("1".toCharArray(),null,null,new RelatedItemAdditionalProperties()); String name = hourBasedMapper.getLocationName(product); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd_HH"); assertEquals(config.getStorageIndexNamePrefix() + "-" + today.format(new Date()),name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
@Test public void testSetDateReturnsIndexNameWithGivenDate() { Date now = new Date(); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); SimpleDateFormat todayDate = new SimpleDateFormat("yyyy-MM-dd'_'HH"); RelatedItem product = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); try { Thread.sleep(2000); } catch(Exception e) { } RelatedItem product2 = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); String name = hourBasedMapper.getLocationName(product); String name2 = hourBasedMapper.getLocationName(product2); assertEquals(config.getStorageIndexNamePrefix() + "-" + todayDate.format(new Date()),name); assertEquals(config.getStorageIndexNamePrefix() + "-" + todayDate.format(new Date()),name2); RelatedItem product3 = new RelatedItem("1".toCharArray(),"1920-01-02T23:59:59+00:00",null,new RelatedItemAdditionalProperties()); name = hourBasedMapper.getLocationName(product3); assertEquals(config.getStorageIndexNamePrefix() + "-1920-01-02_23",name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
@Test public void testTimeZoneDate() { RelatedItem product = new RelatedItem("1".toCharArray(),"1920-01-02T01:59:59+02:00",null,new RelatedItemAdditionalProperties()); String name = hourBasedMapper.getLocationName(product); assertEquals(config.getStorageIndexNamePrefix() + "-1920-01-01_23",name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
@Test public void testEmptyDateReturnsToday() { RelatedItem product = new RelatedItem("1".toCharArray(),null,null,new RelatedItemAdditionalProperties()); String name = minBasedMapper.getLocationName(product); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd_HH':'mm"); assertEquals(config.getStorageIndexNamePrefix() + "-" + today.format(new Date()),name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
@Test public void parseFoundTwoSources() { Map<String,String> parsedDoc = ElasticSearchRelatedItemHttpGetRepository.processResults(FOUND_TWO); assertTrue(parsedDoc.size()==2); assertTrue(parsedDoc.containsKey("1")); assertTrue(parsedDoc.containsKey("2")); assertTrue(parsedDoc.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); assertTrue(parsedDoc.get("2").contains("71a5120bdf4d998c2b043a681b1bd211")); }
public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void testSetDateReturnsIndexNameWithGivenDate() { Date now = new Date(); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); SimpleDateFormat todayDate = new SimpleDateFormat("yyyy-MM-dd'_'HH':'mm"); RelatedItem product = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); try { Thread.sleep(2000); } catch(Exception e) { } RelatedItem product2 = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); String name = minBasedMapper.getLocationName(product); String name2 = minBasedMapper.getLocationName(product2); assertEquals(config.getStorageIndexNamePrefix() + "-" + todayDate.format(now), name); assertEquals(config.getStorageIndexNamePrefix() + "-" + todayDate.format(now),name2); RelatedItem product3 = new RelatedItem("1".toCharArray(),"1920-01-02T23:59:59+00:00",null,new RelatedItemAdditionalProperties()); name = minBasedMapper.getLocationName(product3); assertEquals(config.getStorageIndexNamePrefix() + "-1920-01-02_23:59",name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }