method2testcases
stringlengths
118
3.08k
### Question: 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); }### Answer: @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)); }
### Question: 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(); }### Answer: @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()); }
### Question: 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(); }### Answer: @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()); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @Test public void testCurrentTimeDayAndHour() { String before = getNow(); String s = formatter.getCurrentDayAndHourAndMinute(); String after = getNow(); checkEquals(s,before,after); }
### Question: JodaUTCCurrentDateAndHourAndMinuteFormatter implements UTCCurrentDateAndHourAndMinuteFormatter { @Override public String parseToDateAndHourAndMinute(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHourAndMinute(); @Override String parseToDateAndHourAndMinute(String dateAndOrTime); }### Answer: @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); }
### Question: 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); }### Answer: @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))); }
### Question: 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); }### Answer: @Test public void testCurrentTimeDayAndHour() { String before = getNow(); String s = formatter.getCurrentDayAndHour(); String after = getNow(); checkEquals(s,before,after); }
### Question: JodaUTCCurrentDateAndHourFormatter implements UTCCurrentDateAndHourFormatter { @Override public String parseToDateAndHour(String dateAndOrTime) { return formatter.print(formatterUTC.parseDateTime(dateAndOrTime)); } @Override String getCurrentDayAndHour(); @Override String parseToDateAndHour(String dateAndOrTime); }### Answer: @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); }
### Question: 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); }### Answer: @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) { } }
### Question: 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(); }### Answer: @Test public void testShutdown() throws Exception { }
### Question: 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(); }### Answer: @Test public void testShutdown() throws Exception { }
### Question: 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(); }### Answer: @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()); }
### Question: 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(); }### Answer: @Test public void testShutdownIsCalledOnStorageRepo() { handler.shutdown(); assertTrue(repo.isShutdown()); }
### Question: 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(); }### Answer: @Test public void testFactoryCreatesNewBatchingRelatedItemReferenceEventHander() { BatchingRelatedItemReferenceEventHanderFactory factory = new BatchingRelatedItemReferenceEventHanderFactory(new SystemPropertiesConfiguration(),repo,null); assertNotSame(factory.getHandler(),factory.getHandler()); assertEquals(2,repo.getInvocationCount()); }
### Question: 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(); }### Answer: @Test public void testShutdownIsCalledOnStorageRepo() { handler.shutdown(); assertTrue(repo.handlers.get(0).isShutdown()); assertTrue(repo.handlers.get(1).isShutdown()); }
### Question: 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(); }### Answer: @Test public void testShutdownIsCalledOnStorageRepo() { handler.shutdown(); assertTrue(repo.isShutdown()); }
### Question: TotalResult { @NonNull public List<CheckInfo> getList() { return mList; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); @NonNull List<CheckInfo> getList(); @CheckingState int getCheckState(); }### Answer: @Test public void getList() throws Exception { assertEquals(totalResult.getList().size(), 0); }
### Question: TotalResult { @CheckingState public int getCheckState() { return mCheckState; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); @NonNull List<CheckInfo> getList(); @CheckingState int getCheckState(); }### Answer: @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); }
### Question: 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(); }### Answer: @Test public void getTypeCheck() throws Exception { checkInfo.setTypeCheck(CH_TYPE_HOOKS); assertEquals(checkInfo.getTypeCheck(), CH_TYPE_HOOKS); }
### Question: 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(); }### Answer: @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)); }
### Question: 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(); }### Answer: @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()); }
### Question: 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; }### Answer: @Test public void getPath() { testPath = "/sample34"; GmsSecurityException e = new GmsSecurityException("somePath"); ReflectionTestUtils.setField(e, "path", testPath); assertEquals(testPath, e.getPath()); }
### Question: 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(); }### Answer: @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()); }
### Question: 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(); }### Answer: @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()); }
### Question: 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; }### Answer: @Test public void configurationExist() { assertTrue(configurationService.isApplicationConfigured() && configurationRepository.count() > 0); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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())); }
### Question: 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; }### Answer: @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()); }
### Question: 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(); }### Answer: @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()); }
### Question: 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); }### Answer: @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)); }
### Question: 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; }### Answer: @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)); }
### Question: 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); }### Answer: @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)); }
### Question: 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); }### Answer: @Test public void createDefaultUser() { assertNotNull(userRepository.findFirstByUsername(dc.getUserAdminDefaultUsername())); }
### Question: 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); }### Answer: @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); }
### Question: 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); }### Answer: @Test public void getEntityIdByUserWithNoRoles() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); assertNull(userService.getEntityIdByUser(u)); }
### Question: 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; }### Answer: @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)); }
### Question: OwnedEntityService { public EOwnedEntity createDefaultEntity() { return entityRepository.save(new EOwnedEntity( dc.getEntityDefaultName(), dc.getEntityDefaultUsername(), dc.getEntityDefaultDescription()) ); } EOwnedEntity createDefaultEntity(); EOwnedEntity create(final EOwnedEntity e); }### Answer: @Test public void createDefaultEntity() { assertNotNull(repository.findFirstByUsername(dc.getEntityDefaultUsername())); }
### Question: 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); }### Answer: @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); } }
### Question: 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; }### Answer: @Test public void createDefaultRole() { BRole r = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); assertNotNull("Default role not created", r); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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"); } }
### Question: 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); }### Answer: @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)); }
### Question: AuthenticationFacadeImpl implements AuthenticationFacade { @Override public Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentication); }### Answer: @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()); }
### Question: AuthenticationFacadeImpl implements AuthenticationFacade { @Override public void setAuthentication(final Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentication); }### Answer: @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()); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @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); }
### Question: 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; }### Answer: @Test public void getFreeURLsAnyRequest() { assertArrayEquals(autowiredSc.getFreeURLsAnyRequest(), freeURLsAnyRequestBind.split(SEPARATOR)); }
### Question: 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); }### Answer: @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()); }
### Question: 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); }### Answer: @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()); }
### Question: 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); }### Answer: @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); } }
### Question: 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); }### Answer: @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") ) ) ); }
### Question: 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(); }### Answer: @Test public void getAuthorities() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "authorities", authoritiesS); assertArrayEquals(entity0.getAuthorities().toArray(), authoritiesS.toArray()); }
### Question: EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonExpired() { return accountNonExpired == null || accountNonExpired; } 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(); }### Answer: @Test public void isAccountNonExpired() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "accountNonExpired", accountNonExpiredS); assertEquals(entity0.isAccountNonExpired(), accountNonExpiredS); }
### Question: EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonLocked() { return accountNonLocked == null || accountNonLocked; } 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(); }### Answer: @Test public void isAccountNonLocked() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "accountNonLocked", accountNonLockedS); assertEquals(entity0.isAccountNonLocked(), accountNonLockedS); }
### Question: EUser extends GmsEntity implements UserDetails { @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired == null || credentialsNonExpired; } 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(); }### Answer: @Test public void isCredentialsNonExpired() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "credentialsNonExpired", credentialsNonExpiredS); assertEquals(entity0.isCredentialsNonExpired(), credentialsNonExpiredS); }
### Question: EUser extends GmsEntity implements UserDetails { @Override public boolean isEnabled() { return enabled != null && enabled; } 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(); }### Answer: @Test public void isEnabled() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "enabled", enabledS); assertEquals(entity0.isEnabled(), enabledS); }
### Question: EUser extends GmsEntity implements UserDetails { public boolean isEmailVerified() { return emailVerified != null && emailVerified; } 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(); }### Answer: @Test public void isEmailVerified() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "emailVerified", emailVerifiedS); assertEquals(entity0.isEmailVerified(), emailVerifiedS); }
### Question: SecurityConst { public String[] getFreeURLsGetRequest() { return freeURLsGetRequest.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; }### Answer: @Test public void getFreeURLsGetRequest() { assertArrayEquals(autowiredSc.getFreeURLsGetRequest(), freeURLsGetRequestBind.split(SEPARATOR)); }
### Question: BRole extends GmsEntity { public void addPermission(final BPermission... p) { if (permissions == null) { permissions = new HashSet<>(); } permissions.addAll(Arrays.asList(p)); } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); }### Answer: @Test public void addPermission() { cleanEntity0(); entity0.addPermission(sampleP); final Collection<?> permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && permissions.contains(sampleP)); }
### Question: BRole extends GmsEntity { public void removePermission(final BPermission... p) { if (permissions != null) { for (BPermission iP : p) { permissions.remove(iP); } } } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); }### Answer: @Test public void removePermission() { Collection<BPermission> auxP = new HashSet<>(); auxP.add(sampleP); cleanEntity0(); ReflectionTestUtils.setField(entity0, "permissions", auxP); Collection<?> permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && permissions.contains(sampleP)); entity0.removePermission(sampleP); permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && !permissions.contains(sampleP)); }
### Question: Application extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(Application.class, args); GMS_LOGGER.info("Application is running..."); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }### Answer: @Test public void mainTest() { Runnable runnable = () -> Application.main(noArgs); Thread thread = new Thread(runnable); thread.start(); }
### Question: Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) { return builder.sources(Application.class); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }### Answer: @Test public void configureTest() { Application app = new Application(); assertNotNull(app.configure(new SpringApplicationBuilder(Application.class))); }
### Question: Application extends SpringBootServletInitializer { @Bean public CommandLineRunner commandLineRunner(final AppService appService) { return strings -> { if (!appService.isInitialLoadOK()) { GMS_LOGGER.error("App did not start properly and probably will fail at some point. Restarting it is " + "highly advisable"); } }; } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }### Answer: @Test public void commandLineRunnerBeanCreationIsOK() { Application app = new Application(); assertNotNull(app.commandLineRunner(appService)); }
### Question: Application extends SpringBootServletInitializer { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }### Answer: @Test public void bCryptPasswordEncoderTest() { Application app = new Application(); assertNotNull(app.bCryptPasswordEncoder()); }
### Question: SecurityConst { public String[] getFreeURLsPostRequest() { return freeURLsPostRequest.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; }### Answer: @Test public void getFreeURLsPostRequest() { assertArrayEquals(autowiredSc.getFreeURLsPostRequest(), freeURLsPostRequestBind.split(SEPARATOR)); }
### Question: ReplayingRandom extends Random { @Override public int nextInt(int n) { if (n == 5) { return getNextValueOf(fives, indexInFives++); } else if (n == 9) { return getNextValueOf(nines, indexInNines++); } throw new UnsupportedOperationException("not expected invocation of nextInt(" + n + ")"); } ReplayingRandom(String five, String nine); @Override int nextInt(int n); }### Answer: @Test public void shouldReturnExpectedRandomsFor5And9() { assertThat(rand.nextInt(5), equalTo(2)); assertThat(rand.nextInt(9), equalTo(3)); assertThat(rand.nextInt(5), equalTo(3)); assertThat(rand.nextInt(9), equalTo(3)); assertThat(rand.nextInt(5), equalTo(3)); assertThat(rand.nextInt(9), equalTo(8)); assertThat(rand.nextInt(5), equalTo(4)); assertThat(rand.nextInt(9), equalTo(2)); } @Test(expected = UnsupportedOperationException.class) public void shouldFailForOthers() { rand.nextInt(3); }
### Question: HttpServletResponseExcelWrite implements OutputStreamDelegate { public static ExcelWrite build(InputStream inputStream, String fileName, HttpServletRequest request, HttpServletResponse response) { Objects.requireNonNull(inputStream); Objects.requireNonNull(fileName); Objects.requireNonNull(request); Objects.requireNonNull(response); return new CopyInputStreamExcelWrite(inputStream, fileName, new HttpServletResponseExcelWrite(request, response)); } private HttpServletResponseExcelWrite(HttpServletRequest request, HttpServletResponse response); @Override OutputStream createOutputStream(String fileName); static ExcelWrite build(InputStream inputStream, String fileName, HttpServletRequest request, HttpServletResponse response); static ExcelWrite build(String fileName, HttpServletRequest request, HttpServletResponse response); }### Answer: @Test public void testWriteExcel() { HttpServletResponseExcelWrite.build(fileName, request, response) .deal(ExcelDataList.getTitle(), get(), ExcelDataList.getTenList()) .write(); } @Test public void testWriteExcelByInputStream() { HttpServletResponseExcelWrite.build(this.getClass().getResourceAsStream("/c.xls"), fileName, request, response) .deal(new WriteDeal<ExcelDto>() { public String[] dealBean(ExcelDto obj) { String[] result = new String[3]; result[0] = obj.getId() + ""; result[1] = obj.getName(); result[2] = obj.getAge() + ""; return result; } public int skipLine() { return 4; } @Override public Map<String, Object> additional() { Map<String, Object> map = new HashMap<>(); map.put("quoteCurrency", "ETH"); map.put("symbol", "USDT_ETH"); map.put("startTime", "2019-01-09 00:00:00"); map.put("endTime", "2019-01-09 12:00:00"); return map; } }, ExcelDataList.getTenList()) .write(); }
### Question: SpringProxyUtils { public static boolean isMultipleProxy(Object proxy) { try { ProxyFactory proxyFactory = getProxyFactory(proxy); if (proxyFactory == null) { return false; } ConfigurablePropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(proxyFactory); TargetSource targetSource = (TargetSource) accessor.getPropertyValue("targetSource"); if (targetSource == null) { return false; } return AopUtils.isAopProxy(targetSource.getTarget()); } catch (Exception e) { throw new IllegalArgumentException("proxy args maybe not proxy " + "with cglib or jdk dynamic proxy. this method not support", e); } } static T getRealTarget(Object proxy); static boolean isMultipleProxy(Object proxy); static ProxyFactory findJdkDynamicProxyFactory(Object proxy); static ProxyFactory findCglibProxyFactory(Object proxy); static boolean isTransactional(Object proxy); static void removeTransactional(Object proxy); static boolean isAsync(Object proxy); static void removeAsync(Object proxy); }### Answer: @Test public void testIsMultipleProxy() { Bmw bmw = new Bmw(); ProxyFactory proxyFactory1 = new ProxyFactory(); TargetSource targetSource1 = new SingletonTargetSource(bmw); proxyFactory1.setTargetSource(targetSource1); Advisor[] advisors = new Advisor[1]; advisors[0] = advisorAdapterRegistry.wrap(new TestMethodInterceptor()); proxyFactory1.addAdvisors(advisors); Object object = proxyFactory1.getProxy(); ProxyFactory proxyFactory = new ProxyFactory(); TargetSource targetSource = new SingletonTargetSource(object); proxyFactory.setTargetSource(targetSource); Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(bmw.getClass()); for (Class<?> targetInterface : targetInterfaces) { proxyFactory.addInterface(targetInterface); } advisors[0] = advisorAdapterRegistry.wrap(new TestMethodInterceptor()); proxyFactory.addAdvisors(advisors); Car proxy = (Car) proxyFactory.getProxy(); assertTrue(SpringProxyUtils.isMultipleProxy(proxy)); SpringProxyUtils.getRealTarget(proxy); }
### Question: SpringProxyUtils { public static ProxyFactory findJdkDynamicProxyFactory(Object proxy) { InvocationHandler h = Proxy.getInvocationHandler(proxy); ConfigurablePropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(h); return (ProxyFactory) accessor.getPropertyValue("advised"); } static T getRealTarget(Object proxy); static boolean isMultipleProxy(Object proxy); static ProxyFactory findJdkDynamicProxyFactory(Object proxy); static ProxyFactory findCglibProxyFactory(Object proxy); static boolean isTransactional(Object proxy); static void removeTransactional(Object proxy); static boolean isAsync(Object proxy); static void removeAsync(Object proxy); }### Answer: @Test public void testFindJdkDynamicProxyFactory() { ProxyFactory proxyFactory = new ProxyFactory(); Bmw bmw = new Bmw(); TargetSource targetSource = new SingletonTargetSource(bmw); proxyFactory.setTargetSource(targetSource); Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(bmw.getClass()); for (Class<?> targetInterface : targetInterfaces) { proxyFactory.addInterface(targetInterface); } Advisor[] advisors = new Advisor[1]; advisors[0] = advisorAdapterRegistry.wrap(new TestMethodInterceptor()); proxyFactory.addAdvisors(advisors); Car proxy = (Car) proxyFactory.getProxy(); SpringProxyUtils.findJdkDynamicProxyFactory(proxy); }
### Question: ServiceLocator implements ApplicationContextAware { public static ApplicationContext getFactory() { Assert.notNull(factory, "没有注入spring factory"); return factory; } static ApplicationContext getFactory(); static void setFactory(ApplicationContext context); @SuppressWarnings("unchecked") static T getBean(String beanName); static Map<String, T> getBeansOfType(Class<T> type); static Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit); static T getBean(Class<T> clazz); static boolean containsBean(String name); static boolean isSingleton(String name); static Class<?> getType(String name); static String[] getAliases(String name); void setApplicationContext(ApplicationContext applicationContext); }### Answer: @Test public void testGetFactory() { try { ServiceLocator.getBean("test"); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "没有注入spring factory"); } }
### Question: PlaceholderResolver { public String doParse(String strVal) { if (strVal == null) { return null; } return parseStringValue(strVal, visitedPlaceholders); } PlaceholderResolver(PlaceholderResolved resolvedInterceptor); String doParse(String strVal); boolean hasPlaceHolder(String strVal); static boolean substringMatch(CharSequence str, int index, CharSequence substring); void setPlaceholderPrefix(String placeholderPrefix); void setPlaceholderSuffix(String placeholderSuffix); static final String DEFAULT_PLACEHOLDER_PREFIX; static final String DEFAULT_PLACEHOLDER_SUFFIX; }### Answer: @Test public void testDoParse() { final Map<String, String> placeholderVals = new HashMap<>(5); placeholderVals.put("key1", "china"); placeholderVals.put("key2", "3"); placeholderVals.put("key3", "beijin"); String testStr = "hello ${key1}"; PlaceholderResolver resolver = new PlaceholderResolver(placeholderVals::get); resolver.setPlaceholderPrefix("${"); resolver.setPlaceholderSuffix("}"); assertEquals(resolver.doParse(testStr), "hello china"); testStr = "hello ${key${key2}}"; assertEquals(resolver.doParse(testStr), "hello beijin"); }
### Question: EasyUITreeServiceImpl implements EasyUITreeService<T> { private EasyUITreeModel findModel(List<T> list, Function<T, EasyUITreeModel> mc) { if (null == list) { throw new RuntimeException("没有EasyUI菜单"); } Map<Integer, EasyUITreeModel> p = new HashMap<>(list.size() + 1); EasyUITreeModel root = new EasyUITreeModel(); root.setId(0); p.put(root.getId(), root); findModel(list, p, mc); root.setId(null); return root; } @Override List<EasyUITreeModel> findChildren(List<T> list, Function<T, EasyUITreeModel> mc); void setCheck(List<EasyUITreeModel> easyUITreeModels); }### Answer: @Test public void testFindModel() { List<EasyUITreeModel> json = service.findChildren(getList(), p -> { EasyUITreeModel m = new EasyUITreeModel(); m.setId(p.getParamId()); m.setText(p.getParamName()); m.setPid(p.getParamType()); return m; }); assertNotNull(json); }
### Question: ExcelRead { public static <E> void read(InputStream inputStream, ExcelReadDeal<E> deal) { Objects.requireNonNull(inputStream); Objects.requireNonNull(deal); try (Workbook wb = WorkbookFactory.create(inputStream)) { for (int i = 0; i < wb.getNumberOfSheets(); i++) { Sheet sheet = wb.getSheetAt(i); if (null == sheet) { continue; } int tmp = deal.getBatchCount(); int index = 0; List<E> l = new ArrayList<>(tmp); for (Row row : sheet) { ++index; if (index <= deal.skipLine()) { continue; } E o = deal.dealBean(row); if (null != o) { l.add(o); if (index % tmp == 0) { deal.dealBatchBean(l); l = new ArrayList<>(tmp); } } } if (!l.isEmpty()) { deal.dealBatchBean(l); } } } catch (Exception e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (IOException e) { inputStream = null; } } } static void read(InputStream inputStream, ExcelReadDeal<E> deal); }### Answer: @Test public void testRead() { ExcelRead.read(ExcelReadTest.class.getResourceAsStream("/a.xls"), new ExcelReadDeal<ExcelReadDto>() { @Override public ExcelReadDto dealBean(Row row) { ExcelReadDto dto = new ExcelReadDto(); dto.setId(new BigDecimal(row.getCell(0).toString()).longValue()); dto.setName(row.getCell(1).toString()); dto.setAge(Integer.valueOf(row.getCell(2).toString())); return dto; } @Override public void dealBatchBean(List<ExcelReadDto> list) { Assert.assertEquals("name1", list.get(0).getName()); Assert.assertEquals("name2", list.get(1).getName()); Assert.assertEquals("name3", list.get(2).getName()); } }); }
### Question: BigDecimalUtil { public static double add(double v1, double v2) { return add(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale); static double sub(double v1, double v2); static double sub(double v1, double v2, int scale); static BigDecimal sub(BigDecimal v1, BigDecimal v2); static BigDecimal sub(BigDecimal v1, BigDecimal v2, int scale); static double mul(double v1, double v2); static double mul(double v1, double v2, int scale); static BigDecimal mul(BigDecimal v1, BigDecimal v2); static BigDecimal mul(BigDecimal v1, BigDecimal v2, int scale); static double div(double v1, double v2); static double div(double v1, double v2, int scale); static BigDecimal div(BigDecimal v1, BigDecimal v2); static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale); }### Answer: @Test public void testAdd() { assertEquals(BigDecimalUtil.add(123, 234), 357.0); } @Test public void testAdd1() { BigDecimal v1 = new BigDecimal(123); BigDecimal v2 = new BigDecimal(234); assertEquals(BigDecimalUtil.add(v1, v2), new BigDecimal("357.00")); }
### Question: BigDecimalUtil { public static double sub(double v1, double v2) { return sub(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale); static double sub(double v1, double v2); static double sub(double v1, double v2, int scale); static BigDecimal sub(BigDecimal v1, BigDecimal v2); static BigDecimal sub(BigDecimal v1, BigDecimal v2, int scale); static double mul(double v1, double v2); static double mul(double v1, double v2, int scale); static BigDecimal mul(BigDecimal v1, BigDecimal v2); static BigDecimal mul(BigDecimal v1, BigDecimal v2, int scale); static double div(double v1, double v2); static double div(double v1, double v2, int scale); static BigDecimal div(BigDecimal v1, BigDecimal v2); static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale); }### Answer: @Test public void testSub() { assertEquals(BigDecimalUtil.sub(123, 234), -111.0); } @Test public void testSub1() { BigDecimal v1 = new BigDecimal(123); BigDecimal v2 = new BigDecimal(234); assertEquals(BigDecimalUtil.sub(v1, v2), new BigDecimal("-111.00")); }
### Question: BigDecimalUtil { public static double mul(double v1, double v2) { return mul(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale); static double sub(double v1, double v2); static double sub(double v1, double v2, int scale); static BigDecimal sub(BigDecimal v1, BigDecimal v2); static BigDecimal sub(BigDecimal v1, BigDecimal v2, int scale); static double mul(double v1, double v2); static double mul(double v1, double v2, int scale); static BigDecimal mul(BigDecimal v1, BigDecimal v2); static BigDecimal mul(BigDecimal v1, BigDecimal v2, int scale); static double div(double v1, double v2); static double div(double v1, double v2, int scale); static BigDecimal div(BigDecimal v1, BigDecimal v2); static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale); }### Answer: @Test public void testMul() { assertEquals(BigDecimalUtil.mul(10, 23), 230.0); } @Test public void testMul1() { BigDecimal v1 = new BigDecimal(10); BigDecimal v2 = new BigDecimal(23); assertEquals(BigDecimalUtil.mul(v1, v2), new BigDecimal("230.00")); }
### Question: BigDecimalUtil { public static double div(double v1, double v2) { return div(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale); static double sub(double v1, double v2); static double sub(double v1, double v2, int scale); static BigDecimal sub(BigDecimal v1, BigDecimal v2); static BigDecimal sub(BigDecimal v1, BigDecimal v2, int scale); static double mul(double v1, double v2); static double mul(double v1, double v2, int scale); static BigDecimal mul(BigDecimal v1, BigDecimal v2); static BigDecimal mul(BigDecimal v1, BigDecimal v2, int scale); static double div(double v1, double v2); static double div(double v1, double v2, int scale); static BigDecimal div(BigDecimal v1, BigDecimal v2); static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale); }### Answer: @Test public void testDiv() { assertEquals(BigDecimalUtil.div(23, 10), 2.3); } @Test public void testDiv1() { BigDecimal v1 = new BigDecimal(23); BigDecimal v2 = new BigDecimal(10); assertEquals(BigDecimalUtil.div(v1, v2), new BigDecimal("2.30")); } @Test public void testDiv2() { BigDecimal v1 = new BigDecimal(23); BigDecimal v2 = new BigDecimal(0); assertEquals(BigDecimalUtil.div(v1, v2), BigDecimal.ZERO); }
### Question: JsonUtil { public static String toJson(Object obj, String... ignoreProperties) { return gson(ignoreProperties).toJson(obj); } static T fromJson(String json, Class<T> clazz); static String toJson(Object obj, String... ignoreProperties); static Gson gson(String... ignoreProperties); static Gson gson1(String... ignoreProperties); static ExclusionStrategy getExclusionStrategy(String... ignoreProperties); }### Answer: @Test public void testToJson() { User user = new User(); user.setName("名称"); user.setDesc("测试"); user.setAge(27); assertEquals("{\"name\":\"名称\",\"age\":27}", JsonUtil.toJson(user, "desc")); }
### Question: MapDistance { public static double getDistance(double lng1, double lat1, double lng2, double lat2) { double radLat1 = rad(lng1); double radLat2 = rad(lng2); double difference = radLat1 - radLat2; double mdifference = rad(lat1) - rad(lat2); double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(mdifference / 2), 2))); distance = distance * EARTH_RADIUS; distance = Math.round(distance * 10000) / 10000; return distance; } static double getDistance(double lng1, double lat1, double lng2, double lat2); static Map<String, Double> getAround(double lng, double lat, double raidusMile); static final double EARTH_RADIUS; }### Answer: @Test public void testGetDistance() { assertEquals(MapDistance.getDistance(116.327396, 39.938416, 120.332685, 37.617222), 462.0); assertEquals(MapDistance.getDistance(120.332685, 37.617222, 116.327396, 39.938416), 462.0); }
### Question: MapDistance { public static Map<String, Double> getAround(double lng, double lat, double raidusMile) { Map<String, Double> map = new HashMap<>(); double degree = (24901 * 1609) / 360.0; double mpdLng = Double.parseDouble((degree * Math.cos(lng * (Math.PI / 180)) + "").replace("-", "")); double dpmLng = 1 / mpdLng; double radiusLng = dpmLng * raidusMile; double minLat = lat - radiusLng; double maxLat = lat + radiusLng; double dpmLat = 1 / degree; double radiusLat = dpmLat * raidusMile; double minLng = lng - radiusLat; double maxLng = lng + radiusLat; map.put("minLat", minLat); map.put("maxLat", maxLat); map.put("minLng", minLng); map.put("maxLng", maxLng); return map; } static double getDistance(double lng1, double lat1, double lng2, double lat2); static Map<String, Double> getAround(double lng, double lat, double raidusMile); static final double EARTH_RADIUS; }### Answer: @Test public void testGetAround() { Map<String, Double> map = MapDistance.getAround(117.11811, 36.68484, 13000); assertEquals(map.get("maxLat"), Double.valueOf("36.941095784459634")); assertEquals(map.get("minLat"), Double.valueOf("36.42858421554037")); assertEquals(map.get("minLng"), Double.valueOf("117.001301883613")); assertEquals(map.get("maxLng"), Double.valueOf("117.234918116387")); }
### Question: Num62 { public static String longToN62(long l) { return longToNBuf(l, N62_CHARS).reverse().toString(); } static String longToN62(long l); static String longToN36(long l); static String longToN62(long l, int length); static String longToN36(long l, int length); static long n62ToLong(String n62); static long n36ToLong(String n36); static final char[] N62_CHARS; static final char[] N36_CHARS; static final int LONG_N36_LEN; static final int LONG_N62_LEN; }### Answer: @Test public void testLongToN62() throws Exception { assertEquals(Num62.longToN62(Long.MAX_VALUE), "AzL8n0Y58m7"); }
### Question: MapUtil { public static <K, V> MapPlain<K, V> build() { return new MapPlain<>(); } static MapPlain<K, V> build(); static MapPlain<K, V> build(int cap); static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties); static Map<String, Object> toMap(Object o, String... ignoreProperties); static void toObject(Map<String, Object> source, Object target, String... ignoreProperties); static List<Map<String, Object>> mapConvertToList(Map<K, V> map); static List<Map<String, Object>> mapConvertToList(Map<K, V> map, Object defaultValue); }### Answer: @Test public void testMapPlainPut() { Map<String, Object> map = MapUtil.<String, Object>build(1).put("name", "name").get(); assertEquals(map.get("name"), "name"); } @Test public void testMapPlainPutAll() { Map<String, Object> mapAll = new HashMap<>(); mapAll.put("name", "name"); mapAll.put("age", 25); Map<String, Object> map = MapUtil.<String, Object>build().putAll(mapAll).get(); assertEquals(map.get("name"), "name"); assertEquals(map.get("age"), 25); } @Test public void testMapPlainPutAllEmpty() { Map<String, Object> mapAll = new HashMap<>(); Map<String, Object> map = MapUtil.<String, Object>build().putAll(mapAll).get(); assertEquals(map.size(), 0); }
### Question: MapUtil { public static void toObject(Map<String, Object> source, Object target, String... ignoreProperties) { PropertyDescriptor[] ts = ReflectUtil.getPropertyDescriptors(target); List<String> ignoreList = (ignoreProperties != null && ignoreProperties.length > 0) ? Arrays.asList(ignoreProperties) : null; for (PropertyDescriptor t : ts) { String name = t.getName(); if (ignoreList == null || !ignoreList.contains(name)) { Object value; if (null != source && (value = source.get(name)) != null) { ReflectUtil.setValueByField(target, name, value); } } } } static MapPlain<K, V> build(); static MapPlain<K, V> build(int cap); static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties); static Map<String, Object> toMap(Object o, String... ignoreProperties); static void toObject(Map<String, Object> source, Object target, String... ignoreProperties); static List<Map<String, Object>> mapConvertToList(Map<K, V> map); static List<Map<String, Object>> mapConvertToList(Map<K, V> map, Object defaultValue); }### Answer: @Test public void testToObject() { Map<String, Object> params = new HashMap<>(); params.put("name", "name"); params.put("age", 25); A a = new A(); MapUtil.toObject(params, a); assertEquals(a.getName(), "name"); assertEquals(a.getAge(), 25); }
### Question: MapUtil { public static <K, V> List<Map<String, Object>> mapConvertToList(Map<K, V> map) { return mapConvertToList(map, null); } static MapPlain<K, V> build(); static MapPlain<K, V> build(int cap); static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties); static Map<String, Object> toMap(Object o, String... ignoreProperties); static void toObject(Map<String, Object> source, Object target, String... ignoreProperties); static List<Map<String, Object>> mapConvertToList(Map<K, V> map); static List<Map<String, Object>> mapConvertToList(Map<K, V> map, Object defaultValue); }### Answer: @Test public void testEmptyMapConvertToList() { Map<String, Object> map = new HashMap<>(); List<Map<String, Object>> list = MapUtil.mapConvertToList(map); assertEquals(list.size(), 0); } @Test public void testMapConvertToList() { Map<String, Object> map = new HashMap<>(); map.put("name", "name"); map.put("age", 25); List<Map<String, Object>> list = MapUtil.mapConvertToList(map); assertEquals(list.size(), 2); assertEquals(list.get(0).get("value"), "name"); assertEquals(list.get(1).get("value"), "age"); } @Test public void testMapConvertToListDefaultValue() { Map<String, Object> map = new HashMap<>(); map.put("name", "name"); map.put("age", 25); List<Map<String, Object>> list = MapUtil.mapConvertToList(map, "age"); assertTrue((Boolean) list.get(1).get("selected")); }
### Question: WebUtil { public static String guessContentType(String fileName) { return URLConnection.getFileNameMap().getContentTypeFor(fileName); } static String guessContentType(String fileName); static String encodeContentDisposition(String userAgent, String fileName); }### Answer: @Test public void testGuessContentType() throws Exception { assertEquals(WebUtil.guessContentType("1.jpg"), "image/jpeg"); assertNull(WebUtil.guessContentType("2.xlsx")); assertEquals(WebUtil.guessContentType("3.png"), "image/png"); assertNull(WebUtil.guessContentType("4.csv")); assertEquals(WebUtil.guessContentType("5.zip"), "application/zip"); assertEquals(WebUtil.guessContentType("6.txt"), "text/plain"); assertNull(WebUtil.guessContentType("7.docx")); assertNull(WebUtil.guessContentType("8.doc")); assertNull(WebUtil.guessContentType("9.ppt")); assertEquals(WebUtil.guessContentType("10.pdf"), "application/pdf"); assertNull(WebUtil.guessContentType("11.xls")); }
### Question: WebUtil { public static String encodeContentDisposition(String userAgent, String fileName) { try { String lowUserAgent = userAgent.toLowerCase(); if (lowUserAgent.contains("msie") || lowUserAgent.contains("trident")) { return "attachment;filename=" + StringUtils.replace(URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()), "+", "%20"); } else if (lowUserAgent.contains("opera")) { return "attachment;filename*=UTF-8''" + fileName; } else if (lowUserAgent.contains("safari") || lowUserAgent.contains("applewebkit") || lowUserAgent.contains("mozilla")) { return "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); } else { return "attachment;filename=" + MimeUtility.encodeWord(fileName); } } catch (UnsupportedEncodingException e) { String charset = MimeUtility.getDefaultJavaCharset(); throw new RuntimeException("default java charset [" + charset + "]", e); } } static String guessContentType(String fileName); static String encodeContentDisposition(String userAgent, String fileName); }### Answer: @Test public void testEncodeContentDisposition() throws Exception { assertEquals(MimeUtility.encodeWord("1.jpg"), "1.jpg"); }
### Question: SystemPropertyUtil { public static String get(String key) { return get(key, null); } private SystemPropertyUtil(); static boolean contains(String key); static String get(String key); static String get(final String key, String def); static int getInt(String key, int def); }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testGetWithKeyNull() { SystemPropertyUtil.get(null, null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testGetWithKeyEmpty() { SystemPropertyUtil.get("", null); } @Test public void testGetDefaultValueWithPropertyNull() { assertEquals("default", SystemPropertyUtil.get("key", "default")); } @Test public void testGetPropertyValue() { System.setProperty("key", "value"); assertEquals("value", SystemPropertyUtil.get("key")); }
### Question: SystemPropertyUtil { public static int getInt(String key, int def) { String value = get(key); if (value == null) { return def; } value = value.trim(); try { return Integer.parseInt(value); } catch (Exception e) { } return def; } private SystemPropertyUtil(); static boolean contains(String key); static String get(String key); static String get(final String key, String def); static int getInt(String key, int def); }### Answer: @Test public void getIntDefaultValueWithPropertyNull() { assertEquals(1, SystemPropertyUtil.getInt("key", 1)); } @Test public void getIntWithPropertValueIsInt() { System.setProperty("key", "123"); assertEquals(123, SystemPropertyUtil.getInt("key", 1)); } @Test public void getIntDefaultValueWithPropertValueIsNotInt() { System.setProperty("key", "NotInt"); assertEquals(1, SystemPropertyUtil.getInt("key", 1)); }
### Question: DbManager { public Connection getConnection() { try { Class.forName(this.driveName); return DriverManager.getConnection(this.url, this.user, this.password); } catch (ClassNotFoundException e) { throw new RuntimeException("load database class exception : " + e.getMessage(), e); } catch (SQLException e) { throw new RuntimeException("get database connection : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer: @Test public void testGetConnection() { Connection connection = dbManager.getConnection(); assertNotNull(connection); dbManager.close(connection); }
### Question: DbManager { public PreparedStatement getPreparedStatement(Connection connection, String sql) { try { return connection.prepareStatement(sql); } catch (SQLException e) { throw new RuntimeException("get PrepareStatement exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer: @Test public void testGetPreparedStatement() { Connection connection = dbManager.getConnection(); PreparedStatement preparedStatement = dbManager.getPreparedStatement(connection, "select count(1) as count from tb_user"); assertNotNull(preparedStatement); dbManager.close(connection, preparedStatement, null); }
### Question: DbManager { public ResultSet getResultSet(PreparedStatement preparedStatement) { try { return preparedStatement.executeQuery(); } catch (SQLException e) { throw new RuntimeException("get ResultSet exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer: @Test public void testGetResultSet() throws Exception { Connection connection = dbManager.getConnection(); PreparedStatement preparedStatement = dbManager.getPreparedStatement(connection, "select count(1) as count from tb_user"); ResultSet resultSet = dbManager.getResultSet(preparedStatement); assertNotNull(resultSet); resultSet.next(); long count = resultSet.getLong("count"); assertEquals(count, 0); dbManager.close(connection, preparedStatement, resultSet); }
### Question: DbManager { public ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName) { try { return getDatabaseMetaData(connection).getTables(localCatalog, localSchema, localTableName, null); } catch (SQLException e) { throw new RuntimeException("get tables exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer: @Test public void testGetTables() throws Exception { Connection connection = dbManager.getConnection(); ResultSet resultSet = dbManager.getTables(connection, "", "test_tmp", ""); assertNotNull(resultSet); int size = 0; while (resultSet.next()) { size++; } assertEquals(size, 1); dbManager.close(connection, null, resultSet); }
### Question: DbManager { public ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName) { try { return getDatabaseMetaData(connection).getColumns(localCatalog, localSchema, localTableName, null); } catch (SQLException e) { throw new RuntimeException("get columns exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer: @Test public void testGetColumns() throws Exception { Connection connection = dbManager.getConnection(); ResultSet resultSet = dbManager.getColumns(connection, "", "test_tmp", "tb_user"); assertNotNull(resultSet); int size = 0; while (resultSet.next()) { size++; } assertEquals(size, 6); dbManager.close(connection, null, resultSet); }