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 lookupKeyGenerato...
@Test public void testCreateSearchObject() throws Exception { assertNotNull(factory.createSearchObject()); }
RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch newInstance() { return createSearchObject(); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedIt...
@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...
@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 = ...
BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public RelatedItem[] convertFrom(RelatedItemIndexingMessage message) { RelatedItemSet items = message.getRelatedItems(); int numberOfRelatedItems = items.getNumberOfRelatedItems(); RelatedItem[] relatedItems = new RelatedItem[numb...
@Test public void testConvertFromSingleItemIndexingMessage() throws Exception { RelatedItemIndexingMessageConverter converter = getConverter(); RelatedItemIndexingMessage message = getIndexingMessageWithOneRelatedItem(); RelatedItem[] products = converter.convertFrom(message); assertEquals("Should only have found a sin...
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 arrayStri...
@Test public void testHttpParseFoundTwoSourcesOneWithAnError() { System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_HTTP_HOSTS, "http: Configuration configuration = new SystemPropertiesConfiguration(); HttpElasticSearchClientFactory factory = new AHCHttpElasticSearchClientFactory(configuration); reposito...
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;...
@Test public void testRelatedItemIds() { RelatedItemInfo info1 = createRelatedItemInfoObj("1"); RelatedItemInfo info2 = createRelatedItemInfoObj("2"); RelatedItemInfo info3 = createRelatedItemInfoObj("3"); RelatedItemInfo info4 = createRelatedItemInfoObj("4"); RelatedItemInfo info5 = createRelatedItemInfoObj("5"); Rela...
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); Relate...
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) { request...
@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...
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(re...
@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("a8f...
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()==...
@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_SNIF...
ElasticSearchRelatedItemHttpSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches", searches.length); Sear...
@Test public void testEmptyResultsAreReturnedWhenNoIndexExists() { repository = searchRepositoryFactory.createRelatedItemSearchRepository(configuration,builder); SearchResultEventWithSearchRequestKey[] results = repository.findRelatedItems(configuration, createSearch()); assertEquals(2,results.length); System.out.print...
NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: fact...
@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.set...
ElasticSearchRelatedItemSearchRepository implements RelatedItemSearchRepository<FrequentlyRelatedSearchResult[]> { @Override public SearchResultEventWithSearchRequestKey[] findRelatedItems(Configuration configuration, RelatedItemSearch[] searches) { log.debug("request to execute {} searches",searches.length); SearchRes...
@Test public void testFailedResultsAreReturnedWhenNoIndexExists() { SearchResultEventWithSearchRequestKey[] results = repository.findRelatedItems(configuration, createSearch()); assertEquals(2,results.length); System.out.println("testFailedResultsAreReturnedWhenNoIndexExists, Results 0 outcometype: " + results[0].getRe...
DisruptorBasedSearchRequestProcessor implements RelatedItemSearchRequestProcessor { @Override public SearchRequestSubmissionStatus processRequest(RelatedItemSearchType requestType, Map<String,String> parameters, SearchResponseContext[] context) { SearchRequestParameterValidator validator = requestValidators.getValidato...
@Test public void testProcessRequestThatFailsValidationIsCaughtAndNotProcessed() throws Exception { Configuration configuration = new SystemPropertiesConfiguration(); IncomingSearchRequestTranslator translator = mock(IncomingSearchRequestTranslator.class); RelatedContentSearchRequestProcessorHandler hanlder = mock(Rela...
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 = obje...
@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 ...
RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler implements RelatedContentSearchRequestProcessorHandler { @Override public void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch) throws Exception { handleRequest(event,searchRequestExecutor[this.currentIndex++ & mask]); } Round...
@Test public void testCallingOnEventThatEachExecutorIsCalledInRoundRobinFashion() throws Exception { Configuration config = new SystemPropertiesConfiguration(); RelatedItemSearchExecutor executor1 = mock(RelatedItemSearchExecutor.class); RelatedItemSearchExecutor executor2 = mock(RelatedItemSearchExecutor.class); Relat...
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.get...
@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.pu...
RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorF...
@Test public void testSingleRelatedContentSearchRequestProcessorHandlerIsCreated() { System.setProperty(ConfigurationConstants.PROPNAME_NUMBER_OF_SEARCHING_REQUEST_PROCESSORS,"1"); Configuration config = new SystemPropertiesConfiguration(); RoundRobinRelatedContentSearchRequestProcessorHandlerFactory factory = new Roun...
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void storeResponseContextForSearchRequest(SearchRequestLookupKey key, SearchResponseContext[] context) { ringBuffer.publishEvent(storeResponseContextTranslator,key,context); } DisruptorRelatedItemS...
@Test public void testStoreResponseContextForSearchRequest() throws Exception { Configuration config = new SystemPropertiesConfiguration(); RequestCountingContextLookup contextLookup = new RequestCountingContextLookup(new MultiMapSearchResponseContextLookup(config),1,1); ResponseEventHandler responseHandler = mock(Resp...
DisruptorRelatedItemSearchResultsToResponseGateway implements RelatedItemSearchResultsToResponseGateway { @Override public void sendSearchResultsToResponseContexts(SearchResultEventWithSearchRequestKey[] multipleSearchResults) { ringBuffer.publishEvent(processSearchResultsTranslator,multipleSearchResults); } DisruptorR...
@Test public void testSendSearchResultsToResponseContexts() throws Exception { Configuration config = new SystemPropertiesConfiguration(); RequestCountingContextLookup contextLookup = new RequestCountingContextLookup(new MultiMapSearchResponseContextLookup(config),1,1); ResponseEventHandler responseHandler = mock(Respo...
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); handle...
@Test public void testHandleFrequentlyRelatedSearchResultResponseEvent() throws Exception { SearchResultsConverterFactory resultsConverterFactory = mock(SearchResultsConverterFactory.class); NumberOfSearchResultsConverter searchResultsConverter = new NumberOfSearchResultsConverter("application/json"); when(resultsConve...
MapBasedSearchResponseContextHandlerLookup implements SearchResponseContextHandlerLookup { @Override public SearchResponseContextHandler getHandler(Class responseClassToHandle) { SearchResponseContextHandler handler = mappings.get(responseClassToHandle); return handler == null ? defaultMapping : handler; } MapBasedSear...
@Test public void testGetHandlerReturnsDefaultMapping() throws Exception { SearchResponseContextHandler h = defaultLookup.getHandler(Long.class); assertSame(DebugSearchResponseContextHandler.INSTANCE,h); } @Test public void testDefaultHandlerReturnedForCustomLookup() { assertSame(mockHandler1, customMappingsLookup.getH...
HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = nu...
@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 ByteArra...
JsonSmartIndexingRequestConverterFactory implements IndexingRequestConverterFactory { @Override public IndexingRequestConverter createConverter(Configuration configuration, ByteBuffer convertFrom) throws InvalidIndexingRequestException { return new JsonSmartIndexingRequestConverter(configuration,dateCreator,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 ab...
JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProp...
@Test public void testANonStringPropertyIsIgnored() { String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ \"B009S4IJCK\", \"B0076UICIO\" ,\"B0096TJCXW\" ]"+ "}"; IndexingRequestConverter converter = createConverter(ByteBuffer.wrap(json.getBytes())); RelatedItemIndexingMessage message...
JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String getCurrentDayAndHourAndMinute() { DateTime dt = new DateTime(); DateTime utc =dt.withZone(DateTimeZone.UTC); return formatter.print(utc); } @Override String getCurrentDayAndHourAndMinute(); @Overrid...
@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 parseToDat...
@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 ...
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) {...
@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(); } @O...
@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")); ...
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 d...
@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 testTimeIsAd...
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(); @Overr...
@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=nu...
ElasticSearchRelatedItemIndexingRepository implements RelatedItemStorageRepository { @Override @PreDestroy public void shutdown() { log.debug("Shutting down ElasticSearchRelatedItemIndexingRepository"); try { elasticSearchClientFactory.shutdown(); } catch(Exception e) { } } ElasticSearchRelatedItemIndexingRepository(Co...
@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(Configu...
@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(dateC...
@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.getStorageInd...
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(dateS...
@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(...
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAn...
@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.getStorageIndexNamePre...
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 {}...
@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.onEv...
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { public void shutdown() { try { storageRepository.shutdown(); } catch(Exception e) { log.error("Problem shutting down storage repository"); } } BatchingRelatedItemReferenceEventHandler(int batchSize, ...
@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); } BatchingRe...
@Test public void testFactoryCreatesNewBatchingRelatedItemReferenceEventHander() { BatchingRelatedItemReferenceEventHanderFactory factory = new BatchingRelatedItemReferenceEventHanderFactory(new SystemPropertiesConfiguration(),repo,null); assertNotSame(factory.getHandler(),factory.getHandler()); assertEquals(2,repo.get...
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...
@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(50...
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(Execu...
@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....
@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.onEv...
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void shutdown() { if(!shutdown) { shutdown = true; try { storageRepository.shutdown(); } catch(Exception e) { log.warn("Unable to shutdown respository client"); } } } SingleRelatedItemIndexingMessageEventHa...
@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); a...
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(...
@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(@Nul...
@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(nul...
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 getTy...
@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.hashCod...
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.strin...
@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(getCheckStri...
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 Str...
@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 g...
@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 = t...
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 getBAuthor...
@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;...
ConfigurationService { public boolean isApplicationConfigured() { return configurationRepository.count() > 0; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, ...
@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_REGISTRA...
@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(keyMultiEntity...
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 ...
@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 E...
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(fina...
@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(configura...
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 Config...
@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...
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 GmsGeneralExcept...
@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...
ConfigurationService { public void setUserRegistrationAllowed(final boolean userRegistrationAllowed) { insertOrUpdateValue(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER, userRegistrationAllowed); this.userRegistrationAllowed = userRegistrationAllowed; } @Autowired ConfigurationService(final BConfigurationRepository...
@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.get...
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(fi...
@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.addErr...
ConfigurationService { public void setIsMultiEntity(final boolean isMultiEntity) { insertOrUpdateValue(ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER, isMultiEntity); this.multiEntity = isMultiEntity; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, fin...
@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 multiE...
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, ...
@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(n...
ConfigurationService { public void setLastAccessedEntityIdByUser(final long userId, final long entityId) { insertOrUpdateValue(ConfigKey.LAST_ACCESSED_ENTITY, entityId, userId); } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserReposito...
@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.setLastAccessedEntityIdByUse...
AppService { public boolean isInitialLoadOK() { if (initialLoadOK == null) { boolean ok = true; if (!configurationService.isApplicationConfigured()) { ok = configurationService.isDefaultConfigurationCreated(); ok = ok && permissionService.areDefaultPermissionsCreatedSuccessfully(); ok = ok && roleService.createDefaultR...
@Test public void isInitialLoadOKTest() { authRepository.deleteAll(); userRepository.deleteAll(); entityRepository.deleteAll(); roleRepository.deleteAll(); permissionRepository.deleteAll(); configRepository.deleteAll(); ReflectionTestUtils.setField(appService, "initialLoadOK", null); Assert.assertTrue(appService.isInit...
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 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 St...
@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.form...
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(resu...
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.VERIFI...
@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 EmailStatu...
@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())); assertNotN...
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 Emai...
@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())); asser...
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 cr...
@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...
@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(ran...
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 emailSt...
@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.nex...
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 sig...
@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.nextSt...
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 ...
@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 fina...
@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, ...
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(); } EOwnedEntit...
@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());...
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) {...
@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 ro...
@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.getSamplePe...
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>...
@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...
@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(rando...
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 l...
@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.getSam...
PermissionService { public List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId) { return repository.findPermissionsByUserIdAndEntityId(userId, entityId); } boolean areDefaultPermissionsCreatedSuccessfully(); List<BPermission> findPermissionsByUserIdAndEntityId(final long userId,...
@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.getSam...
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("(getAu...
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public void setAuthentication(final Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentic...
@Test public void setAuthentication() { SecurityContextHolder.clearContext(); authFacade.setAuthentication(auth); final Authentication realAuthInfo = SecurityContextHolder.getContext().getAuthentication(); final Authentication facadeAuthInfo = authFacade.getAuthentication(); assertEquals("(setAuthentication)The \"princ...
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 su...
@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", ...
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 s...
@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", jwtSe...
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...
@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", ...
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 subje...
@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#createRefreshT...
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 S...
@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, ...
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...
@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,...
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; ...
@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", req...
@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...
@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....
@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(ap...
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> cla...
@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) .c...
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, f...
@Test public void getAuthorities() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "authorities", authoritiesS); assertArrayEquals(entity0.getAuthorities().toArray(), authoritiesS.toArray()); }