method2testcases
stringlengths
118
6.63k
### Question: IdUtils { public static byte[] toBytes(final UUID id) { if (id == null) { return null; } final byte[] buffer = new byte[16]; final ByteBuffer bb = ByteBuffer.wrap(buffer); bb.putLong(id.getMostSignificantBits()); bb.putLong(id.getLeastSignificantBits()); return buffer; } IdUtils(); static UUID create(); static UUID tryParse(final String str); static byte[] toBytes(final UUID id); static UUID fromBytes(final byte[] b); }### Answer: @Test public void testToBytesNull() { assertNull(IdUtils.toBytes(null)); } @Test public void testToBytes() { final UUID id = IdUtils.create(); final byte[] b1 = IdUtils.toBytes(id); final byte[] b2 = IdUtils.toBytes(id); assertNotNull(b1); assertEquals(16, b1.length); assertArrayEquals(b1, b2); }
### Question: IdUtils { public static UUID fromBytes(final byte[] b) { if (b == null || b.length != 16) { return null; } final ByteBuffer bb = ByteBuffer.wrap(b); return new UUID(bb.getLong(), bb.getLong()); } IdUtils(); static UUID create(); static UUID tryParse(final String str); static byte[] toBytes(final UUID id); static UUID fromBytes(final byte[] b); }### Answer: @Test public void testFromBytesNull() { assertNull(IdUtils.fromBytes(null)); } @Test public void testFromBytesTooShort() { assertNull(IdUtils.fromBytes(new byte[] { 1, 2, 3 })); } @Test public void testFromBytesTooLong() { assertNull(IdUtils.fromBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 })); }
### Question: Minitwit { @GET @Path("/public") public Response publicTimeline() { List<Message> messages = dao.getEntityManager() .createQuery("SELECT m FROM Message m ORDER BY m.id DESC", Message.class) .getResultList(); return renderTimeline(messages); } @GET Response timeline(); @GET @Path("/public") Response publicTimeline(); @GET @Path("/{handle}") Response userTimeline(@PathParam("handle") String handle); @GET @Path("/{handle}/follow") @RolesAllowed("user") Response followUser(@PathParam("handle") String handle); @POST @Path("/addmessage") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @RolesAllowed("user") Response addMessage(@FormParam("text") String text); @GET @Path("/login") View login(); @POST @Path("/login") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) Response login( @FormParam("email") String email, @FormParam("password") String password); @GET @Path("/logout") Response logout(); @GET @Path("/register") View register(); @POST @Path("/register") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) Response register( @FormParam("handle") String handle, @FormParam("email") String email, @FormParam("password") String password); static void main(String[] args); }### Answer: @Test public void testPublicTimeline() { final Response response = target("/public").request().get(); assertNotNull(response); assertEquals(200, response.getStatus()); final View view = (View) response.getEntity(); assertNotNull(view); assertEquals("timeline", view.getTemplateName()); assertNotNull(view.getModel().get("messages")); }
### Question: IOUtils { public static byte[] toByteArray(final InputStream input) throws IOException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); copy(input, output); return output.toByteArray(); } IOUtils(); static byte[] toByteArray(final InputStream input); static InputStream toInputStream(final String str, final Charset charset); static String toString(final InputStream input, final Charset charset); static void copy(final InputStream input, final OutputStream output); }### Answer: @Test public void testToByteArray() throws IOException { final InputStream input = new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8)); final byte[] output = IOUtils.toByteArray(input); assertEquals(4, output.length); }
### Question: IOUtils { public static InputStream toInputStream(final String str, final Charset charset) { return new ByteArrayInputStream(str.getBytes(charset)); } IOUtils(); static byte[] toByteArray(final InputStream input); static InputStream toInputStream(final String str, final Charset charset); static String toString(final InputStream input, final Charset charset); static void copy(final InputStream input, final OutputStream output); }### Answer: @Test public void testToInputStream() throws IOException { final InputStream input = IOUtils.toInputStream("test", StandardCharsets.UTF_8); assertEquals("test", IOUtils.toString(input, StandardCharsets.UTF_8)); }
### Question: OptionalClasses { OptionalClasses() { throw new UnsupportedOperationException(); } OptionalClasses(); static final Class<Annotation> SERVER_ENDPOINT; static final Class<?> ENTITY_MANAGER_FACTORY; static final Class<?> ENTITY_MANAGER; }### Answer: @Test public void testOptionalClasses() { assertNotNull(OptionalClasses.ENTITY_MANAGER); assertNull(OptionalClasses.SERVER_ENDPOINT); }
### Question: MinijaxPersistenceUnitInfo implements javax.persistence.spi.PersistenceUnitInfo { @Override public PersistenceUnitTransactionType getTransactionType() { throw new UnsupportedOperationException(); } MinijaxPersistenceUnitInfo(final String name, final String providerClassName); @Override String getPersistenceUnitName(); @Override String getPersistenceProviderClassName(); @Override List<String> getManagedClassNames(); @Override Properties getProperties(); @Override PersistenceUnitTransactionType getTransactionType(); @Override DataSource getJtaDataSource(); @Override DataSource getNonJtaDataSource(); @Override List<String> getMappingFileNames(); @Override List<URL> getJarFileUrls(); @Override URL getPersistenceUnitRootUrl(); @Override boolean excludeUnlistedClasses(); @Override SharedCacheMode getSharedCacheMode(); @Override ValidationMode getValidationMode(); @Override String getPersistenceXMLSchemaVersion(); @Override ClassLoader getClassLoader(); @Override void addTransformer(final ClassTransformer transformer); @Override ClassLoader getNewTempClassLoader(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testGetTransactionType() { pui.getTransactionType(); }
### Question: MinijaxPersistenceUnitInfo implements javax.persistence.spi.PersistenceUnitInfo { @Override public DataSource getJtaDataSource() { throw new UnsupportedOperationException(); } MinijaxPersistenceUnitInfo(final String name, final String providerClassName); @Override String getPersistenceUnitName(); @Override String getPersistenceProviderClassName(); @Override List<String> getManagedClassNames(); @Override Properties getProperties(); @Override PersistenceUnitTransactionType getTransactionType(); @Override DataSource getJtaDataSource(); @Override DataSource getNonJtaDataSource(); @Override List<String> getMappingFileNames(); @Override List<URL> getJarFileUrls(); @Override URL getPersistenceUnitRootUrl(); @Override boolean excludeUnlistedClasses(); @Override SharedCacheMode getSharedCacheMode(); @Override ValidationMode getValidationMode(); @Override String getPersistenceXMLSchemaVersion(); @Override ClassLoader getClassLoader(); @Override void addTransformer(final ClassTransformer transformer); @Override ClassLoader getNewTempClassLoader(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testGetJtaDataSource() { pui.getJtaDataSource(); }
### Question: MinijaxPersistenceUnitInfo implements javax.persistence.spi.PersistenceUnitInfo { @Override public DataSource getNonJtaDataSource() { throw new UnsupportedOperationException(); } MinijaxPersistenceUnitInfo(final String name, final String providerClassName); @Override String getPersistenceUnitName(); @Override String getPersistenceProviderClassName(); @Override List<String> getManagedClassNames(); @Override Properties getProperties(); @Override PersistenceUnitTransactionType getTransactionType(); @Override DataSource getJtaDataSource(); @Override DataSource getNonJtaDataSource(); @Override List<String> getMappingFileNames(); @Override List<URL> getJarFileUrls(); @Override URL getPersistenceUnitRootUrl(); @Override boolean excludeUnlistedClasses(); @Override SharedCacheMode getSharedCacheMode(); @Override ValidationMode getValidationMode(); @Override String getPersistenceXMLSchemaVersion(); @Override ClassLoader getClassLoader(); @Override void addTransformer(final ClassTransformer transformer); @Override ClassLoader getNewTempClassLoader(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testGetNonJtaDataSource() { pui.getNonJtaDataSource(); }
### Question: MinijaxPersistenceUnitInfo implements javax.persistence.spi.PersistenceUnitInfo { @Override public List<String> getMappingFileNames() { throw new UnsupportedOperationException(); } MinijaxPersistenceUnitInfo(final String name, final String providerClassName); @Override String getPersistenceUnitName(); @Override String getPersistenceProviderClassName(); @Override List<String> getManagedClassNames(); @Override Properties getProperties(); @Override PersistenceUnitTransactionType getTransactionType(); @Override DataSource getJtaDataSource(); @Override DataSource getNonJtaDataSource(); @Override List<String> getMappingFileNames(); @Override List<URL> getJarFileUrls(); @Override URL getPersistenceUnitRootUrl(); @Override boolean excludeUnlistedClasses(); @Override SharedCacheMode getSharedCacheMode(); @Override ValidationMode getValidationMode(); @Override String getPersistenceXMLSchemaVersion(); @Override ClassLoader getClassLoader(); @Override void addTransformer(final ClassTransformer transformer); @Override ClassLoader getNewTempClassLoader(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testGetMappingFileNames() { pui.getMappingFileNames(); }
### Question: MinijaxPersistenceUnitInfo implements javax.persistence.spi.PersistenceUnitInfo { @Override public List<URL> getJarFileUrls() { throw new UnsupportedOperationException(); } MinijaxPersistenceUnitInfo(final String name, final String providerClassName); @Override String getPersistenceUnitName(); @Override String getPersistenceProviderClassName(); @Override List<String> getManagedClassNames(); @Override Properties getProperties(); @Override PersistenceUnitTransactionType getTransactionType(); @Override DataSource getJtaDataSource(); @Override DataSource getNonJtaDataSource(); @Override List<String> getMappingFileNames(); @Override List<URL> getJarFileUrls(); @Override URL getPersistenceUnitRootUrl(); @Override boolean excludeUnlistedClasses(); @Override SharedCacheMode getSharedCacheMode(); @Override ValidationMode getValidationMode(); @Override String getPersistenceXMLSchemaVersion(); @Override ClassLoader getClassLoader(); @Override void addTransformer(final ClassTransformer transformer); @Override ClassLoader getNewTempClassLoader(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testGetJarFileUrls() { pui.getJarFileUrls(); }
### Question: MinijaxPersistenceUnitInfo implements javax.persistence.spi.PersistenceUnitInfo { @Override public URL getPersistenceUnitRootUrl() { throw new UnsupportedOperationException(); } MinijaxPersistenceUnitInfo(final String name, final String providerClassName); @Override String getPersistenceUnitName(); @Override String getPersistenceProviderClassName(); @Override List<String> getManagedClassNames(); @Override Properties getProperties(); @Override PersistenceUnitTransactionType getTransactionType(); @Override DataSource getJtaDataSource(); @Override DataSource getNonJtaDataSource(); @Override List<String> getMappingFileNames(); @Override List<URL> getJarFileUrls(); @Override URL getPersistenceUnitRootUrl(); @Override boolean excludeUnlistedClasses(); @Override SharedCacheMode getSharedCacheMode(); @Override ValidationMode getValidationMode(); @Override String getPersistenceXMLSchemaVersion(); @Override ClassLoader getClassLoader(); @Override void addTransformer(final ClassTransformer transformer); @Override ClassLoader getNewTempClassLoader(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testGetPersistenceUnitRootUrl() { pui.getPersistenceUnitRootUrl(); }
### Question: MinijaxPersistenceUnitInfo implements javax.persistence.spi.PersistenceUnitInfo { @Override public boolean excludeUnlistedClasses() { throw new UnsupportedOperationException(); } MinijaxPersistenceUnitInfo(final String name, final String providerClassName); @Override String getPersistenceUnitName(); @Override String getPersistenceProviderClassName(); @Override List<String> getManagedClassNames(); @Override Properties getProperties(); @Override PersistenceUnitTransactionType getTransactionType(); @Override DataSource getJtaDataSource(); @Override DataSource getNonJtaDataSource(); @Override List<String> getMappingFileNames(); @Override List<URL> getJarFileUrls(); @Override URL getPersistenceUnitRootUrl(); @Override boolean excludeUnlistedClasses(); @Override SharedCacheMode getSharedCacheMode(); @Override ValidationMode getValidationMode(); @Override String getPersistenceXMLSchemaVersion(); @Override ClassLoader getClassLoader(); @Override void addTransformer(final ClassTransformer transformer); @Override ClassLoader getNewTempClassLoader(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void testExcludeUnlistedClasses() { pui.excludeUnlistedClasses(); }
### Question: Minitwit { @GET @Path("/{handle}/follow") @RolesAllowed("user") public Response followUser(@PathParam("handle") String handle) { security.getUserPrincipal().following.add(dao.readByHandle(User.class, handle)); dao.update(security.getUserPrincipal()); return Response.seeOther(URI.create("/")).build(); } @GET Response timeline(); @GET @Path("/public") Response publicTimeline(); @GET @Path("/{handle}") Response userTimeline(@PathParam("handle") String handle); @GET @Path("/{handle}/follow") @RolesAllowed("user") Response followUser(@PathParam("handle") String handle); @POST @Path("/addmessage") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @RolesAllowed("user") Response addMessage(@FormParam("text") String text); @GET @Path("/login") View login(); @POST @Path("/login") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) Response login( @FormParam("email") String email, @FormParam("password") String password); @GET @Path("/logout") Response logout(); @GET @Path("/register") View register(); @POST @Path("/register") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) Response register( @FormParam("handle") String handle, @FormParam("email") String email, @FormParam("password") String password); static void main(String[] args); }### Answer: @Test public void testFollowUser() throws Exception { assertFalse(alice.following.contains(bob)); final Response response = target("/bob/follow").request().cookie(aliceCookie).get(); assertNotNull(response); assertEquals(303, response.getStatus()); try (final MinijaxRequestContext ctx = createRequestContext()) { final Dao dao = ctx.getResource(Dao.class); assertTrue(dao.read(User.class, alice.getId()).following.contains(bob)); } }
### Question: CharEscapeUtil { public static String escape(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '=' || c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':' || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~' || c == '*' || c == '?' || c == '|' || c == '&' || c == '/') { sb.append('\\'); } sb.append(c); } return sb.toString(); } CharEscapeUtil( Writer w,int features); CharEscapeUtil( ); CharEscapeUtil( Writer w); Object getOutputTarget(); int getOutputBuffered(); boolean canWriteFormattedNumbers(); void writeString(String text,boolean flush); String toString(); void _writeString(String text); void _writeString2(final int len); static String escape(String s); }### Answer: @Test public void escape(){ StringWriter writer = new StringWriter(); CharEscapeUtil charEscapeUtil = new CustomCharEscapeUtil(writer); charEscapeUtil.writeString("/+\"\\", true); System.out.println(writer.toString()); }
### Question: ManageHousekeepingService implements ChannelEventListener { @Override public void onChannelClose(String remoteAddr, Channel channel) { this.namesrvController.getRouteInfoManager().onChannelDestroy(remoteAddr, channel); } ManageHousekeepingService(NameSrvController namesrvController); @Override void onChannelConnect(String remoteAddr, Channel channel); @Override void onChannelClose(String remoteAddr, Channel channel); @Override void onChannelException(String remoteAddr, Channel channel); @Override void onChannelIdle(String remoteAddr, Channel channel); }### Answer: @Test public void testOnChannelClose() { brokerHousekeepingService.onChannelClose("127.0.0.1:9876", null); }
### Question: ManageHousekeepingService implements ChannelEventListener { @Override public void onChannelException(String remoteAddr, Channel channel) { this.namesrvController.getRouteInfoManager().onChannelDestroy(remoteAddr, channel); } ManageHousekeepingService(NameSrvController namesrvController); @Override void onChannelConnect(String remoteAddr, Channel channel); @Override void onChannelClose(String remoteAddr, Channel channel); @Override void onChannelException(String remoteAddr, Channel channel); @Override void onChannelIdle(String remoteAddr, Channel channel); }### Answer: @Test public void testOnChannelException() { brokerHousekeepingService.onChannelException("127.0.0.1:9876", null); }
### Question: ManageHousekeepingService implements ChannelEventListener { @Override public void onChannelIdle(String remoteAddr, Channel channel) { this.namesrvController.getRouteInfoManager().onChannelDestroy(remoteAddr, channel); } ManageHousekeepingService(NameSrvController namesrvController); @Override void onChannelConnect(String remoteAddr, Channel channel); @Override void onChannelClose(String remoteAddr, Channel channel); @Override void onChannelException(String remoteAddr, Channel channel); @Override void onChannelIdle(String remoteAddr, Channel channel); }### Answer: @Test public void testOnChannelIdle() { brokerHousekeepingService.onChannelException("127.0.0.1:9876", null); }
### Question: RouteInfoManager { public byte[] getGtsManagerInfo() { LiveManageInfo liveManageInfo = new LiveManageInfo(); List<GtsManageLiveAddr> brokerLiveAddrs=this.liveTable.values().stream(). filter(item->Objects.nonNull(item)). map(item-> new GtsManageLiveAddr(item.getGtsManageId(), item.getLastUpdateTimestamp(),item.getGtsManageName(), item.getGtsManageAddr())). collect(Collectors.toList()); liveManageInfo.setGtsManageLiveAddrs(brokerLiveAddrs); return liveManageInfo.encode(); } RouteInfoManager(); byte[] getGtsManagerInfo(); RegisterBrokerResult registerBroker( String brokerAddr, String brokerName, long brokerId, TopicConfigSerializeWrapper topicConfigWrapper, Channel channel); void unregisterBroker( String brokerAddr, String brokerName, long brokerId); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); }### Answer: @Test public void testGetAllClusterInfo() { byte[] clusterInfo = routeInfoManager.getGtsManagerInfo(); assertThat(clusterInfo).isNotNull(); }
### Question: DefaultRequestProcessor implements NettyRequestProcessor { @Override public RemotingCommand processRequest(ChannelHandlerContext ctx,RemotingCommand request) throws RemotingCommandException { if (log.isDebugEnabled()) { log.debug("receive request, {} {} {}", request.getCode(), RemotingHelper.parseChannelRemoteAddr(ctx.channel()), request); } switch (request.getCode()) { case RequestCode.REGISTER_MANAGE: return this.registerBrokerWithFilterServer(ctx, request); case RequestCode.UNREGISTER_MANAGE: return this.unregisterBroker(ctx, request); case RequestCode.GET_MANAGE_CLUSTER_INFO: return this.getBrokerClusterInfo(ctx, request); default: break; } return null; } DefaultRequestProcessor(NameSrvController namesrvController); @Override RemotingCommand processRequest(ChannelHandlerContext ctx,RemotingCommand request); @Override boolean rejectRequest(); RemotingCommand registerBrokerWithFilterServer(ChannelHandlerContext ctx, RemotingCommand request); RemotingCommand unregisterBroker(ChannelHandlerContext ctx,RemotingCommand request); }### Answer: @Test public void testProcessRequest_UnregisterBroker() throws RemotingCommandException, NoSuchFieldException, IllegalAccessException { ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); when(ctx.channel()).thenReturn(null); RemotingCommand regRequest = genSampleRegisterCmd(true); defaultRequestProcessor.processRequest(ctx, regRequest); RemotingCommand unregRequest = genSampleRegisterCmd(false); RemotingCommand unregResponse = defaultRequestProcessor.processRequest(ctx, unregRequest); assertThat(unregResponse.getCode()).isEqualTo(ResponseCode.SUCCESS); assertThat(unregResponse.getRemark()).isNull(); RouteInfoManager routes = namesrvController.getRouteInfoManager(); Field brokerAddrTable = RouteInfoManager.class.getDeclaredField("brokerAddrTable"); brokerAddrTable.setAccessible(true); assertThat((Map) brokerAddrTable.get(routes)).isNotEmpty(); }
### Question: FrequentlyRelatedContentRequestParameterValidator implements SearchRequestParameterValidator { @Override public ValidationMessage validateParameters(Map<String, String> requestParameters) { String id = requestParameters.get(idParameter); if(id == null || id.length()==0) return INVALID_ID_MESSAGE; else return VALID_ID_MESSAGE; } FrequentlyRelatedContentRequestParameterValidator(Configuration configuration); @Override ValidationMessage validateParameters(Map<String, String> requestParameters); final ValidationMessage VALID_ID_MESSAGE; final ValidationMessage INVALID_ID_MESSAGE; }### Answer: @Test public void testMissingIdParameterReturnsInvalidMessage() { ValidationMessage message = validator.validateParameters(new HashMap<String, String>()); assertSame(message,validator.INVALID_ID_MESSAGE); } @Test public void testIdParameterReturnsValidMessage() { ValidationMessage message = validator.validateParameters(new HashMap<String, String>(){{ put(configuration.getKeyForFrequencyResultId(),"11111");}}); assertSame(message,validator.VALID_ID_MESSAGE); }
### Question: DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); @Override IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data); @PreDestroy void shutdown(); }### Answer: @Test public void testHandlerIsNotExecutedWithIndexingRequestWithTooManyProducts() { String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ \"1\",\"2\",\"3\",\"4\",\"5\" ]"+ "}"; processor.processRequest(configuation, ByteBuffer.wrap(json.getBytes())); assertEquals(0,handler.getNumberOfCalls()); } @Test public void testHandlerIsNotExecutedWithIndexingRequestWithNoProducts() { String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ ]"+ "}"; processor.processRequest(configuation, ByteBuffer.wrap(json.getBytes())); assertEquals(0,handler.getNumberOfCalls()); } @Test public void testHandlerIsCalled() { String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ \"1\" ]"+ "}"; processor.processRequest(configuation, ByteBuffer.wrap(json.getBytes())); try { handler.getLatch().await(5000, TimeUnit.MILLISECONDS); } catch(Exception e) { fail("Failed waiting for disruptor to call the handler"); } assertEquals(1,handler.getNumberOfCalls()); } @Test public void testHandlerIsNotExecutedWithEmptyRequestData() { processor.processRequest(configuation, ByteBuffer.wrap(new byte[0])); assertEquals(0,handler.getNumberOfCalls()); }
### Question: RelatedItemSearch { public RelatedItemSearch copy(Configuration config) { RelatedItemSearch newCopy = new RelatedItemSearch(config,this.getAdditionalSearchCriteria().getNumberOfProperties()); newCopy.setRelatedItemId(this.relatedItemId); newCopy.setMaxResults(this.maxResults); newCopy.setRelatedItemSearchType(this.searchType); newCopy.setLookupKey(this.getLookupKey()); newCopy.setStartOfRequestNanos(this.getStartOfRequestNanos()); this.additionalSearchCriteria.copyTo(newCopy.additionalSearchCriteria); return newCopy; } RelatedItemSearch(Configuration config); RelatedItemSearch(Configuration config,int numberOfAdditionalSearchCriteria); void setMaxResults(int maxResults); int getMaxResults(); RelatedItemAdditionalProperties getAdditionalSearchCriteria(); void setRelatedItemId(String id); String getRelatedItemId(); RelatedItemInfoIdentifier getRelatedContentIdentifier(); RelatedItemSearchType getRelatedItemSearchType(); void setRelatedItemSearchType(RelatedItemSearchType searchType); RelatedItemSearch copy(Configuration config); void setLookupKey(SearchRequestLookupKey key); SearchRequestLookupKey getLookupKey(); long getStartOfRequestNanos(); void setStartOfRequestNanos(long startOfRequestNanos); static final String RESULTS_SET_SIZE_KEY; static final String ID_KEY; static final int RESULTS_SET_SIZE_KEY_LENGTH; static final int ID_KEY_LENGTH; }### Answer: @Test public void testCopy() { Configuration c = new SystemPropertiesConfiguration(); RelatedItemSearch searchObject = new RelatedItemSearch(new SystemPropertiesConfiguration()); searchObject.getAdditionalSearchCriteria().addProperty("key","value"); searchObject.getAdditionalSearchCriteria().addProperty("request","response"); searchObject.setRelatedItemId("I am a unique identifier"); searchObject.setMaxResults(1); searchObject.setRelatedItemSearchType(RelatedItemSearchType.FREQUENTLY_RELATED_WITH); RelatedItemSearchLookupKeyGenerator factory = new KeyFactoryBasedRelatedItemSearchLookupKeyGenerator(c,new SipHashSearchRequestLookupKeyFactory()); factory.setSearchRequestLookupKeyOn(searchObject); RelatedItemSearch copy = searchObject.copy(c); assertNotSame(copy,searchObject); assertEquals(copy.getMaxResults(),searchObject.getMaxResults()); assertEquals(copy.getRelatedItemId(),searchObject.getRelatedItemId()); assertEquals(copy.getRelatedItemSearchType(),searchObject.getRelatedItemSearchType()); assertEquals(copy.getLookupKey(),searchObject.getLookupKey()); assertEquals(copy.getAdditionalSearchCriteria().getNumberOfProperties(),searchObject.getAdditionalSearchCriteria().getNumberOfProperties()); assertEquals(copy.getAdditionalSearchCriteria().getPropertyName(0),searchObject.getAdditionalSearchCriteria().getPropertyName(0)); assertEquals(copy.getAdditionalSearchCriteria().getPropertyName(1),searchObject.getAdditionalSearchCriteria().getPropertyName(1)); assertEquals(copy.getAdditionalSearchCriteria().getPropertyValue(0),searchObject.getAdditionalSearchCriteria().getPropertyValue(0)); assertEquals(copy.getAdditionalSearchCriteria().getPropertyValue(1),searchObject.getAdditionalSearchCriteria().getPropertyValue(1)); assertNotSame(copy.getRelatedContentIdentifier(),searchObject.getRelatedContentIdentifier()); assertEquals(copy.getRelatedContentIdentifier().toString(),searchObject.getRelatedContentIdentifier().toString()); }
### Question: RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch createSearchObject() { return new RelatedItemSearch(configuration); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedItemSearch createSearchObject(); @Override void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties); @Override RelatedItemSearch newInstance(); }### Answer: @Test public void testCreateSearchObject() throws Exception { assertNotNull(factory.createSearchObject()); }
### Question: RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public RelatedItemSearch newInstance() { return createSearchObject(); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedItemSearch createSearchObject(); @Override void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties); @Override RelatedItemSearch newInstance(); }### Answer: @Test public void testNewInstance() throws Exception { assertNotNull(factory.newInstance()); }
### Question: RelatedItemSearchFactoryWithSearchLookupKeyFactory implements RelatedItemSearchFactory { @Override public void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties) { objectToPopulate.setStartOfRequestNanos(System.nanoTime()); String sizeKey = configuration.getRequestParameterForSize(); String idKey = configuration.getRequestParameterForId(); try { String size = properties.remove(sizeKey); if(size!=null) { objectToPopulate.setMaxResults(Integer.parseInt(size)); } else { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } } catch(NumberFormatException e) { objectToPopulate.setMaxResults(configuration.getDefaultNumberOfResults()); } objectToPopulate.setRelatedItemId(properties.remove(idKey)); RelatedItemAdditionalProperties props = objectToPopulate.getAdditionalSearchCriteria(); int maxPropertiesToCopy = Math.min(props.getMaxNumberOfAvailableProperties(),properties.size()); log.debug("max properties to copy {}, from properties {}",maxPropertiesToCopy,properties); int i=0; List<String> sortedParameters = new ArrayList<String>(properties.keySet()); Collections.sort(sortedParameters); for(String key : sortedParameters) { if(i==maxPropertiesToCopy) break; props.setProperty(key,properties.get(key),i++); } props.setNumberOfProperties(i); objectToPopulate.setRelatedItemSearchType(type); lookupKeyGenerator.setSearchRequestLookupKeyOn(objectToPopulate); } RelatedItemSearchFactoryWithSearchLookupKeyFactory(Configuration config, RelatedItemSearchLookupKeyGenerator lookupKeyGenerator); @Override RelatedItemSearch createSearchObject(); @Override void populateSearchObject(RelatedItemSearch objectToPopulate, RelatedItemSearchType type, Map<String, String> properties); @Override RelatedItemSearch newInstance(); }### Answer: @Test public void testPopulateSearchObject() throws Exception { String[][] props = new String[4][2]; props[0] = new String[]{"channel","one"}; props[1] = new String[]{"type","computer"}; props[2] = new String[]{"attributed_to","user1"}; props[3] = new String[]{config.getRequestParameterForSize(),"3"}; Map properties = getProperties("1",props); RelatedItemSearch objectToPopulate = factory.createSearchObject(); assertEquals(0,objectToPopulate.getMaxResults()); assertEquals("",objectToPopulate.getRelatedItemId()); assertEquals(0,objectToPopulate.getAdditionalSearchCriteria().getNumberOfProperties()); factory.populateSearchObject(objectToPopulate, RelatedItemSearchType.FREQUENTLY_RELATED_WITH,properties); assertEquals(3,objectToPopulate.getMaxResults()); assertEquals("1",objectToPopulate.getRelatedItemId()); assertEquals(3,objectToPopulate.getAdditionalSearchCriteria().getNumberOfProperties()); assertEquals("attributed_to",objectToPopulate.getAdditionalSearchCriteria().getPropertyName(0)); assertEquals("user1",objectToPopulate.getAdditionalSearchCriteria().getPropertyValue(0)); assertEquals("channel",objectToPopulate.getAdditionalSearchCriteria().getPropertyName(1)); assertEquals("one",objectToPopulate.getAdditionalSearchCriteria().getPropertyValue(1)); assertEquals("type",objectToPopulate.getAdditionalSearchCriteria().getPropertyName(2)); assertEquals("computer",objectToPopulate.getAdditionalSearchCriteria().getPropertyValue(2)); }
### Question: BasicRelatedItemIndexingMessageConverter implements RelatedItemIndexingMessageConverter { public static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length) { int len = length; RelatedItemInfo[][] idSets = new RelatedItemInfo[len][len]; for(int j = 0;j<len;j++) { idSets[0][j] = ids[j]; } for(int i=1;i<len;i++) { int k=0; for(int j=i;j<len;j++) { idSets[i][k++] = ids[j]; } for(int j=0;j<i;j++) { idSets[i][k++] = ids[j]; } } return idSets; } BasicRelatedItemIndexingMessageConverter(Configuration configuration); RelatedItem[] convertFrom(RelatedItemIndexingMessage message); static RelatedItemInfo[][] relatedIds(RelatedItemInfo[] ids, int length); }### Answer: @Test public void testRelatedItemIds() { RelatedItemInfo info1 = createRelatedItemInfoObj("1"); RelatedItemInfo info2 = createRelatedItemInfoObj("2"); RelatedItemInfo info3 = createRelatedItemInfoObj("3"); RelatedItemInfo info4 = createRelatedItemInfoObj("4"); RelatedItemInfo info5 = createRelatedItemInfoObj("5"); RelatedItemInfo[][] relatedItemIds = BasicRelatedItemIndexingMessageConverter.relatedIds(new RelatedItemInfo[]{info1, info2, info3, info4, info5}, 5); String[] concatIds = new String[relatedItemIds.length]; for(int i = 0;i<relatedItemIds.length;i++) { StringBuilder b = new StringBuilder(5); for(int j=0;j<relatedItemIds[i].length;j++) { b.append(relatedItemIds[i][j].getId().toString()); } concatIds[i] = b.toString(); } System.out.println(Arrays.toString(concatIds)); assertSame(info5, relatedItemIds[0][4]); assertSame(info1, relatedItemIds[1][4]); assertSame(info2, relatedItemIds[2][4]); assertSame(info3, relatedItemIds[3][4]); assertSame(info4, relatedItemIds[4][4]); assertEquals("12345",concatIds[0]); assertEquals("23451",concatIds[1]); assertEquals("34512",concatIds[2]); assertEquals("45123",concatIds[3]); assertEquals("51234",concatIds[4]); }
### Question: RelatedItemIndexingMessageFactory implements EventFactory<RelatedItemIndexingMessage> { @Override public RelatedItemIndexingMessage newInstance() { return new RelatedItemIndexingMessage(configuration); } RelatedItemIndexingMessageFactory(Configuration configuration); @Override RelatedItemIndexingMessage newInstance(); }### Answer: @Test public void testRelatedItemIndexingMessageWith4RelatedItems() throws Exception { System.setProperty(PROPNAME_MAX_NO_OF_RELATED_ITEMS_PER_INDEX_REQUEST,"4"); Configuration config = new SystemPropertiesConfiguration(); RelatedItemIndexingMessageFactory factory = new RelatedItemIndexingMessageFactory(config); RelatedItemIndexingMessage message = factory.newInstance(); assertEquals(4, message.getMaxNumberOfRelatedItemsAllowed()); } @Test public void testRelatedItemIndexingMessage() { System.setProperty(PROPNAME_MAX_NO_OF_RELATED_ITEMS_PER_INDEX_REQUEST,"2"); Configuration config = new SystemPropertiesConfiguration(); RelatedItemIndexingMessageFactory factory = new RelatedItemIndexingMessageFactory(config); RelatedItemIndexingMessage message = factory.newInstance(); assertEquals(2, message.getMaxNumberOfRelatedItemsAllowed()); } @Test public void testRelatedItemIndexingMessageRestrictsNumberOfProperties() { System.setProperty(PROPNAME_MAX_NO_OF_RELATED_ITEMS_PER_INDEX_REQUEST,"2"); System.setProperty(PROPNAME_MAX_NO_OF_RELATED_ITEM_PROPERTES,"3"); Configuration config = new SystemPropertiesConfiguration(); RelatedItemIndexingMessageFactory factory = new RelatedItemIndexingMessageFactory(config); RelatedItemIndexingMessage message = factory.newInstance(); assertEquals(2, message.getMaxNumberOfRelatedItemsAllowed()); assertEquals(3, message.getIndexingMessageProperties().getMaxNumberOfAvailableProperties()); }
### Question: RelatedItemReferenceMessageFactory implements EventFactory<RelatedItemReference> { @Override public RelatedItemReference newInstance() { return new RelatedItemReference(); } RelatedItemReferenceMessageFactory(); @Override RelatedItemReference newInstance(); }### Answer: @Test public void testCanCreateReferenceObject() { EventFactory<RelatedItemReference> factory = new RelatedItemReferenceMessageFactory(); assertNotNull(factory.newInstance()); assertTrue(factory.newInstance() instanceof RelatedItemReference); }
### Question: ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }### Answer: @Test public void parseFoundTwoAndOneNotFound() { Map<String,String> parsedDoc = ElasticSearchRelatedItemHttpGetRepository.processResults(FOUND_TWO_ONE_NOT_FOUND); assertTrue(parsedDoc.size()==2); assertTrue(parsedDoc.containsKey("1")); assertTrue(parsedDoc.containsKey("2")); assertTrue(parsedDoc.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); assertTrue(parsedDoc.get("2").contains("71a5120bdf4d998c2b043a681b1bd211")); } @Test public void parseFoundTwoSources() { Map<String,String> parsedDoc = ElasticSearchRelatedItemHttpGetRepository.processResults(FOUND_TWO); assertTrue(parsedDoc.size()==2); assertTrue(parsedDoc.containsKey("1")); assertTrue(parsedDoc.containsKey("2")); assertTrue(parsedDoc.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); assertTrue(parsedDoc.get("2").contains("71a5120bdf4d998c2b043a681b1bd211")); } @Test public void parseFoundOneAndOneWithError() { Map<String,String> parsedDoc = ElasticSearchRelatedItemHttpGetRepository.processResults(FOUND_ONE_ONE_WITH_ERROR); assertTrue(parsedDoc.size()==1); assertTrue(parsedDoc.containsKey("1")); assertTrue(parsedDoc.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); }
### Question: AHCHttpSniffAvailableNodes implements SniffAvailableNodes { @Override public Set<String> getAvailableNodes(String[] hosts) { Set<String> newHosts = new TreeSet<>(); for(String host : hosts) { HttpResult result = AHCRequestExecutor.executeSearch(client, HttpMethod.GET, host, NODE_ENDPOINT, null); if(result.getStatus()== HttpSearchExecutionStatus.OK) { newHosts.addAll(HostParsingUtil.parseAvailablePublishedHttpServerAddresses(result.getResult())); } } return newHosts; } AHCHttpSniffAvailableNodes(Configuration configuration); @Override Set<String> getAvailableNodes(String[] hosts); @Override void shutdown(); final String NODE_ENDPOINT; }### Answer: @Test public void testOneHostIsContacted() { Set<String> hosts = nodeSniffer.getAvailableNodes(new String[]{"http: assertEquals("Should be one host",1,hosts.size()); assertEquals("parsed host should be: http: wireMockRule1.verify(1,getRequestedFor(urlMatching(ConfigurationConstants.DEFAULT_ELASTIC_SEARCH_HTTP_NODE_SNIFFING_ENDPOINT))); wireMockRule2.verify(0,getRequestedFor(urlMatching(ConfigurationConstants.DEFAULT_ELASTIC_SEARCH_HTTP_NODE_SNIFFING_ENDPOINT))); } @Test public void testBothHostIsContacted() { Set<String> hosts = nodeSniffer.getAvailableNodes(new String[]{"http: assertEquals("Should be one host",3,hosts.size()); assertEquals("parsed host should be: http: assertEquals("parsed host should be: http: assertEquals("parsed host should be: http: wireMockRule1.verify(1,getRequestedFor(urlMatching(ConfigurationConstants.DEFAULT_ELASTIC_SEARCH_HTTP_NODE_SNIFFING_ENDPOINT))); wireMockRule2.verify(1,getRequestedFor(urlMatching(ConfigurationConstants.DEFAULT_ELASTIC_SEARCH_HTTP_NODE_SNIFFING_ENDPOINT))); }
### Question: NodeOrTransportBasedElasticSearchClientFactoryCreator implements ElasticSearchClientFactoryCreator { @Override public ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration) { ElasticSearchClientFactory factory; switch(configuration.getElasticSearchClientType()) { case NODE: factory = new NodeBasedElasticSearchClientFactory(configuration); break; case TRANSPORT: factory = new TransportBasedElasticSearchClientFactory(configuration); break; default: factory = new TransportBasedElasticSearchClientFactory(configuration); break; } return factory; } @Override ElasticSearchClientFactory getElasticSearchClientConnectionFactory(Configuration configuration); static final ElasticSearchClientFactoryCreator INSTANCE; }### Answer: @Test public void testTransportBasedClientCanConnectToES() { esServer = new ElasticSearchServer(clusterName,true); assertTrue("Unable to start in memory elastic search", esServer.isSetup()); System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_TRANSPORT_HOSTS, "localhost:" + esServer.getPort()); System.setProperty(ConfigurationConstants.PROPNAME_ES_CLIENT_TYPE, "transport"); Configuration config = new SystemPropertiesConfiguration(); try { ElasticSearchClientFactory factory = clientFactoryCreator.getElasticSearchClientConnectionFactory(config); Client c = factory.getClient(); assertEquals(config.getStorageClusterName(), c.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getClusterName().value()); assertNotNull(c.index(new IndexRequest("test", "test").source("name", "a")).actionGet().getId()); c.admin().indices().refresh(new RefreshRequest("test").force(true)).actionGet(); assertEquals(1,c.admin().indices().stats(new IndicesStatsRequest().indices("test")).actionGet().getTotal().docs.getCount()); } catch(Exception e) { fail("Unable to connect to elasticsearch: " + e.getMessage()); } try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void testNodeBasedClientCanConnectToES() { System.setProperty(ConfigurationConstants.PROPNAME_ES_CLIENT_TYPE, "node"); Configuration config = new SystemPropertiesConfiguration(); esServer = new ElasticSearchServer(clusterName,false); assertTrue("Unable to start in memory elastic search", esServer.isSetup()); try { ElasticSearchClientFactory factory = clientFactoryCreator.getElasticSearchClientConnectionFactory(config); Client c = factory.getClient(); assertEquals(config.getStorageClusterName(), c.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getClusterName().value()); assertNotNull(c.index(new IndexRequest("test", "test").source("name", "a")).actionGet().getId()); c.admin().indices().refresh(new RefreshRequest("test").force(true)).actionGet(); assertEquals(1, c.admin().indices().stats(new IndicesStatsRequest().indices("test")).actionGet().getTotal().docs.getCount()); } catch(Exception e) { e.printStackTrace(); fail("Unable to connect to elasticsearch: " + e.getMessage()); } }
### Question: RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler implements RelatedContentSearchRequestProcessorHandler { @Override public void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch) throws Exception { handleRequest(event,searchRequestExecutor[this.currentIndex++ & mask]); } RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(RelatedItemSearchResultsToResponseGateway contextStorage, RelatedItemSearchExecutor[] searchExecutor); @Override void onEvent(RelatedItemSearchRequest event, long sequence, boolean endOfBatch); void handleRequest(RelatedItemSearchRequest searchRequest, RelatedItemSearchExecutor searchExecutor); void shutdown(); }### Answer: @Test public void testCallingOnEventThatEachExecutorIsCalledInRoundRobinFashion() throws Exception { Configuration config = new SystemPropertiesConfiguration(); RelatedItemSearchExecutor executor1 = mock(RelatedItemSearchExecutor.class); RelatedItemSearchExecutor executor2 = mock(RelatedItemSearchExecutor.class); RelatedItemSearchExecutor executor3 = mock(RelatedItemSearchExecutor.class); RelatedItemSearchExecutor executor4 = mock(RelatedItemSearchExecutor.class); RelatedItemSearchResultsToResponseGateway gateway = mock(RelatedItemSearchResultsToResponseGateway.class); handler = new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,new RelatedItemSearchExecutor[]{executor1,executor2,executor3,executor4}); RelatedItemSearchRequest r1 = new RelatedItemSearchRequest(config); r1.getSearchRequest().setLookupKey(new SipHashSearchRequestLookupKey("1")); handler.onEvent(r1,1,true); r1.getSearchRequest().setLookupKey(new SipHashSearchRequestLookupKey("2")); handler.onEvent(r1,1,true); r1.getSearchRequest().setLookupKey(new SipHashSearchRequestLookupKey("3")); handler.onEvent(r1,1,true); r1.getSearchRequest().setLookupKey(new SipHashSearchRequestLookupKey("4")); handler.onEvent(r1,1,true); verify(executor1,times(1)).executeSearch(any(RelatedItemSearch.class)); verify(executor2,times(1)).executeSearch(any(RelatedItemSearch.class)); verify(executor3,times(1)).executeSearch(any(RelatedItemSearch.class)); verify(executor4,times(1)).executeSearch(any(RelatedItemSearch.class)); }
### 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: RoundRobinRelatedContentSearchRequestProcessorHandlerFactory implements RelatedContentSearchRequestProcessorHandlerFactory { @Override public RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ) { int numberOfSearchProcessors = config.getNumberOfSearchingRequestProcessors(); if(numberOfSearchProcessors==1) { log.debug("Creating Single Search Request Processor"); RelatedItemSearchExecutor searchExecutor = searchExecutorFactory.createSearchExecutor(gateway); return new DisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutor); } else { log.debug("Creating {} Search Request Processor",numberOfSearchProcessors); RelatedItemSearchExecutor[] searchExecutors = new RelatedItemSearchExecutor[numberOfSearchProcessors]; int i = numberOfSearchProcessors; while(i-- !=0) { searchExecutors[i] = searchExecutorFactory.createSearchExecutor(gateway); } return new RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler(gateway,searchExecutors); } } RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); @Override RelatedContentSearchRequestProcessorHandler createHandler(Configuration config, RelatedItemSearchResultsToResponseGateway gateway,RelatedItemSearchExecutorFactory searchExecutorFactory ); }### Answer: @Test public void testSingleRelatedContentSearchRequestProcessorHandlerIsCreated() { System.setProperty(ConfigurationConstants.PROPNAME_NUMBER_OF_SEARCHING_REQUEST_PROCESSORS,"1"); Configuration config = new SystemPropertiesConfiguration(); RoundRobinRelatedContentSearchRequestProcessorHandlerFactory factory = new RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); RelatedContentSearchRequestProcessorHandler handler = factory.createHandler(config,mock(RelatedItemSearchResultsToResponseGateway.class),mock(RelatedItemSearchExecutorFactory.class)); assertTrue(handler instanceof DisruptorBasedRelatedContentSearchRequestProcessorHandler); } @Test public void testRoundRobinRelatedContentSearchRequestProcessorHandlerIsCreated() { System.setProperty(ConfigurationConstants.PROPNAME_NUMBER_OF_SEARCHING_REQUEST_PROCESSORS,"2"); Configuration config = new SystemPropertiesConfiguration(); RoundRobinRelatedContentSearchRequestProcessorHandlerFactory factory = new RoundRobinRelatedContentSearchRequestProcessorHandlerFactory(); RelatedContentSearchRequestProcessorHandler handler = factory.createHandler(config,mock(RelatedItemSearchResultsToResponseGateway.class),mock(RelatedItemSearchExecutorFactory.class)); assertTrue(handler instanceof RoundRobinDisruptorBasedRelatedContentSearchRequestProcessorHandler); }
### 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: HttpAsyncSearchResponseContextHandler implements SearchResponseContextHandler<AsyncContext> { @Override public void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx) { AsyncContext ctx = sctx.getSearchResponseContext(); HttpServletResponse r = null; try { ServletRequest request = ctx.getRequest(); if(request==null) { return; } r = (HttpServletResponse)ctx.getResponse(); if(r!=null) { int statusCode = configuration.getResponseCode(results.getOutcomeType()); r.setStatus(statusCode); r.setContentType(mediaType); r.getWriter().write(resultsAsString); } } catch (IOException e) { if(r!=null) { r.setStatus(500); } } catch (IllegalStateException e) { log.warn("Async Context not available",e); } } HttpAsyncSearchResponseContextHandler(Configuration configuration); @Override void sendResults(String resultsAsString, String mediaType, SearchResultsEvent results, SearchResponseContext<AsyncContext> sctx); }### Answer: @Test public void testResultsSent() { Configuration configuration = mock(Configuration.class); when(configuration.getResponseCode(any(SearchResultsOutcome.class))).thenReturn(200); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); ServletOutputStream out = new ServletOutputStream() { public OutputStream getOutputStream() { return stream; } @Override public void write(int b) throws IOException { stream.write(b); } }; StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); try { when(response.getOutputStream()).thenReturn(out); } catch (IOException e) { e.printStackTrace(); } try { when(response.getWriter()).thenReturn(writer); } catch (IOException e) { e.printStackTrace(); } AsyncContext userResponse = getAsyncContext(request,response); SearchResponseContext responseHolder = new AsyncServletSearchResponseContext(userResponse,System.nanoTime()); SearchResponseContextHandler handler = getHandler(configuration); handler.sendResults("results","appplication/json",createSearchResultEvent(),responseHolder); String s = new String(stream.toByteArray()); if(s.length()==0) { s = stringWriter.toString(); } assertEquals("results",s); responseHolder.close(); verify(userResponse,times(1)).complete(); } @Test public void testResultsNotSentWhenRequestOrResponseNotAvailable() { Configuration configuration = mock(Configuration.class); when(configuration.getResponseCode(any(SearchResultsOutcome.class))).thenReturn(200); AsyncContext userResponse = getAsyncContext(null,null); SearchResponseContext responseHolder = new AsyncServletSearchResponseContext(userResponse,System.nanoTime()); SearchResponseContextHandler handler = getHandler(configuration); handler.sendResults("results","appplication/json",null,responseHolder); verify(configuration,times(0)).getResponseCode(any(SearchResultsOutcome.class)); responseHolder.close(); verify(userResponse,times(1)).complete(); } @Test public void testIOExceptionIsHandled() { Configuration configuration = mock(Configuration.class); when(configuration.getResponseCode(any(SearchResultsOutcome.class))).thenReturn(200); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); try { doThrow(new IOException()).when(response).getWriter(); } catch (IOException e) { e.printStackTrace(); } AsyncContext userResponse = getAsyncContext(request,response); SearchResponseContext responseHolder = new AsyncServletSearchResponseContext(userResponse,System.nanoTime()); SearchResponseContextHandler handler = getHandler(configuration); handler.sendResults("results","appplication/json",mock(SearchResultsEvent.class),responseHolder); verify(response,times(1)).setStatus(500); responseHolder.close(); verify(userResponse, times(1)).complete(); }
### 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: JsonSmartIndexingRequestConverter implements IndexingRequestConverter { @Override public void translateTo(RelatedItemIndexingMessage convertedTo, long sequence) { convertedTo.setValidMessage(true); convertedTo.setUTCFormattedDate(date); parseProductArray(convertedTo,maxNumberOfAdditionalProperties); parseAdditionalProperties(convertedTo.getIndexingMessageProperties(), object, maxNumberOfAdditionalProperties); } JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData); JsonSmartIndexingRequestConverter(Configuration config, ISO8601UTCCurrentDateAndTimeFormatter dateCreator, ByteBuffer requestData, int maxNumberOfAllowedProperties,int maxNumberOfRelatedItems); @Override void translateTo(RelatedItemIndexingMessage convertedTo, long sequence); }### Answer: @Test public void testANonStringPropertyIsIgnored() { String json = "{" + " \"channel\" : 1.0," + " \"site\" : \"amazon\"," + " \"items\" : [ \"B009S4IJCK\", \"B0076UICIO\" ,\"B0096TJCXW\" ]"+ "}"; IndexingRequestConverter converter = createConverter(ByteBuffer.wrap(json.getBytes())); RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(new SystemPropertiesConfiguration()); converter.translateTo(message,1); assertEquals(1,message.getIndexingMessageProperties().getNumberOfProperties()); } @Test public void testExceptionIsNotThrownWhenJsonContainsTooManyProducts() { System.setProperty(ConfigurationConstants.PROPNAME_DISCARD_INDEXING_REQUESTS_WITH_TOO_MANY_ITEMS,"false"); System.setProperty(ConfigurationConstants.PROPNAME_MAX_NO_OF_RELATED_ITEMS_PER_INDEX_REQUEST,"2"); String json = "{" + " \"channel\" : \"uk\"," + " \"site\" : \"amazon\"," + " \"date\" : \"2013-05-02T15:31:31\"," + " \"items\" : [ \"B009S4IJCK\", \"B0076UICIO\" ,\"B0096TJCXW\" ]"+ "}"; try { IndexingRequestConverter converter = createConverter(ByteBuffer.wrap(json.getBytes())); RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(new SystemPropertiesConfiguration()); converter.translateTo(message,1); assertEquals(2, message.getRelatedItems().getNumberOfRelatedItems()); if(message.getRelatedItems().getRelatedItemAtIndex(0).getId().toString().equals("B009S4IJCK")) { assertEquals("B0076UICIO",message.getRelatedItems().getRelatedItemAtIndex(1).getId().toString()); } else if(message.getRelatedItems().getRelatedItemAtIndex(0).getId().toString().equals("B0076UICIO")) { assertEquals("B009S4IJCK",message.getRelatedItems().getRelatedItemAtIndex(1).getId().toString()); } else { fail("Json message should have thrown away the last id."); } } catch(InvalidIndexingRequestException e) { fail("Should be able to parse json, just that some related items are not stored"); } }
### 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: JodaISO8601UTCCurrentDateAndTimeFormatter implements ISO8601UTCCurrentDateAndTimeFormatter { @Override public String formatToUTC(String day) { StringBuilderWriter b = new StringBuilderWriter(24); try { formatterUTCPrinter.printTo(b,formatterUTC.parseDateTime(day)); } catch (IOException e) { } return b.toString(); } @Override String getCurrentDay(); @Override String formatToUTC(String day); }### Answer: @Test public void testParseDatesToUTCTimeGoesBackADay() { assertEquals("2008-02-06T22:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00.000+11:00")); } @Test public void testParseDatesToUTCTimeGoesBackInCurrentDay() { assertEquals("2008-02-07T00:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00.000+09:00")); } @Test public void testParseDateToUTCTimeGoesBackInCurrentDayWithNoMillis() { assertEquals("2008-02-07T00:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00+09:00")); } @Test public void testParseDateToUTCTimeGoesBackInCurrentDayWithNoSeparators() { assertEquals("2008-02-07T00:30:00.000Z",formatter.formatToUTC("20080207T093000+0900")); } @Test public void testParseDateToUTCTimeWithNoTimeZoneIsTakenAsUTC() { assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("20080207T093000+0000")); assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00")); assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00+00:00")); assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00.000+00:00")); assertEquals("2008-02-07T09:30:00.000Z",formatter.formatToUTC("2008-02-07T09:30:00+00:00")); } @Test public void testParseDateToUTCWithNoTimeInformation() { assertEquals("2008-02-07T00:00:00.000Z",formatter.formatToUTC("2008-02-07")); }
### 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: HourBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHour(); } else { date = currentDayFormatter.parseToDateAndHour(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } HourBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }### Answer: @Test public void testEmptyDateReturnsToday() { RelatedItem product = new RelatedItem("1".toCharArray(),null,null,new RelatedItemAdditionalProperties()); String name = hourBasedMapper.getLocationName(product); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd_HH"); assertEquals(config.getStorageIndexNamePrefix() + "-" + today.format(new Date()),name); } @Test public void testSetDateReturnsIndexNameWithGivenDate() { Date now = new Date(); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); SimpleDateFormat todayDate = new SimpleDateFormat("yyyy-MM-dd'_'HH"); RelatedItem product = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); try { Thread.sleep(2000); } catch(Exception e) { } RelatedItem product2 = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); String name = hourBasedMapper.getLocationName(product); String name2 = hourBasedMapper.getLocationName(product2); assertEquals(config.getStorageIndexNamePrefix() + "-" + todayDate.format(new Date()),name); assertEquals(config.getStorageIndexNamePrefix() + "-" + todayDate.format(new Date()),name2); RelatedItem product3 = new RelatedItem("1".toCharArray(),"1920-01-02T23:59:59+00:00",null,new RelatedItemAdditionalProperties()); name = hourBasedMapper.getLocationName(product3); assertEquals(config.getStorageIndexNamePrefix() + "-1920-01-02_23",name); } @Test public void testTimeZoneDate() { RelatedItem product = new RelatedItem("1".toCharArray(),"1920-01-02T01:59:59+02:00",null,new RelatedItemAdditionalProperties()); String name = hourBasedMapper.getLocationName(product); assertEquals(config.getStorageIndexNamePrefix() + "-1920-01-01_23",name); }
### Question: MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }### Answer: @Test public void testEmptyDateReturnsToday() { RelatedItem product = new RelatedItem("1".toCharArray(),null,null,new RelatedItemAdditionalProperties()); String name = minBasedMapper.getLocationName(product); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd_HH':'mm"); assertEquals(config.getStorageIndexNamePrefix() + "-" + today.format(new Date()),name); } @Test public void testSetDateReturnsIndexNameWithGivenDate() { Date now = new Date(); SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); SimpleDateFormat todayDate = new SimpleDateFormat("yyyy-MM-dd'_'HH':'mm"); RelatedItem product = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); try { Thread.sleep(2000); } catch(Exception e) { } RelatedItem product2 = new RelatedItem("1".toCharArray(),today.format(now),null,new RelatedItemAdditionalProperties()); String name = minBasedMapper.getLocationName(product); String name2 = minBasedMapper.getLocationName(product2); assertEquals(config.getStorageIndexNamePrefix() + "-" + todayDate.format(now), name); assertEquals(config.getStorageIndexNamePrefix() + "-" + todayDate.format(now),name2); RelatedItem product3 = new RelatedItem("1".toCharArray(),"1920-01-02T23:59:59+00:00",null,new RelatedItemAdditionalProperties()); name = minBasedMapper.getLocationName(product3); assertEquals(config.getStorageIndexNamePrefix() + "-1920-01-02_23:59",name); } @Test public void testTimeZoneDate() { RelatedItem product = new RelatedItem("1".toCharArray(),"1920-01-02T01:59:59+02:00",null,new RelatedItemAdditionalProperties()); String name = minBasedMapper.getLocationName(product); assertEquals(config.getStorageIndexNamePrefix() + "-1920-01-01_23:59",name); }
### 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 onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }### Answer: @Test public void testSendingOneItem() { try { handler.onEvent(getMessage(),1,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(3,repo.getNumberOfProductsSentForStoring()); } @Test public void testSendingManyItemsButBelowBatchSize() { try { for(int i=0;i<7;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),8,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(24,repo.getNumberOfProductsSentForStoring()); } @Test public void testSendingManyItemsExceedingBatchSize() { try { for(int i=0;i<25;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),26,true); } catch(Exception e) { fail(); } assertEquals(3,repo.getNumberOfCalls()); assertEquals(78,repo.getNumberOfProductsSentForStoring()); } @Test public void checkNoCallMadeForInvalidMessage() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(false); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.getNumberOfCalls()); assertEquals(0,repo.getNumberOfProductsSentForStoring()); } @Test public void checkNoCallMadeForMessageWithNoProducts() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(true); message.getRelatedItems().setNumberOfRelatedItems(0); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.getNumberOfCalls()); assertEquals(0,repo.getNumberOfProductsSentForStoring()); }
### 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: ChecksHelper { @StringRes public static int getCheckStringId(@CheckingMethodType int typeCheck) { @StringRes int result = 0; switch (typeCheck) { case CH_TYPE_TEST_KEYS: result = R.string.checks_desc_1; break; case CH_TYPE_DEV_KEYS: result = R.string.checks_desc_2; break; case CH_TYPE_NON_RELEASE_KEYS: result = R.string.checks_desc_3; break; case CH_TYPE_DANGEROUS_PROPS: result = R.string.checks_desc_4; break; case CH_TYPE_PERMISSIVE_SELINUX: result = R.string.checks_desc_5; break; case CH_TYPE_SU_EXISTS: result = R.string.checks_desc_6; break; case CH_TYPE_SUPER_USER_APK: result = R.string.checks_desc_7; break; case CH_TYPE_SU_BINARY: result = R.string.checks_desc_8; break; case CH_TYPE_BUSYBOX_BINARY: result = R.string.checks_desc_9; break; case CH_TYPE_XPOSED: result = R.string.checks_desc_10; break; case CH_TYPE_RESETPROP: result = R.string.checks_desc_11; break; case CH_TYPE_WRONG_PATH_PERMITION: result = R.string.checks_desc_12; break; case CH_TYPE_HOOKS: result = R.string.checks_desc_13; break; case CH_TYPE_UNKNOWN: default: result = R.string.empty; } return result; } private ChecksHelper(); @StringRes static int getCheckStringId(@CheckingMethodType int typeCheck); static Bitmap getNonCheck(@NonNull Context pContext); static Bitmap getFound(@NonNull Context pContext); static Bitmap getOk(@NonNull Context pContext); }### Answer: @Test public void getCheckStringIdTest() throws Exception { assertThat(getCheckStringId(CH_TYPE_TEST_KEYS), is(R.string.checks_desc_1)); assertThat(getCheckStringId(CH_TYPE_DEV_KEYS), is(R.string.checks_desc_2)); assertThat(getCheckStringId(CH_TYPE_NON_RELEASE_KEYS), is(R.string.checks_desc_3)); assertThat(getCheckStringId(CH_TYPE_DANGEROUS_PROPS), is(R.string.checks_desc_4)); assertThat(getCheckStringId(CH_TYPE_PERMISSIVE_SELINUX), is(R.string.checks_desc_5)); assertThat(getCheckStringId(CH_TYPE_SU_EXISTS), is(R.string.checks_desc_6)); assertThat(getCheckStringId(CH_TYPE_SUPER_USER_APK), is(R.string.checks_desc_7)); assertThat(getCheckStringId(CH_TYPE_SU_BINARY), is(R.string.checks_desc_8)); assertThat(getCheckStringId(CH_TYPE_BUSYBOX_BINARY), is(R.string.checks_desc_9)); assertThat(getCheckStringId(CH_TYPE_XPOSED), is(R.string.checks_desc_10)); assertThat(getCheckStringId(CH_TYPE_RESETPROP), is(R.string.checks_desc_11)); assertThat(getCheckStringId(CH_TYPE_WRONG_PATH_PERMITION), is(R.string.checks_desc_12)); assertThat(getCheckStringId(CH_TYPE_HOOKS), is(R.string.checks_desc_13)); assertThat(getCheckStringId(CH_TYPE_UNKNOWN), is(R.string.empty)); assertEquals(getCheckStringId(CH_TYPE_UNKNOWN), R.string.empty); assertThat(getCheckStringId(Integer.MAX_VALUE), is(R.string.empty)); }
### 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 boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }### Answer: @Test public void assignDefaultUserToEntityWithRole() { final String msg = "Assign default user to entity with role failed"; final boolean ok = configurationService.isDefaultUserAssignedToEntityWithRole(); assertTrue(msg, ok); final EUser u = userRepository.findFirstByUsername(dc.getUserAdminDefaultUsername()); final EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); assertNotNull(u); assertNotNull(e); final List<BRole> roles = authRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertTrue(msg, roles != null && !roles.isEmpty()); } @Transactional @Test public void assignDefaultUserToEntityWithRoleDefaultUserNotFound() { EUser defaultUser = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); authRepository.delete(authRepository.findFirstByUserAndEntityNotNullAndRoleEnabled(defaultUser, true)); userRepository.delete(defaultUser); assertFalse(configurationService.isDefaultUserAssignedToEntityWithRole()); }
### Question: ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }### Answer: @Test public void getConfig() { String key; String value; List<String> keys = new LinkedList<>(); List<String> values = new LinkedList<>(); final int top = 10; for (int i = 0; i < top; i++) { key = random.nextString() + "_IN_SERVER"; value = random.nextString(); keys.add(key); values.add(value); assertNotNull(configurationRepository.save(new BConfiguration(key, value))); } Map<String, String> configs = configurationService.getConfig(); Object config; for (int i = 0; i < keys.size(); i++) { config = configs.get(keys.get(i)); assertNotNull("Configuration found if null", config); value = values.get(i); assertEquals("Configuration value returned by server (" + config + ") does not match the expected", config, value); } } @Test public void getConfigInServerNotFound() { boolean success = false; try { configurationService.getConfig(random.nextString() + ConfigurationService.IN_SERVER); } catch (NotFoundEntityException e) { assertEquals(ConfigurationService.CONFIG_NOT_FOUND, e.getMessage()); success = true; } assertTrue(success); } @Test public void getConfigNotFound() { boolean success = false; try { configurationService.getConfig(random.nextString().replace(ConfigurationService.IN_SERVER, "")); } catch (NotFoundEntityException e) { assertEquals(ConfigurationService.CONFIG_NOT_FOUND, e.getMessage()); success = true; } assertTrue(success); }
### Question: ConfigurationService { public Map<String, Object> getConfigByUser(final long userId) { final List<BConfiguration> configs = configurationRepository.findAllByUserId(userId); Map<String, Object> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }### Answer: @Test public void getConfigByUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BConfiguration c = configurationRepository.save(new BConfiguration(keyLang, "es", u.getId())); assertNotNull(c); BConfiguration c2 = configurationRepository.save( new BConfiguration(keyLastAccessedEntity, String.valueOf(e.getId()), u.getId()) ); assertNotNull(c2); Map<String, Object> configs = configurationService.getConfigByUser(u.getId()); assertNotNull(configs.get(keyLang)); assertNotNull(configs.get(keyLastAccessedEntity)); assertEquals("Configuration values (language) do not match", "es", configs.get(keyLang)); assertEquals("Configuration values (last accessed entity) do not match", configs.get(keyLastAccessedEntity), String.valueOf(e.getId())); }
### Question: ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }### Answer: @Test public void saveConfig() { List<Iterable<BConfiguration>> list = deleteAllServerConfig(); Map<String, Object> configs = new HashMap<>(); configs.put(keyUserRegistrationAllowed, false); configs.put(keyMultiEntityApp, true); try { configurationService.saveConfig(configs); BConfiguration cR = configurationRepository.findFirstByKey(keyUserRegistrationAllowed); assertNotNull(cR); assertEquals(Boolean.toString(false), cR.getValue()); cR = configurationRepository.findFirstByKey(keyMultiEntityApp); assertNotNull(cR); assertEquals(Boolean.toString(true), cR.getValue()); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("At least one of the keys was not found."); } catch (GmsGeneralException e) { LOGGER.error(e.getLocalizedMessage()); fail("The provided user key was not valid"); } assertTrue(hasRestoredAllServerConfig(list)); } @Test public void saveConfigForUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(u); Map<String, Object> configs = new HashMap<>(); configs.put(keyLang, "fr"); configs.put(keyLastAccessedEntity, e.getId()); try { configurationService.saveConfig(configs, u.getId()); } catch (NotFoundEntityException e1) { LOGGER.error(e1.getLocalizedMessage()); fail("At least one of the keys was not found."); } } @Test public void saveConfigKeyNotFound() { Map<String, Object> configs = new HashMap<>(); configs.put(random.nextString(), random.nextString()); boolean success = false; try { configurationService.saveConfig(configs); } catch (GmsGeneralException e) { LOGGER.error(e.getLocalizedMessage()); fail("There was not provided user and the test still failed because of it"); } catch (Exception e) { success = true; } assertTrue(success); }
### 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 { public List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, true); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }### Answer: @Test public void addRolesToUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); List<Long> ids = new LinkedList<>(); ids.add(r1.getId()); ids.add(r2.getId()); assertEquals(2, ids.size()); List<Long> added = null; try { added = userService.addRolesToUser(u.getId(), e.getId(), ids); assertNotNull(added); assertEquals(added.size(), ids.size()); assertTrue(added.contains(ids.get(0))); assertTrue(added.contains(ids.get(1))); } catch (NotFoundEntityException e1) { LOGGER.error(e1.getLocalizedMessage()); fail("Roles could not be saved"); } final List<BRole> roles = authorizationRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertEquals(roles.size(), ids.size()); assertNotNull(added); assertEquals(added.size(), roles.size()); assertTrue(added.contains(roles.get(0).getId())); assertTrue(added.contains(roles.get(1).getId())); }
### Question: UserService implements UserDetailsService { public List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, false); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }### Answer: @Test public void removeRolesFromUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r1.getId()); assertNotNull(pk1); BAuthorization auth1 = authorizationRepository.save(new BAuthorization(pk1, u, e, r1)); assertNotNull(auth1); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r2.getId()); assertNotNull(pk1); BAuthorization auth2 = authorizationRepository.save(new BAuthorization(pk2, u, e, r2)); assertNotNull(auth2); Collection<Long> ids = new LinkedList<>(); ids.add(r1.getId()); ids.add(r2.getId()); List<BRole> roles = authorizationRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertEquals(roles.size(), ids.size()); assertTrue(ids.contains(roles.get(0).getId())); assertTrue(ids.contains(roles.get(1).getId())); List<Long> removed = null; try { removed = userService.removeRolesFromUser(u.getId(), e.getId(), ids); } catch (NotFoundEntityException e1) { LOGGER.error(e1.getLocalizedMessage()); fail("Roles could not be removed"); } assertNotNull(removed); assertEquals(removed.size(), roles.size()); assertTrue(removed.contains(roles.get(0).getId())); assertTrue(removed.contains(roles.get(1).getId())); roles = authorizationRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertTrue(roles.isEmpty()); }
### 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 String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator) { StringBuilder authBuilder = new StringBuilder(); EUser u = (EUser) loadUserByUsername(usernameOrEmail); if (u != null) { Long entityId = getEntityIdByUser(u); if (entityId == null) { return ""; } List<BPermission> pFromDB = permissionService.findPermissionsByUserIdAndEntityId(u.getId(), entityId); for (BPermission p : pFromDB) { authBuilder.append(p.getName()).append(separator); } } return authBuilder.toString(); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }### Answer: @Test public void getUserAuthoritiesForToken() { BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r1 = EntityUtil.getSampleRole(random.nextString()); r1.addPermission(p1, p2); assertNotNull(roleRepository.save(r1)); BPermission p3 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p3); BPermission p4 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p4); BRole r2 = EntityUtil.getSampleRole(random.nextString()); r2.addPermission(p3, p4); assertNotNull(roleRepository.save(r2)); EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r1.getId()); BAuthorization auth1 = new BAuthorization(pk1, u, e, r1); assertNotNull(authorizationRepository.save(auth1)); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r2.getId()); BAuthorization auth2 = new BAuthorization(pk2, u, e, r2); assertNotNull(authorizationRepository.save(auth2)); String separator = "--<<" + random.nextString() + ">>--"; String authForToken = userService.getUserAuthoritiesForToken(u.getUsername(), separator); assertNotNull(authForToken); assertNotEquals("", authForToken); List<String> permissionNames = Arrays.asList(authForToken.split(separator)); assertTrue(permissionNames.contains(p1.getName())); assertTrue(permissionNames.contains(p2.getName())); assertTrue(permissionNames.contains(p3.getName())); assertTrue(permissionNames.contains(p4.getName())); }
### Question: UserService implements UserDetailsService { public Map<String, List<BRole>> getRolesForUser(final Long id) throws NotFoundEntityException { EUser u = getUser(id); return authorizationRepository.getRolesForUserOverAllEntities(u.getId()); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }### Answer: @Test public void getRolesForUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e1 = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e1); EOwnedEntity e2 = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e2); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); BRole r3 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r3); BRole r4 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r4); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e1.getId(), r1.getId()); BAuthorization auth1 = authorizationRepository.save(new BAuthorization(pk1, u, e1, r1)); assertNotNull(auth1); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e1.getId(), r2.getId()); BAuthorization auth2 = authorizationRepository.save(new BAuthorization(pk2, u, e1, r2)); assertNotNull(auth2); BAuthorization.BAuthorizationPk pk3 = new BAuthorization.BAuthorizationPk(u.getId(), e2.getId(), r3.getId()); BAuthorization auth3 = authorizationRepository.save(new BAuthorization(pk3, u, e2, r3)); assertNotNull(auth3); BAuthorization.BAuthorizationPk pk4 = new BAuthorization.BAuthorizationPk(u.getId(), e2.getId(), r4.getId()); BAuthorization auth4 = authorizationRepository.save(new BAuthorization(pk4, u, e2, r4)); assertNotNull(auth4); try { final Map<String, List<BRole>> rolesForUser = userService.getRolesForUser(u.getId()); assertNotNull(rolesForUser); assertFalse(rolesForUser.isEmpty()); final Set<String> keySet = rolesForUser.keySet(); assertTrue(keySet.contains(e1.getUsername())); assertTrue(keySet.contains(e2.getUsername())); assertTrue(rolesForUser.get(e1.getUsername()).contains(r1)); assertTrue(rolesForUser.get(e1.getUsername()).contains(r2)); assertTrue(rolesForUser.get(e2.getUsername()).contains(r3)); assertTrue(rolesForUser.get(e2.getUsername()).contains(r4)); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("The username was not found"); } }
### Question: UserService implements UserDetailsService { public List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId) throws NotFoundEntityException { return authorizationRepository.getRolesForUserOverEntity( getUser(userId).getId(), getOwnedEntity(entityId).getId() ); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }### Answer: @Test public void getRolesForUserOverEntity() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r1.getId()); BAuthorization auth1 = authorizationRepository.save(new BAuthorization(pk1, u, e, r1)); assertNotNull(auth1); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r2.getId()); BAuthorization auth2 = authorizationRepository.save(new BAuthorization(pk2, u, e, r2)); assertNotNull(auth2); try { final List<BRole> roles = userService.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertFalse(roles.isEmpty()); assertTrue(roles.contains(r1)); assertTrue(roles.contains(r2)); } catch (NotFoundEntityException ex) { LOGGER.error(ex.getLocalizedMessage()); fail("Either the username or the entity was not found"); } }
### 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 List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }### Answer: @Test public void addPermissionsToRole() { BRole r = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r); BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(p1.getId()); pIDs.add(p2.getId()); try { List<Long> added = roleService.addPermissionsToRole(r.getId(), pIDs); assertEquals(added.size(), pIDs.size()); assertTrue(added.contains(p1.getId())); assertTrue(added.contains(p2.getId())); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("Could not add permissions to role"); } } @Test public void addPermissionsNotFoundToRole() { BRole r = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(INVALID_ID); boolean success = false; try { roleService.addPermissionsToRole(r.getId(), pIDs); } catch (NotFoundEntityException e) { success = true; assertEquals("role.add.permissions.found.none", e.getMessage()); } assertTrue(success); }
### 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: RoleService { public List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.UPDATE_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }### Answer: @Test @Transactional public void updatePermissionsInRole() { BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r = EntityUtil.getSampleRole(random.nextString()); r.addPermission(p1, p2); assertNotNull(roleRepository.save(r)); assertTrue(r.getPermissions().contains(p1)); assertTrue(r.getPermissions().contains(p2)); BPermission p3 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p3); BPermission p4 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p4); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(p3.getId()); pIDs.add(p4.getId()); try { final List<Long> updated = roleService.updatePermissionsInRole(r.getId(), pIDs); assertNotNull(updated); assertEquals(updated.size(), pIDs.size()); assertTrue(updated.contains(p3.getId())); assertTrue(updated.contains(p4.getId())); assertFalse(updated.contains(p1.getId())); assertFalse(updated.contains(p2.getId())); Optional<BRole> role = roleRepository.findById(r.getId()); assertTrue(role.isPresent()); final Set<BPermission> rPermissions = role.get().getPermissions(); assertFalse(rPermissions.contains(p1)); assertFalse(rPermissions.contains(p2)); assertTrue(rPermissions.contains(p3)); assertTrue(rPermissions.contains(p4)); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("Could not update the role permissions"); } }
### 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()); }