src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
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 testCreateSearchObject() throws Exception { assertNotNull(factory.createSearchObject()); }
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 testNewInstance() throws Exception { assertNotNull(factory.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 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)); }
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 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")); } @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")); } @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"); } }
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 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("{}")); } @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")); } @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")); } @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")); } @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")); } @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")); } @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")); } @Test public void testHttpParseFoundTwoSources() { 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("71a5120bdf4d998c2b043a681b1bd211")); }
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 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]); }
RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); @Override RelatedItemIndexingMessage newInstance(); }
@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()); } @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()); } @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()); }
RelatedItemReferenceMessageFactory implements EventFactory<RelatedItemReference> { @Override public RelatedItemReference newInstance() { return new RelatedItemReference(); } RelatedItemReferenceMessageFactory(); @Override RelatedItemReference newInstance(); }
@Test public void testCanCreateReferenceObject() { EventFactory<RelatedItemReference> factory = new RelatedItemReferenceMessageFactory(); assertNotNull(factory.newInstance()); assertTrue(factory.newInstance() instanceof RelatedItemReference); }
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 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); } @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()); } @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(); } } @Test public void testConnectionException() { HttpResult httpResult = AHCRequestExecutor.executeSearch(client, HttpMethod.GET,"http: assertTrue(httpResult.getStatus()== HttpSearchExecutionStatus.CONNECTION_FAILURE); }
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 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")); } @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")); } @Test public void parseFoundOneAndOneWithError() { Map<String,String> parsedDoc = ElasticSearchRelatedItemHttpGetRepository.processResults(FOUND_ONE_ONE_WITH_ERROR); assertTrue(parsedDoc.size()==1); assertTrue(parsedDoc.containsKey("1")); assertTrue(parsedDoc.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); }
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 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))); } @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))); }
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 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()); } @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()); } @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()); }
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 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(); } } @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()); } }
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 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()); } @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()); } @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); } } @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()); } @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()); }
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 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)); } @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)); } @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)); }
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 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()); } @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); } @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()); } @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); } @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()); }
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 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)); }
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 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)); }
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 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); } @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); }
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 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()); }
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 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()); }
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 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(); } @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(); } @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(); } @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)); }
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 testGetHandlerReturnsDefaultMapping() throws Exception { SearchResponseContextHandler h = defaultLookup.getHandler(Long.class); assertSame(DebugSearchResponseContextHandler.INSTANCE,h); } @Test public void testDefaultHandlerReturnedForCustomLookup() { assertSame(mockHandler1, customMappingsLookup.getHandler(Long.class)); assertSame(mockHandler2,customMappingsLookup.getHandler(String.class)); assertSame(DebugSearchResponseContextHandler.INSTANCE,customMappingsLookup.getHandler(AsyncContext.class)); } @Test public void testDefaultMappings() { assertTrue(defaultLookup.getHandler(AsyncContext.class) instanceof SearchResponseContextHandler); assertSame(DebugSearchResponseContextHandler.INSTANCE,defaultLookup.getHandler(LogDebuggingSearchResponseContext.class)); }
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 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(); } @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(); } @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(); }
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 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); }
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 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()); } @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"); } }
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 testCurrentTimeDayAndHour() { String before = getNow(); String s = formatter.getCurrentDayAndHourAndMinute(); String after = getNow(); checkEquals(s,before,after); }
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 testDateHasCurrentHour() { String s = formatter.parseToDateAndHourAndMinute("2008-02-07"); assertEquals("2008-02-07_00:00", s); } @Test public void testDateIsOneDayBehind() { String s = formatter.parseToDateAndHourAndMinute("2008-02-07T09:30:00.000+11:00"); assertEquals("2008-02-06_22:30",s); } @Test public void testTimeIsAdapted() { String s = formatter.parseToDateAndHourAndMinute("2008-02-07T09:30:00+09:00"); assertEquals("2008-02-07_00:30",s); } @Test public void testTimeWithMillisIsAdapted() { String s = formatter.parseToDateAndHourAndMinute("2008-02-07T09:30:00.000+09:00"); assertEquals("2008-02-07_00:30",s); } @Test public void testTimeWithNoSeparatorsIsParsed() { String s = formatter.parseToDateAndHourAndMinute("20080207T093000+0900"); assertEquals("2008-02-07_00:30",s); }
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 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))); }
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 testParseDatesToUTCTimeGoesBackADay() { assertEquals("2008-02-06T22:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00.000+11:00")); } @Test public void testParseDatesToUTCTimeGoesBackInCurrentDay() { assertEquals("2008-02-07T00:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00.000+09:00")); } @Test public void testParseDateToUTCTimeGoesBackInCurrentDayWithNoMillis() { assertEquals("2008-02-07T00:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00+09:00")); } @Test public void testParseDateToUTCTimeGoesBackInCurrentDayWithNoSeparators() { assertEquals("2008-02-07T00:30:00.000Z",formatter.formatToUTC("20080207T093000+0900")); } @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")); } @Test public void testParseDateToUTCWithNoTimeInformation() { assertEquals("2008-02-07T00:00:00.000Z",formatter.formatToUTC("2008-02-07")); }
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 testCurrentTimeDayAndHour() { String before = getNow(); String s = formatter.getCurrentDayAndHour(); String after = getNow(); checkEquals(s,before,after); }
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 testDateHasCurrentHour() { String s = formatter.parseToDateAndHour("2008-02-07"); assertEquals("2008-02-07_00", s); } @Test public void testDateIsOneDayBehind() { String s = formatter.parseToDateAndHour("2008-02-07T09:30:00.000+11:00"); assertEquals("2008-02-06_22",s); } @Test public void testTimeIsAdapted() { String s = formatter.parseToDateAndHour("2008-02-07T09:30:00+09:00"); assertEquals("2008-02-07_00",s); } @Test public void testTimeWithMillisIsAdapted() { String s = formatter.parseToDateAndHour("2008-02-07T09:30:00.000+09:00"); assertEquals("2008-02-07_00",s); } @Test public void testTimeWithNoSeparatorsIsParsed() { String s = formatter.parseToDateAndHour("20080207T093000+0900"); assertEquals("2008-02-07_00",s); }
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 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) { } }
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 { }
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 testShutdown() throws Exception { }
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 = cachingDayBasedMapper.getLocationName(product); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd"); assertEquals(cachingDayConfig.getStorageIndexNamePrefix() + "-" + today.format(new Date()),name); } @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); } @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); } @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); }
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 = hourBasedMapper.getLocationName(product); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd_HH"); assertEquals(config.getStorageIndexNamePrefix() + "-" + today.format(new Date()),name); } @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); } @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); }
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 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); } @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); } @Test public void testTimeZoneDate() { RelatedItem product = new RelatedItem("1".toCharArray(),"1920-01-02T01:59:59+02:00",null,new RelatedItemAdditionalProperties()); String name = minBasedMapper.getLocationName(product); assertEquals(config.getStorageIndexNamePrefix() + "-1920-01-01_23:59",name); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testSendingOneItem() { try { handler.onEvent(getMessage(),1,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(1,repo.getNumberOfProductsSentForStoring()); } @Test public void testSendingManyItemsButBelowBatchSize() { try { for(int i=0;i<7;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),8,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(8,repo.getNumberOfProductsSentForStoring()); } @Test public void testSendingManyItemsExceedingBatchSize() { try { for(int i=0;i<25;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),26,true); } catch(Exception e) { fail(); } assertEquals(2,repo.getNumberOfCalls()); assertEquals(26,repo.getNumberOfProductsSentForStoring()); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { public void shutdown() { try { storageRepository.shutdown(); } catch(Exception e) { log.error("Problem shutting down storage repository"); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testShutdownIsCalledOnStorageRepo() { handler.shutdown(); assertTrue(repo.isShutdown()); }
BatchingRelatedItemReferenceEventHanderFactory implements RelatedItemReferenceEventHandlerFactory { @Override public RelatedItemReferenceEventHandler getHandler() { return new BatchingRelatedItemReferenceEventHandler(configuration.getIndexBatchSize(),repository.getRepository(configuration),locationMapper); } BatchingRelatedItemReferenceEventHanderFactory(Configuration config, RelatedItemStorageRepositoryFactory repository, RelatedItemStorageLocationMapper locationMapper); @Override RelatedItemReferenceEventHandler getHandler(); }
@Test public void testFactoryCreatesNewBatchingRelatedItemReferenceEventHander() { BatchingRelatedItemReferenceEventHanderFactory factory = new BatchingRelatedItemReferenceEventHanderFactory(new SystemPropertiesConfiguration(),repo,null); assertNotSame(factory.getHandler(),factory.getHandler()); assertEquals(2,repo.getInvocationCount()); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testSendingOneItem() { CountDownLatch latch = new CountDownLatch(3); repo.handlers.get(0).setEndOfBatchCountDownLatch(latch); repo.handlers.get(1).setEndOfBatchCountDownLatch(latch); try { handler.onEvent(getMessage(),1,true); } catch(Exception e) { fail(); } try { boolean countedDown = latch.await(5000, TimeUnit.MILLISECONDS); assertTrue("Storage Repository not called in required time",countedDown); } catch (InterruptedException e) { fail("Timed out waiting for messages to be sent through the ring buffer"); e.printStackTrace(); } assertEquals(3,(repo.handlers.get(0).getNumberOfCalls()+repo.handlers.get(1).getNumberOfCalls())); assertEquals(1,(repo.handlers.get(0).getNumberOfEndOfBatchCalls()+repo.handlers.get(1).getNumberOfEndOfBatchCalls())); } @Test public void testSendingManyItemsButBelowBatchSize() { CountDownLatch latch = new CountDownLatch(24); repo.handlers.get(0).setEndOfBatchCountDownLatch(latch); repo.handlers.get(1).setEndOfBatchCountDownLatch(latch); try { for(int i=0;i<7;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),8,true); } catch(Exception e) { fail(); } try { boolean countedDown = latch.await(10000, TimeUnit.MILLISECONDS); assertTrue("Storage Repository not called in required time",countedDown); } catch (InterruptedException e) { fail("Timed out waiting for messages to be sent through the ring buffer"); e.printStackTrace(); } assertEquals(24,repo.handlers.get(0).getNumberOfCalls()); assertEquals(1,repo.handlers.get(0).getNumberOfEndOfBatchCalls()); } @Test public void testSendingManyItemsExceedingBatchSize() { CountDownLatch latch = new CountDownLatch(78); repo.handlers.get(0).setEndOfBatchCountDownLatch(latch); repo.handlers.get(1).setEndOfBatchCountDownLatch(latch); try { for(int i=0;i<25;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),26,true); } catch(Exception e) { fail(); } try { boolean countedDown = latch.await(10000, TimeUnit.MILLISECONDS); assertTrue("Storage Repository not called in required time",countedDown); } catch (InterruptedException e) { fail("Timed out waiting for messages to be sent through the ring buffer"); e.printStackTrace(); } assertEquals(51,repo.handlers.get(0).getNumberOfCalls()); assertTrue(repo.handlers.get(0).getNumberOfEndOfBatchCalls()>0); assertEquals(27,repo.handlers.get(1).getNumberOfCalls()); assertTrue(repo.handlers.get(1).getNumberOfEndOfBatchCalls()>0); } @Test public void checkNoCallMadeForInvalidMessage() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(false); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.handlers.get(0).getNumberOfCalls()); } @Test public void checkNoCallMadeForMessageWithNoProducts() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(true); message.getRelatedItems().setNumberOfRelatedItems(0); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.handlers.get(0).getNumberOfCalls()); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { public void shutdown() { if(!shutdown) { shutdown=true; for(RelatedItemReferenceEventHandler handler : handlers) { try { handler.shutdown(); } catch(Exception e) { log.error("Issue terminating handler",e); } } for(ExecutorService executorService : executors) { try { executorService.shutdownNow(); } catch(Exception e) { log.error("Problem during shutdown terminating the executorservice",e); } } for(Disruptor disruptor : disruptors) { try { disruptor.shutdown(); } catch(Exception e) { log.error("Problem during shutdown of the disruptor",e); } } } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testShutdownIsCalledOnStorageRepo() { handler.shutdown(); assertTrue(repo.handlers.get(0).isShutdown()); assertTrue(repo.handlers.get(1).isShutdown()); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
@Test public void testSendingOneItem() { try { handler.onEvent(getMessage(),1,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(3,repo.getNumberOfProductsSentForStoring()); } @Test public void testSendingManyItemsButBelowBatchSize() { try { for(int i=0;i<7;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),8,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(24,repo.getNumberOfProductsSentForStoring()); } @Test public void testSendingManyItemsExceedingBatchSize() { try { for(int i=0;i<25;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),26,true); } catch(Exception e) { fail(); } assertEquals(3,repo.getNumberOfCalls()); assertEquals(78,repo.getNumberOfProductsSentForStoring()); } @Test public void checkNoCallMadeForInvalidMessage() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(false); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.getNumberOfCalls()); assertEquals(0,repo.getNumberOfProductsSentForStoring()); } @Test public void checkNoCallMadeForMessageWithNoProducts() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(true); message.getRelatedItems().setNumberOfRelatedItems(0); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.getNumberOfCalls()); assertEquals(0,repo.getNumberOfProductsSentForStoring()); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void shutdown() { if(!shutdown) { shutdown = true; try { storageRepository.shutdown(); } catch(Exception e) { log.warn("Unable to shutdown respository client"); } } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
@Test public void testShutdownIsCalledOnStorageRepo() { handler.shutdown(); assertTrue(repo.isShutdown()); }
TotalResult { @NonNull public List<CheckInfo> getList() { return mList; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); @NonNull List<CheckInfo> getList(); @CheckingState int getCheckState(); }
@Test public void getList() throws Exception { assertEquals(totalResult.getList().size(), 0); }
TotalResult { @CheckingState public int getCheckState() { return mCheckState; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); @NonNull List<CheckInfo> getList(); @CheckingState int getCheckState(); }
@Test public void getCheckState() throws Exception { assertEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_CHECKED_ROOT_NOT_DETECTED); assertNotEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_CHECKED_ERROR); assertNotEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_CHECKED_ROOT_DETECTED); assertNotEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_STILL_GOING); assertNotEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_UNCHECKED); }
CheckInfo { @CheckingMethodType public int getTypeCheck() { return mTypeCheck; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); @Nullable Boolean getState(); void setState(@Nullable Boolean state); @CheckingMethodType int getTypeCheck(); void setTypeCheck(int typeCheck); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void getTypeCheck() throws Exception { checkInfo.setTypeCheck(CH_TYPE_HOOKS); assertEquals(checkInfo.getTypeCheck(), CH_TYPE_HOOKS); }
CheckInfo { @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CheckInfo)) return false; CheckInfo checkInfo = (CheckInfo) o; if (mTypeCheck != checkInfo.mTypeCheck) return false; return mState != null ? mState.equals(checkInfo.mState) : checkInfo.mState == null; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); @Nullable Boolean getState(); void setState(@Nullable Boolean state); @CheckingMethodType int getTypeCheck(); void setTypeCheck(int typeCheck); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void equalsTest() throws Exception { checkInfo.setState(null); assertThat(checkInfo.equals(checkInfo), is(true)); assertThat(checkInfo.equals(this), is(false)); assertThat(checkInfo.equals(null), is(false)); checkInfo.setTypeCheck(GeneralConst.CH_TYPE_UNKNOWN); assertThat(checkInfo.equals(new CheckInfo(null, GeneralConst.CH_TYPE_UNKNOWN)), is(true)); assertThat(checkInfo.equals(new CheckInfo(null, GeneralConst.CH_TYPE_NON_RELEASE_KEYS)), is(false)); assertThat(checkInfo.equals(new CheckInfo(true, GeneralConst.CH_TYPE_UNKNOWN)), is(false)); }
CheckInfo { @Override public int hashCode() { int result = mState != null ? mState.hashCode() : 0; result = 31 * result + mTypeCheck; return result; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); @Nullable Boolean getState(); void setState(@Nullable Boolean state); @CheckingMethodType int getTypeCheck(); void setTypeCheck(int typeCheck); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void hashCodeTest() throws Exception { checkInfo.setState(true); checkInfo.setTypeCheck(CH_TYPE_DEV_KEYS); CheckInfo chInfo = new CheckInfo(true,CH_TYPE_DEV_KEYS); assertEquals(checkInfo.hashCode(), chInfo.hashCode()); chInfo.setTypeCheck(CH_TYPE_HOOKS); assertNotEquals(checkInfo.hashCode(), chInfo.hashCode()); chInfo.setState(null); checkInfo.setState(null); checkInfo.setTypeCheck(CH_TYPE_HOOKS); assertEquals(checkInfo.hashCode(), chInfo.hashCode()); }
ChecksHelper { @StringRes public static int getCheckStringId(@CheckingMethodType int typeCheck) { @StringRes int result = 0; switch (typeCheck) { case CH_TYPE_TEST_KEYS: result = R.string.checks_desc_1; break; case CH_TYPE_DEV_KEYS: result = R.string.checks_desc_2; break; case CH_TYPE_NON_RELEASE_KEYS: result = R.string.checks_desc_3; break; case CH_TYPE_DANGEROUS_PROPS: result = R.string.checks_desc_4; break; case CH_TYPE_PERMISSIVE_SELINUX: result = R.string.checks_desc_5; break; case CH_TYPE_SU_EXISTS: result = R.string.checks_desc_6; break; case CH_TYPE_SUPER_USER_APK: result = R.string.checks_desc_7; break; case CH_TYPE_SU_BINARY: result = R.string.checks_desc_8; break; case CH_TYPE_BUSYBOX_BINARY: result = R.string.checks_desc_9; break; case CH_TYPE_XPOSED: result = R.string.checks_desc_10; break; case CH_TYPE_RESETPROP: result = R.string.checks_desc_11; break; case CH_TYPE_WRONG_PATH_PERMITION: result = R.string.checks_desc_12; break; case CH_TYPE_HOOKS: result = R.string.checks_desc_13; break; case CH_TYPE_UNKNOWN: default: result = R.string.empty; } return result; } private ChecksHelper(); @StringRes static int getCheckStringId(@CheckingMethodType int typeCheck); static Bitmap getNonCheck(@NonNull Context pContext); static Bitmap getFound(@NonNull Context pContext); static Bitmap getOk(@NonNull Context pContext); }
@Test public void getCheckStringIdTest() throws Exception { assertThat(getCheckStringId(CH_TYPE_TEST_KEYS), is(R.string.checks_desc_1)); assertThat(getCheckStringId(CH_TYPE_DEV_KEYS), is(R.string.checks_desc_2)); assertThat(getCheckStringId(CH_TYPE_NON_RELEASE_KEYS), is(R.string.checks_desc_3)); assertThat(getCheckStringId(CH_TYPE_DANGEROUS_PROPS), is(R.string.checks_desc_4)); assertThat(getCheckStringId(CH_TYPE_PERMISSIVE_SELINUX), is(R.string.checks_desc_5)); assertThat(getCheckStringId(CH_TYPE_SU_EXISTS), is(R.string.checks_desc_6)); assertThat(getCheckStringId(CH_TYPE_SUPER_USER_APK), is(R.string.checks_desc_7)); assertThat(getCheckStringId(CH_TYPE_SU_BINARY), is(R.string.checks_desc_8)); assertThat(getCheckStringId(CH_TYPE_BUSYBOX_BINARY), is(R.string.checks_desc_9)); assertThat(getCheckStringId(CH_TYPE_XPOSED), is(R.string.checks_desc_10)); assertThat(getCheckStringId(CH_TYPE_RESETPROP), is(R.string.checks_desc_11)); assertThat(getCheckStringId(CH_TYPE_WRONG_PATH_PERMITION), is(R.string.checks_desc_12)); assertThat(getCheckStringId(CH_TYPE_HOOKS), is(R.string.checks_desc_13)); assertThat(getCheckStringId(CH_TYPE_UNKNOWN), is(R.string.empty)); assertEquals(getCheckStringId(CH_TYPE_UNKNOWN), R.string.empty); assertThat(getCheckStringId(Integer.MAX_VALUE), is(R.string.empty)); }
GmsSecurityException extends SecurityException { public String getPath() { return path; } GmsSecurityException(final String path); GmsSecurityException(final String path, final String message); GmsSecurityException(final String path, final String message, final Throwable throwable); String getPath(); static final String DEFAULT_MESSAGE; }
@Test public void getPath() { testPath = "/sample34"; GmsSecurityException e = new GmsSecurityException("somePath"); ReflectionTestUtils.setField(e, "path", testPath); assertEquals(testPath, e.getPath()); }
DAOProvider { public BAuthorizationDAO getBAuthorizationDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBAuthorizationDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } @Autowired DAOProvider(final QueryService queryService); BAuthorizationDAO getBAuthorizationDAO(); BPermissionDAO getBPermissionDAO(); }
@Test public void getBAuthorizationDAOThrowNullPointer() { daoProvider = new DAOProvider(queryService); ReflectionTestUtils.setField(daoProvider, URL, URL_VALUE_UNKNOWN); boolean threwException = false; try { Assert.assertNotNull(daoProvider.getBAuthorizationDAO()); } catch (NullPointerException e) { threwException = true; } if (!threwException) { Assert.fail(URL_VALUE_UNKNOWN_MESSAGE); } } @Test public void getBAuthorizationDAOOK() { daoProvider = new DAOProvider(queryService); ReflectionTestUtils.setField(daoProvider, URL, URL_VALUE); Assert.assertNotNull(daoProvider.getBAuthorizationDAO()); }
DAOProvider { public BPermissionDAO getBPermissionDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBPermissionDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } @Autowired DAOProvider(final QueryService queryService); BAuthorizationDAO getBAuthorizationDAO(); BPermissionDAO getBPermissionDAO(); }
@Test public void getBPermissionDAOOKThrowNullPointer() { daoProvider = new DAOProvider(queryService); ReflectionTestUtils.setField(daoProvider, URL, URL_VALUE_UNKNOWN); boolean threwException = false; try { Assert.assertNotNull(daoProvider.getBPermissionDAO()); } catch (NullPointerException e) { threwException = true; } if (!threwException) { Assert.fail(URL_VALUE_UNKNOWN_MESSAGE); } } @Test public void getBPermissionDAOOK() { daoProvider = new DAOProvider(queryService); ReflectionTestUtils.setField(daoProvider, URL, URL_VALUE); Assert.assertNotNull(daoProvider.getBPermissionDAO()); }
ConfigurationService { public boolean isApplicationConfigured() { return configurationRepository.count() > 0; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void configurationExist() { assertTrue(configurationService.isApplicationConfigured() && configurationRepository.count() > 0); }
ConfigurationService { public boolean isDefaultConfigurationCreated() { BConfiguration isMultiEntity = new BConfiguration( ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER.toString(), String.valueOf(dc.getIsMultiEntity()) ); BConfiguration isUserRegistrationAllowed = new BConfiguration( String.valueOf(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER), String.valueOf(dc.getIsUserRegistrationAllowed()) ); configurationRepository.save(isMultiEntity); configurationRepository.save(isUserRegistrationAllowed); multiEntity = Boolean.parseBoolean(isMultiEntity.getValue()); userRegistrationAllowed = Boolean.parseBoolean(isUserRegistrationAllowed.getValue()); return true; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void createDefaultConfig() { configurationRepository.deleteAll(); boolean ok = configurationService.isDefaultConfigurationCreated(); assertTrue("Create default config failed", ok); String msg = "Default configuration was not created"; BConfiguration c = configurationRepository.findFirstByKey(keyMultiEntityApp); assertNotNull(msg, c); c = configurationRepository.findFirstByKey(keyUserRegistrationAllowed); assertNotNull(msg, c); }
ConfigurationService { public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void assignDefaultUserToEntityWithRole() { final String msg = "Assign default user to entity with role failed"; final boolean ok = configurationService.isDefaultUserAssignedToEntityWithRole(); assertTrue(msg, ok); final EUser u = userRepository.findFirstByUsername(dc.getUserAdminDefaultUsername()); final EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); assertNotNull(u); assertNotNull(e); final List<BRole> roles = authRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertTrue(msg, roles != null && !roles.isEmpty()); } @Transactional @Test public void assignDefaultUserToEntityWithRoleDefaultUserNotFound() { EUser defaultUser = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); authRepository.delete(authRepository.findFirstByUserAndEntityNotNullAndRoleEnabled(defaultUser, true)); userRepository.delete(defaultUser); assertFalse(configurationService.isDefaultUserAssignedToEntityWithRole()); }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void getConfig() { String key; String value; List<String> keys = new LinkedList<>(); List<String> values = new LinkedList<>(); final int top = 10; for (int i = 0; i < top; i++) { key = random.nextString() + "_IN_SERVER"; value = random.nextString(); keys.add(key); values.add(value); assertNotNull(configurationRepository.save(new BConfiguration(key, value))); } Map<String, String> configs = configurationService.getConfig(); Object config; for (int i = 0; i < keys.size(); i++) { config = configs.get(keys.get(i)); assertNotNull("Configuration found if null", config); value = values.get(i); assertEquals("Configuration value returned by server (" + config + ") does not match the expected", config, value); } } @Test public void getConfigInServerNotFound() { boolean success = false; try { configurationService.getConfig(random.nextString() + ConfigurationService.IN_SERVER); } catch (NotFoundEntityException e) { assertEquals(ConfigurationService.CONFIG_NOT_FOUND, e.getMessage()); success = true; } assertTrue(success); } @Test public void getConfigNotFound() { boolean success = false; try { configurationService.getConfig(random.nextString().replace(ConfigurationService.IN_SERVER, "")); } catch (NotFoundEntityException e) { assertEquals(ConfigurationService.CONFIG_NOT_FOUND, e.getMessage()); success = true; } assertTrue(success); }
ConfigurationService { public Map<String, Object> getConfigByUser(final long userId) { final List<BConfiguration> configs = configurationRepository.findAllByUserId(userId); Map<String, Object> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void getConfigByUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BConfiguration c = configurationRepository.save(new BConfiguration(keyLang, "es", u.getId())); assertNotNull(c); BConfiguration c2 = configurationRepository.save( new BConfiguration(keyLastAccessedEntity, String.valueOf(e.getId()), u.getId()) ); assertNotNull(c2); Map<String, Object> configs = configurationService.getConfigByUser(u.getId()); assertNotNull(configs.get(keyLang)); assertNotNull(configs.get(keyLastAccessedEntity)); assertEquals("Configuration values (language) do not match", "es", configs.get(keyLang)); assertEquals("Configuration values (last accessed entity) do not match", configs.get(keyLastAccessedEntity), String.valueOf(e.getId())); }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void saveConfig() { List<Iterable<BConfiguration>> list = deleteAllServerConfig(); Map<String, Object> configs = new HashMap<>(); configs.put(keyUserRegistrationAllowed, false); configs.put(keyMultiEntityApp, true); try { configurationService.saveConfig(configs); BConfiguration cR = configurationRepository.findFirstByKey(keyUserRegistrationAllowed); assertNotNull(cR); assertEquals(Boolean.toString(false), cR.getValue()); cR = configurationRepository.findFirstByKey(keyMultiEntityApp); assertNotNull(cR); assertEquals(Boolean.toString(true), cR.getValue()); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("At least one of the keys was not found."); } catch (GmsGeneralException e) { LOGGER.error(e.getLocalizedMessage()); fail("The provided user key was not valid"); } assertTrue(hasRestoredAllServerConfig(list)); } @Test public void saveConfigForUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(u); Map<String, Object> configs = new HashMap<>(); configs.put(keyLang, "fr"); configs.put(keyLastAccessedEntity, e.getId()); try { configurationService.saveConfig(configs, u.getId()); } catch (NotFoundEntityException e1) { LOGGER.error(e1.getLocalizedMessage()); fail("At least one of the keys was not found."); } } @Test public void saveConfigKeyNotFound() { Map<String, Object> configs = new HashMap<>(); configs.put(random.nextString(), random.nextString()); boolean success = false; try { configurationService.saveConfig(configs); } catch (GmsGeneralException e) { LOGGER.error(e.getLocalizedMessage()); fail("There was not provided user and the test still failed because of it"); } catch (Exception e) { success = true; } assertTrue(success); }
ConfigurationService { public void setUserRegistrationAllowed(final boolean userRegistrationAllowed) { insertOrUpdateValue(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER, userRegistrationAllowed); this.userRegistrationAllowed = userRegistrationAllowed; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void setUserRegistrationAllowed() { final List<Iterable<BConfiguration>> list = deleteAllServerConfig(); configurationService.setUserRegistrationAllowed(true); BConfiguration c = configurationRepository.findFirstByKey(keyUserRegistrationAllowed); assertNotNull(c); assertEquals(Boolean.toString(true), c.getValue()); final Object allowed = ReflectionTestUtils.getField(configurationService, "userRegistrationAllowed"); assertNotNull(allowed); assertEquals(Boolean.toString(true), allowed.toString()); hasRestoredAllServerConfig(list); }
GmsError { public void addError(final String field, final String message) { if (errors.get(field) == null) { LinkedList<String> l = new LinkedList<>(); l.add(message); errors.put(field, l); } else { errors.get(field).add(message); } } GmsError(); void addError(final String field, final String message); void addError(final String message); void removeErrors(final String field); void removeError(final String error); void removeError(final String field, final String message); static final String OTHERS; }
@SuppressWarnings("unchecked") @Test public void setErrors() { Map<String, List<String>> errors = new HashMap<>(); List<String> l = new LinkedList<>(); List<String> l2 = new LinkedList<>(); l.add("a"); l.add("b"); l2.add("c"); l2.add("d"); errors.put("k1", l); errors.put("k2", l2); GmsError e = new GmsError(); e.addError(MSG); e.addError(FIELD, MSG_2); Map<String, List<String>> currentErrors = (Map<String, List<String>>) ReflectionTestUtils.getField(e, ERRORS_HOLDER); assertNotNull(currentErrors); assertTrue(currentErrors.get(GmsError.OTHERS).contains(MSG)); assertTrue(currentErrors.get(FIELD).contains(MSG_2)); e.setErrors(errors); currentErrors = (Map<String, List<String>>) ReflectionTestUtils.getField(e, ERRORS_HOLDER); if (currentErrors == null) { currentErrors = new HashMap<>(); } assertEquals(currentErrors.get("k1"), l); assertEquals(currentErrors.get("k2"), l2); }
ConfigurationService { public void setIsMultiEntity(final boolean isMultiEntity) { insertOrUpdateValue(ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER, isMultiEntity); this.multiEntity = isMultiEntity; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void setIsMultiEntity() { final List<Iterable<BConfiguration>> list = deleteAllServerConfig(); configurationService.setIsMultiEntity(true); BConfiguration c = configurationRepository.findFirstByKey(keyMultiEntityApp); assertNotNull(c); assertEquals(Boolean.toString(true), c.getValue()); final Object multiEntity = ReflectionTestUtils.getField(configurationService, "multiEntity"); assertNotNull(multiEntity); assertEquals(Boolean.toString(true), multiEntity.toString()); hasRestoredAllServerConfig(list); }
ConfigurationService { public Long getLastAccessedEntityIdByUser(final long userId) { String v = getValueByUser(ConfigKey.LAST_ACCESSED_ENTITY.toString(), userId); return v != null ? Long.parseLong(v) : null; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void getLastAccessedEntityIdByUser() { EUser user = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(user); EOwnedEntity entity = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(entity); BConfiguration c = configurationRepository.save(new BConfiguration( keyLastAccessedEntity, String.valueOf(entity.getId()), user.getId() )); assertNotNull(c); assertEquals(Long.valueOf(c.getValue()), configurationService.getLastAccessedEntityIdByUser(user.getId())); }
ConfigurationService { public void setLastAccessedEntityIdByUser(final long userId, final long entityId) { insertOrUpdateValue(ConfigKey.LAST_ACCESSED_ENTITY, entityId, userId); } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void setLastAccessedEntityIdByUser() { EUser user = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(user); EOwnedEntity entity = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(entity); configurationService.setLastAccessedEntityIdByUser(user.getId(), entity.getId()); BConfiguration c = configurationRepository.findFirstByKeyAndUserId(keyLastAccessedEntity, user.getId()); assertNotNull(c); assertEquals(Long.valueOf(c.getValue()), entity.getId()); }
AppService { public boolean isInitialLoadOK() { if (initialLoadOK == null) { boolean ok = true; if (!configurationService.isApplicationConfigured()) { ok = configurationService.isDefaultConfigurationCreated(); ok = ok && permissionService.areDefaultPermissionsCreatedSuccessfully(); ok = ok && roleService.createDefaultRole() != null; ok = ok && userService.createDefaultUser() != null; ok = ok && oeService.createDefaultEntity() != null; ok = ok && configurationService.isDefaultUserAssignedToEntityWithRole(); } initialLoadOK = ok; } return initialLoadOK; } boolean isInitialLoadOK(); }
@Test public void isInitialLoadOKTest() { authRepository.deleteAll(); userRepository.deleteAll(); entityRepository.deleteAll(); roleRepository.deleteAll(); permissionRepository.deleteAll(); configRepository.deleteAll(); ReflectionTestUtils.setField(appService, "initialLoadOK", null); Assert.assertTrue(appService.isInitialLoadOK()); }
QueryService { public Query createQuery(final String qls) { return entityManager.createQuery(qls); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
@Test public void createQuery() { assertNotNull(repository.save(EntityUtil.getSamplePermission())); final Query query = queryService.createQuery("select e from BPermission e"); assertNotNull(query); final List<?> resultList = query.getResultList(); assertNotNull(resultList); assertFalse(resultList.isEmpty()); } @Test public void createQueryWithResultClass() { BPermission p = repository.save(EntityUtil.getSamplePermission()); assertNotNull(p); final Query query = queryService.createQuery("select e from BPermission e", BPermission.class); assertNotNull(query); final List<?> resultList = query.getResultList(); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(resultList.contains(p)); }
LinkPath { public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); } private LinkPath(); static String get(final String what); static String getSelf(final String what); static String get(); static final String EMBEDDED; static final String PAGE_SIZE_PARAM_META; static final String PAGE_SORT_PARAM_META; static final String PAGE_PAGE_PARAM_META; }
@Test public void getWhat() { Object field = ReflectionTestUtils.getField(LinkPath.class, "LINK"); String link = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "HREF"); String href = field != null ? field.toString() : ""; Assert.assertEquals(LinkPath.get("test"), String.format("%s.%s.%s", link, "test", href)); } @Test public void get() { Object field = ReflectionTestUtils.getField(LinkPath.class, "LINK"); String link = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "HREF"); String href = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "SELF"); String self = field != null ? field.toString() : ""; Assert.assertEquals(LinkPath.get(self), String.format("%s.%s.%s", link, self, href)); }
QueryService { public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
@Test public void createNativeQuery() { assertNotNull(repository.save(EntityUtil.getSamplePermission())); final Query nativeQuery = queryService.createNativeQuery("SELECT * FROM bpermission"); assertNotNull(nativeQuery); final List<?> resultList = nativeQuery.getResultList(); assertNotNull(resultList); assertFalse(resultList.isEmpty()); } @Test public void createNativeQueryWithResultClass() { BPermission p = repository.save(EntityUtil.getSamplePermission()); assertNotNull(p); final Query nativeQuery = queryService.createNativeQuery("SELECT * FROM bpermission", BPermission.class); assertNotNull(nativeQuery); final List<?> resultList = nativeQuery.getResultList(); assertNotNull(resultList); assertTrue(resultList.contains(p)); }
UserService implements UserDetailsService { public EUser createDefaultUser() { EUser u = new EUser( dc.getUserAdminDefaultUsername(), dc.getUserAdminDefaultEmail(), dc.getUserAdminDefaultName(), dc.getUserAdminDefaultLastName(), dc.getUserAdminDefaultPassword() ); u.setEnabled(true); return signUp(u, EmailStatus.VERIFIED); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void createDefaultUser() { assertNotNull(userRepository.findFirstByUsername(dc.getUserAdminDefaultUsername())); }
UserService implements UserDetailsService { public List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, true); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void addRolesToUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); List<Long> ids = new LinkedList<>(); ids.add(r1.getId()); ids.add(r2.getId()); assertEquals(2, ids.size()); List<Long> added = null; try { added = userService.addRolesToUser(u.getId(), e.getId(), ids); assertNotNull(added); assertEquals(added.size(), ids.size()); assertTrue(added.contains(ids.get(0))); assertTrue(added.contains(ids.get(1))); } catch (NotFoundEntityException e1) { LOGGER.error(e1.getLocalizedMessage()); fail("Roles could not be saved"); } final List<BRole> roles = authorizationRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertEquals(roles.size(), ids.size()); assertNotNull(added); assertEquals(added.size(), roles.size()); assertTrue(added.contains(roles.get(0).getId())); assertTrue(added.contains(roles.get(1).getId())); }
UserService implements UserDetailsService { public List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, false); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void removeRolesFromUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r1.getId()); assertNotNull(pk1); BAuthorization auth1 = authorizationRepository.save(new BAuthorization(pk1, u, e, r1)); assertNotNull(auth1); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r2.getId()); assertNotNull(pk1); BAuthorization auth2 = authorizationRepository.save(new BAuthorization(pk2, u, e, r2)); assertNotNull(auth2); Collection<Long> ids = new LinkedList<>(); ids.add(r1.getId()); ids.add(r2.getId()); List<BRole> roles = authorizationRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertEquals(roles.size(), ids.size()); assertTrue(ids.contains(roles.get(0).getId())); assertTrue(ids.contains(roles.get(1).getId())); List<Long> removed = null; try { removed = userService.removeRolesFromUser(u.getId(), e.getId(), ids); } catch (NotFoundEntityException e1) { LOGGER.error(e1.getLocalizedMessage()); fail("Roles could not be removed"); } assertNotNull(removed); assertEquals(removed.size(), roles.size()); assertTrue(removed.contains(roles.get(0).getId())); assertTrue(removed.contains(roles.get(1).getId())); roles = authorizationRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertTrue(roles.isEmpty()); }
UserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(final String usernameOrEmail) { EUser u = userRepository.findFirstByUsernameOrEmail(usernameOrEmail, usernameOrEmail); if (u != null) { return u; } throw new UsernameNotFoundException(msg.getMessage(USER_NOT_FOUND)); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void loadUserByUsername() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); UserDetails su = userService.loadUserByUsername(u.getUsername()); assertNotNull(su); assertEquals(su, u); }
UserService implements UserDetailsService { public String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator) { StringBuilder authBuilder = new StringBuilder(); EUser u = (EUser) loadUserByUsername(usernameOrEmail); if (u != null) { Long entityId = getEntityIdByUser(u); if (entityId == null) { return ""; } List<BPermission> pFromDB = permissionService.findPermissionsByUserIdAndEntityId(u.getId(), entityId); for (BPermission p : pFromDB) { authBuilder.append(p.getName()).append(separator); } } return authBuilder.toString(); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void getUserAuthoritiesForToken() { BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r1 = EntityUtil.getSampleRole(random.nextString()); r1.addPermission(p1, p2); assertNotNull(roleRepository.save(r1)); BPermission p3 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p3); BPermission p4 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p4); BRole r2 = EntityUtil.getSampleRole(random.nextString()); r2.addPermission(p3, p4); assertNotNull(roleRepository.save(r2)); EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r1.getId()); BAuthorization auth1 = new BAuthorization(pk1, u, e, r1); assertNotNull(authorizationRepository.save(auth1)); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r2.getId()); BAuthorization auth2 = new BAuthorization(pk2, u, e, r2); assertNotNull(authorizationRepository.save(auth2)); String separator = "--<<" + random.nextString() + ">>--"; String authForToken = userService.getUserAuthoritiesForToken(u.getUsername(), separator); assertNotNull(authForToken); assertNotEquals("", authForToken); List<String> permissionNames = Arrays.asList(authForToken.split(separator)); assertTrue(permissionNames.contains(p1.getName())); assertTrue(permissionNames.contains(p2.getName())); assertTrue(permissionNames.contains(p3.getName())); assertTrue(permissionNames.contains(p4.getName())); }
UserService implements UserDetailsService { public Map<String, List<BRole>> getRolesForUser(final Long id) throws NotFoundEntityException { EUser u = getUser(id); return authorizationRepository.getRolesForUserOverAllEntities(u.getId()); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void getRolesForUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e1 = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e1); EOwnedEntity e2 = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e2); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); BRole r3 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r3); BRole r4 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r4); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e1.getId(), r1.getId()); BAuthorization auth1 = authorizationRepository.save(new BAuthorization(pk1, u, e1, r1)); assertNotNull(auth1); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e1.getId(), r2.getId()); BAuthorization auth2 = authorizationRepository.save(new BAuthorization(pk2, u, e1, r2)); assertNotNull(auth2); BAuthorization.BAuthorizationPk pk3 = new BAuthorization.BAuthorizationPk(u.getId(), e2.getId(), r3.getId()); BAuthorization auth3 = authorizationRepository.save(new BAuthorization(pk3, u, e2, r3)); assertNotNull(auth3); BAuthorization.BAuthorizationPk pk4 = new BAuthorization.BAuthorizationPk(u.getId(), e2.getId(), r4.getId()); BAuthorization auth4 = authorizationRepository.save(new BAuthorization(pk4, u, e2, r4)); assertNotNull(auth4); try { final Map<String, List<BRole>> rolesForUser = userService.getRolesForUser(u.getId()); assertNotNull(rolesForUser); assertFalse(rolesForUser.isEmpty()); final Set<String> keySet = rolesForUser.keySet(); assertTrue(keySet.contains(e1.getUsername())); assertTrue(keySet.contains(e2.getUsername())); assertTrue(rolesForUser.get(e1.getUsername()).contains(r1)); assertTrue(rolesForUser.get(e1.getUsername()).contains(r2)); assertTrue(rolesForUser.get(e2.getUsername()).contains(r3)); assertTrue(rolesForUser.get(e2.getUsername()).contains(r4)); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("The username was not found"); } }
UserService implements UserDetailsService { public List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId) throws NotFoundEntityException { return authorizationRepository.getRolesForUserOverEntity( getUser(userId).getId(), getOwnedEntity(entityId).getId() ); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void getRolesForUserOverEntity() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r1.getId()); BAuthorization auth1 = authorizationRepository.save(new BAuthorization(pk1, u, e, r1)); assertNotNull(auth1); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r2.getId()); BAuthorization auth2 = authorizationRepository.save(new BAuthorization(pk2, u, e, r2)); assertNotNull(auth2); try { final List<BRole> roles = userService.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertFalse(roles.isEmpty()); assertTrue(roles.contains(r1)); assertTrue(roles.contains(r2)); } catch (NotFoundEntityException ex) { LOGGER.error(ex.getLocalizedMessage()); fail("Either the username or the entity was not found"); } }
UserService implements UserDetailsService { public Long getEntityIdByUser(final EUser u) { Long entityId = configService.getLastAccessedEntityIdByUser(u.getId()); if (entityId == null) { BAuthorization anAuth = authorizationRepository.findFirstByUserAndEntityNotNullAndRoleEnabled(u, true); if (anAuth == null) { return null; } entityId = anAuth.getEntity().getId(); configService.setLastAccessedEntityIdByUser(u.getId(), entityId); } return entityId; } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void getEntityIdByUserWithNoRoles() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); assertNull(userService.getEntityIdByUser(u)); }
LinkPath { public static String getSelf(final String what) { return String.format("%s.%s.%s", LINK, SELF, what); } private LinkPath(); static String get(final String what); static String getSelf(final String what); static String get(); static final String EMBEDDED; static final String PAGE_SIZE_PARAM_META; static final String PAGE_SORT_PARAM_META; static final String PAGE_PAGE_PARAM_META; }
@Test public void getSelf() { Object field = ReflectionTestUtils.getField(LinkPath.class, "LINK"); String link = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "HREF"); String href = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "SELF"); String self = field != null ? field.toString() : ""; Assert.assertEquals(LinkPath.get(self), String.format("%s.%s.%s", link, self, href)); }
OwnedEntityService { public EOwnedEntity createDefaultEntity() { return entityRepository.save(new EOwnedEntity( dc.getEntityDefaultName(), dc.getEntityDefaultUsername(), dc.getEntityDefaultDescription()) ); } EOwnedEntity createDefaultEntity(); EOwnedEntity create(final EOwnedEntity e); }
@Test public void createDefaultEntity() { assertNotNull(repository.findFirstByUsername(dc.getEntityDefaultUsername())); }
OwnedEntityService { public EOwnedEntity create(final EOwnedEntity e) throws GmsGeneralException { if (configService.isMultiEntity()) { return entityRepository.save(e); } throw GmsGeneralException.builder() .messageI18N("entity.add.not_allowed") .finishedOK(true).httpStatus(HttpStatus.CONFLICT) .build(); } EOwnedEntity createDefaultEntity(); EOwnedEntity create(final EOwnedEntity e); }
@Test public void create() { boolean initialIsM = configService.isMultiEntity(); if (!initialIsM) { configService.setIsMultiEntity(true); } try { final EOwnedEntity e = service.create(EntityUtil.getSampleEntity()); assertNotNull(e); Optional<EOwnedEntity> er = repository.findById(e.getId()); assertTrue(er.isPresent()); assertEquals(e, er.get()); } catch (GmsGeneralException e) { LOGGER.error(e.getLocalizedMessage()); fail("Entity could not be created"); } if (!initialIsM) { configService.setIsMultiEntity(false); } }
RoleService { public BRole createDefaultRole() { BRole role = new BRole(dc.getRoleAdminDefaultLabel()); role.setDescription(dc.getRoleAdminDefaultDescription()); role.setEnabled(dc.isRoleAdminDefaultEnabled()); final Iterable<BPermission> permissions = permissionRepository.findAll(); for (BPermission p : permissions) { role.addPermission(p); } return repository.save(role); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test public void createDefaultRole() { BRole r = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); assertNotNull("Default role not created", r); }
RoleService { public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test public void addPermissionsToRole() { BRole r = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r); BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(p1.getId()); pIDs.add(p2.getId()); try { List<Long> added = roleService.addPermissionsToRole(r.getId(), pIDs); assertEquals(added.size(), pIDs.size()); assertTrue(added.contains(p1.getId())); assertTrue(added.contains(p2.getId())); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("Could not add permissions to role"); } } @Test public void addPermissionsNotFoundToRole() { BRole r = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(INVALID_ID); boolean success = false; try { roleService.addPermissionsToRole(r.getId(), pIDs); } catch (NotFoundEntityException e) { success = true; assertEquals("role.add.permissions.found.none", e.getMessage()); } assertTrue(success); }
RoleService { public BRole getRole(final long id) throws NotFoundEntityException { Optional<BRole> r = repository.findById(id); if (!r.isPresent()) { throw new NotFoundEntityException(ROLE_NOT_FOUND); } return r.get(); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test public void getRoleNotFound() { boolean success = false; try { roleService.getRole(INVALID_ID); } catch (NotFoundEntityException e) { success = true; assertEquals(RoleService.ROLE_NOT_FOUND, e.getMessage()); } assertTrue(success); }
RoleService { public List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.REMOVE_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test public void removePermissionsFromRole() { BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r = EntityUtil.getSampleRole(random.nextString()); r.addPermission(p1, p2); roleRepository.save(r); assertNotNull(r); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(p1.getId()); pIDs.add(p2.getId()); try { List<Long> deleted = roleService.removePermissionsFromRole(r.getId(), pIDs); assertNotNull(deleted); assertEquals(deleted.size(), pIDs.size()); assertTrue(deleted.contains(p1.getId())); assertTrue(deleted.contains(p2.getId())); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("Could not remove element"); } }
RoleService { public List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.UPDATE_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test @Transactional public void updatePermissionsInRole() { BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r = EntityUtil.getSampleRole(random.nextString()); r.addPermission(p1, p2); assertNotNull(roleRepository.save(r)); assertTrue(r.getPermissions().contains(p1)); assertTrue(r.getPermissions().contains(p2)); BPermission p3 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p3); BPermission p4 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p4); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(p3.getId()); pIDs.add(p4.getId()); try { final List<Long> updated = roleService.updatePermissionsInRole(r.getId(), pIDs); assertNotNull(updated); assertEquals(updated.size(), pIDs.size()); assertTrue(updated.contains(p3.getId())); assertTrue(updated.contains(p4.getId())); assertFalse(updated.contains(p1.getId())); assertFalse(updated.contains(p2.getId())); Optional<BRole> role = roleRepository.findById(r.getId()); assertTrue(role.isPresent()); final Set<BPermission> rPermissions = role.get().getPermissions(); assertFalse(rPermissions.contains(p1)); assertFalse(rPermissions.contains(p2)); assertTrue(rPermissions.contains(p3)); assertTrue(rPermissions.contains(p4)); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("Could not update the role permissions"); } }
PermissionService { public List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId) { return repository.findPermissionsByUserIdAndEntityId(userId, entityId); } boolean areDefaultPermissionsCreatedSuccessfully(); List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId); Page<BRole> getAllRolesByPermissionId(final long id, final Pageable pageable); }
@Test public void findPermissionsByUserIdAndEntityId() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r = EntityUtil.getSampleRole(random.nextString()); r.addPermission(p1, p2); roleRepository.save(r); BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r.getId()); assertNotNull(authRepository.save(new BAuthorization(pk, u, e, r))); final List<BPermission> permissions = permissionService.findPermissionsByUserIdAndEntityId(u.getId(), e.getId()); assertTrue(permissions.contains(p1)); assertTrue(permissions.contains(p2)); }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentication); }
@Test public void getAuthentication() { SecurityContextHolder.clearContext(); SecurityContextHolder.getContext().setAuthentication(auth); final Authentication realAuthInfo = SecurityContextHolder.getContext().getAuthentication(); final Authentication facadeAuthInfo = authFacade.getAuthentication(); assertEquals("(getAuthentication)The \"principal\" set in the authentication in the facade context " + "does not match the \"principal\" set in the authentication in the real context", realAuthInfo.getPrincipal(), facadeAuthInfo.getPrincipal()); assertEquals("(getAuthentication)The \"authorities\" set in the authentication in the facade context" + " does not match the \"authorities\" set in the authentication in the real context", realAuthInfo.getAuthorities(), facadeAuthInfo.getAuthorities()); assertEquals("(getAuthentication)The \"credentials\" set in the authentication in the facade context" + " does not match the \"credentials\" set in the authentication in the real context", realAuthInfo.getCredentials(), facadeAuthInfo.getCredentials()); }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public void setAuthentication(final Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentication); }
@Test public void setAuthentication() { SecurityContextHolder.clearContext(); authFacade.setAuthentication(auth); final Authentication realAuthInfo = SecurityContextHolder.getContext().getAuthentication(); final Authentication facadeAuthInfo = authFacade.getAuthentication(); assertEquals("(setAuthentication)The \"principal\" set in the authentication in the facade context " + "does not match the \"principal\" set in the authentication in the real context", realAuthInfo.getPrincipal(), facadeAuthInfo.getPrincipal()); assertEquals("(setAuthentication)The \"authorities\" set in the authentication in the facade context " + "does not match the \"authorities\" set in the authentication in the real context", realAuthInfo.getAuthorities(), facadeAuthInfo.getAuthorities()); assertEquals("(setAuthentication)The \"credentials\" set in the authentication in the facade context " + "does not match the \"credentials\" set in the authentication in the real context", realAuthInfo.getCredentials(), facadeAuthInfo.getCredentials()); }
JWTService { public long getATokenExpirationTime() { return sc.getATokenExpirationTime() > 0 ? (sc.getATokenExpirationTime() * THOUSAND) : DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void getATokenExpirationTime() { final Object aTokenExpirationTime = ReflectionTestUtils.getField(sc, "aTokenExpirationTime"); long prev = aTokenExpirationTime != null ? Long.parseLong(aTokenExpirationTime.toString()) : -1; final long expTime = -10; ReflectionTestUtils.setField(sc, "aTokenExpirationTime", expTime); assertTrue("Expiration time for access token must be greater than zero", jwtService.getATokenExpirationTime() > 0); ReflectionTestUtils.setField(sc, "aTokenExpirationTime", prev); }
JWTService { public long getRTokenExpirationTime() { return sc.getRTokenExpirationTime() > 0 ? (sc.getRTokenExpirationTime() * THOUSAND) : DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void getRTokenExpirationTime() { long prev = Long.parseLong(String.valueOf(ReflectionTestUtils.getField(sc, "rTokenExpirationTime"))); final long expTime = -10; ReflectionTestUtils.setField(sc, "rTokenExpirationTime", expTime); assertTrue("Expiration time for refresh token must be greater than zero", jwtService.getRTokenExpirationTime() > 0); ReflectionTestUtils.setField(sc, "rTokenExpirationTime", prev); }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void createTwoTokensWithSubjectAreNotEqual() { final String sub = "TestSubjectBN"; final String token1 = jwtService.createToken(sub); final String token2 = jwtService.createToken(sub); assertNotEquals("The JWTService#createToken(String subject) method never should create two tokens " + "which are equals", token1, token2); } @Test public void createTwoTokensWithSubjectAndExpAreNotEqual() { final String sub = "TestSubjectCV"; final long exp = 123; final String token1 = jwtService.createToken(sub, exp); final String token2 = jwtService.createToken(sub, exp); assertNotEquals("The JWTService#createToken(String subject, long expiresIn) method never should " + "create two tokens which are equals", token1, token2); } @Test public void createTwoTokensWithSubjectAndAuthAreNotEqual() { final String sub = "TestSubjectRF"; final String auth = "ROLE_WS;ROLE_RF"; final String token1 = jwtService.createToken(sub, auth); final String token2 = jwtService.createToken(sub, auth); assertNotEquals("The JWTService#createToken(String subject, String authorities) method never should " + "create two tokens which are equals", token1, token2); } @Test public void createTwoTokensWithSubjectAuthAndExpAreNotEqual() { final String sub = "TestSubjectBN"; final String auth = "ROLE_GT;ROLE_DE"; final long exp = 123; final String token1 = jwtService.createToken(sub, auth, exp); final String token2 = jwtService.createToken(sub, auth, exp); assertNotEquals("The JWTService#createToken(String subject, String authorities, long expiresIn) " + "method never should create two tokens which are equals", token1, token2); }
JWTService { public String createRefreshToken(final String subject, final String authorities) { return getBuilder(subject, authorities, getRTokenExpirationTime()).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void createTwoRefreshTokensWithSubjectAndAuthAreNotEqual() { final String sub = "TestSubjectG"; final String auth = "ROLE_N;ROLE_C"; final String token1 = jwtService.createRefreshToken(sub, auth); final String token2 = jwtService.createRefreshToken(sub, auth); assertNotEquals("The JWTService#createRefreshToken(String subject, String authorities) method never " + "should create two tokens which are equals", token1, token2); }
JWTService { public Map<String, Object> getClaims(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); processClaimsJWT(claimsJwt, r, key); return r; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void getClaims() { final String sub = "TestSubjectX"; final String auth = "ROLE_1;ROLE_2"; final String token = jwtService.createToken(sub, auth); final Map<String, Object> claims = jwtService.getClaims(token, JWTService.SUBJECT, sc.getAuthoritiesHolder(), JWTService.EXPIRATION); assertClaimsState(claims, sub, auth); }
JWTService { public Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); Claims claims = processClaimsJWT(claimsJwt, r, key); r.put(AUDIENCE, claims.getAudience()); r.put(EXPIRATION, claims.getExpiration()); r.put(ID, claims.getId()); r.put(ISSUED_AT, claims.getIssuedAt()); r.put(ISSUER, claims.getIssuer()); r.put(NOT_BEFORE, claims.getNotBefore()); r.put(SUBJECT, claims.getSubject()); return r; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void getClaimsExtended() { final String sub = "TestSubjectY"; final String auth = "ROLE_X;ROLE_Y"; final long expiresIn = 99999999; final String token = jwtService.createToken(sub, auth, expiresIn); final String randomKey = "randomKey"; final Map<String, Object> claims = jwtService.getClaimsExtended(token, randomKey, sc.getAuthoritiesHolder()); assertClaimsState(claims, sub, auth); assertNull("Claims contains an incorrect pair key-value", claims.get(randomKey)); assertNotNull("Expiration time is null", claims.get(JWTService.EXPIRATION)); assertTrue("Expiration time is not an instance of Date", claims.get(JWTService.EXPIRATION) instanceof Date); if (claims.get(JWTService.EXPIRATION) != null && claims.get(JWTService.EXPIRATION) instanceof Date) { assertTrue("Expiration time is not greater than the creation time of the token", ((Date) claims.get(JWTService.EXPIRATION)).getTime() > expiresIn); } }
SecurityConst { public String[] getFreeURLsAnyRequest() { return freeURLsAnyRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); static final String AUTHORITIES_SEPARATOR; static final String ACCESS_TOKEN_URL; static final String USERNAME_HOLDER; static final String USERNAME_REGEXP; }
@Test public void getFreeURLsAnyRequest() { assertArrayEquals(autowiredSc.getFreeURLsAnyRequest(), freeURLsAnyRequestBind.split(SEPARATOR)); }
ConfigurationController { @GetMapping("sign-up") public boolean isUserRegistrationAllowed() { return configService.isUserRegistrationAllowed(); } @GetMapping("sign-up") boolean isUserRegistrationAllowed(); @GetMapping("multientity") boolean isMultiEntity(); @GetMapping Object getConfig(@RequestParam(value = "key", required = false) final String key, @RequestParam(value = "id", required = false) final Long id); @GetMapping("{id}") Map<String, Object> getConfigByUser(@PathVariable(value = "id") final Long id); @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseStatus(HttpStatus.NO_CONTENT) void saveConfig(@RequestBody final Map<String, Object> configs); }
@Test public void isUserRegistrationAllowed() throws Exception { mvc.perform( get(apiPrefix + "/" + REQ_STRING + "/sign-up") .header(authHeader, tokenType + " " + accessToken) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) ).andExpect(status().isOk()); }
ConfigurationController { @GetMapping("multientity") public boolean isMultiEntity() { return configService.isMultiEntity(); } @GetMapping("sign-up") boolean isUserRegistrationAllowed(); @GetMapping("multientity") boolean isMultiEntity(); @GetMapping Object getConfig(@RequestParam(value = "key", required = false) final String key, @RequestParam(value = "id", required = false) final Long id); @GetMapping("{id}") Map<String, Object> getConfigByUser(@PathVariable(value = "id") final Long id); @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseStatus(HttpStatus.NO_CONTENT) void saveConfig(@RequestBody final Map<String, Object> configs); }
@Test public void isMultiEntity() throws Exception { mvc.perform( get(apiPrefix + "/" + REQ_STRING + "/multientity") .header(authHeader, tokenType + " " + accessToken) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) ).andExpect(status().isOk()); }
RestOwnedEntityController { @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity) throws GmsGeneralException { EOwnedEntity e = entityService.create(entity.getContent()); if (e != null) { return new ResponseEntity<>(HttpStatus.CREATED); } else { throw GmsGeneralException.builder().messageI18N("entity.add.error").finishedOK(false).build(); } } @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity); }
@Test public void create() throws Exception { final boolean multiEntity = configService.isMultiEntity(); if (!multiEntity) { configService.setIsMultiEntity(true); } EOwnedEntity e = EntityUtil.getSampleEntity(random.nextString()); ConstrainedFields fields = new ConstrainedFields(EOwnedEntity.class); mvc.perform(post(apiPrefix + "/" + REQ_STRING) .contentType(MediaType.APPLICATION_JSON) .header(authHeader, tokenType + " " + accessToken) .content(objectMapper.writeValueAsString(e))) .andExpect(status().isCreated()) .andDo(restDocResHandler.document( requestFields( fields.withPath("name") .description("Natural name which is used commonly for referring to the entity"), fields.withPath("username") .description("A unique string representation of the {@LINK #name}. Useful " + "when there are other entities with the same {@LINK #name}"), fields.withPath("description") .description("A brief description of the entity") ) )); if (!multiEntity) { configService.setIsMultiEntity(false); } }
SecurityController { @PostMapping(SecurityConst.ACCESS_TOKEN_URL) public Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload) { String oldRefreshToken = payload.getRefreshToken(); if (oldRefreshToken != null) { try { String[] keys = {sc.getAuthoritiesHolder()}; Map<String, Object> claims = jwtService.getClaimsExtended(oldRefreshToken, keys); String sub = claims.get(JWTService.SUBJECT).toString(); String authorities = claims.get(keys[0]).toString(); Date iat = (Date) claims.get(JWTService.ISSUED_AT); String newAccessToken = jwtService.createToken(sub, authorities); String newRefreshToken = jwtService.createRefreshToken(sub, authorities); return jwtService.createLoginData(sub, newAccessToken, iat, authorities, newRefreshToken); } catch (JwtException e) { throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.invalid"); } } throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.required"); } @PostMapping("${gms.security.sign_up_url}") @ResponseStatus(HttpStatus.CREATED) @ResponseBody ResponseEntity<EUser> signUpUser(@RequestBody @Valid final Resource<? extends EUser> user); @PostMapping(SecurityConst.ACCESS_TOKEN_URL) Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload); }
@Test public void refreshToken() throws Exception { final RefreshTokenPayload payload = new RefreshTokenPayload(refreshToken); final ConstrainedFields fields = new ConstrainedFields(RefreshTokenPayload.class); mvc.perform( post(apiPrefix + "/" + SecurityConst.ACCESS_TOKEN_URL).contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(payload)) ).andExpect(status().isOk()) .andDo( restDocResHandler.document( requestFields( fields.withPath("refreshToken") .description("The refresh token provided when login was " + "previously performed") ) ) ); }
EUser extends GmsEntity implements UserDetails { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? Collections.unmodifiableCollection(authorities) : null; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
@Test public void getAuthorities() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "authorities", authoritiesS); assertArrayEquals(entity0.getAuthorities().toArray(), authoritiesS.toArray()); }