method2testcases
stringlengths 118
3.08k
|
---|
### Question:
RollingPolicyDecorator implements RollingPolicy { @Override public void start() { ScanTask task = createScanTaskAndCancelInProgress(); _decorated.start(); _executorService.execute(task); } RollingPolicyDecorator(RollingPolicyBase decorated, RolloverListener listener, ScheduledExecutorService executorService); @Override void rollover(); @Override String getActiveFileName(); @Override CompressionMode getCompressionMode(); @Override void setParent(FileAppender appender); @Override void start(); @Override void stop(); @Override boolean isStarted(); RollingPolicyBase getDecorated(); static final int DEFAULT_RESCAN_DELAY; static final String ROLLOVER_RESCAN_DELAY_MS_PROPERTY_NAME; static final int DEFAULT_RESCAN_LIMIT; static final String ROLLOVER_RESCAN_LIMIT_PROPERTY_NAME; }### Answer:
@Test public void testStart() { _policy.start(); verify(_delegate).start(); } |
### Question:
InternalMessageMutator implements ServerMessageMutator<InternalMessage> { @Override public byte getPriority() { return _priority; } InternalMessageMutator(final InternalMessage message, final MessageStore messageStore); @Override void setPriority(final byte priority); @Override byte getPriority(); @Override InternalMessage create(); }### Answer:
@Test public void getPriority() { assertThat((int) _messageMutator.getPriority(), is(equalTo((int) TEST_PRIORITY))); } |
### Question:
InternalMessageMutator implements ServerMessageMutator<InternalMessage> { @Override public InternalMessage create() { final InternalMessageHeader messageHeader = _message.getMessageHeader(); final InternalMessageHeader newHeader = new InternalMessageHeader(new HashMap<>(messageHeader.getHeaderMap()), messageHeader.getCorrelationId(), messageHeader.getExpiration(), messageHeader.getUserId(), messageHeader.getAppId(), messageHeader.getMessageId(), messageHeader.getMimeType(), messageHeader.getEncoding(), _priority, messageHeader.getTimestamp(), messageHeader.getNotValidBefore(), messageHeader.getType(), messageHeader.getReplyTo(), _message.getArrivalTime()); final long contentSize = _message.getSize(); final InternalMessageMetaData metaData = InternalMessageMetaData.create(_message.isPersistent(), newHeader, (int) contentSize); final MessageHandle<InternalMessageMetaData> handle = _messageStore.addMessage(metaData); final QpidByteBuffer content = _message.getContent(); if (content != null) { handle.addContent(content); } final StoredMessage<InternalMessageMetaData> storedMessage = handle.allContentAdded(); return new InternalMessage(storedMessage, newHeader, _message.getMessageBody(), _message.getTo()); } InternalMessageMutator(final InternalMessage message, final MessageStore messageStore); @Override void setPriority(final byte priority); @Override byte getPriority(); @Override InternalMessage create(); }### Answer:
@Test public void create() { _messageMutator.setPriority((byte) (TEST_PRIORITY + 1)); final InternalMessage newMessage = _messageMutator.create(); assertThat(newMessage.getMessageHeader().getPriority(), is(equalTo((byte) (TEST_PRIORITY + 1)))); assertThat(newMessage.getMessageHeader().getMimeType(), is(equalTo(TEST_CONTENT_TYPE))); assertThat(newMessage.getMessageHeader().getHeader(TEST_HEADER_NAME), is(equalTo(TEST_HEADER_VALUE))); final QpidByteBuffer content = newMessage.getContent(); final byte[] bytes = new byte[content.remaining()]; content.copyTo(bytes); assertThat(new String(bytes, UTF_8), is(equalTo(TEST_CONTENT))); } |
### Question:
UUIDGenerator { public static UUID generateQueueUUID(String queueName, String virtualHostName) { return createUUID(Queue.class.getName(), virtualHostName, queueName); } static UUID generateRandomUUID(); static UUID generateExchangeUUID(String exchangeName, String virtualHostName); static UUID generateQueueUUID(String queueName, String virtualHostName); static UUID generateBindingUUID(String exchangeName, String queueName, String bindingKey, String virtualHostName); static UUID generateUserUUID(String authenticationProviderName, String userName); static UUID generateGroupUUID(String groupProviderName, String groupName); static UUID generateVhostUUID(String virtualHostName); static UUID generateVhostAliasUUID(String virtualHostName, String portName); static UUID generateConsumerUUID(String virtualHostName, String queueName, String connectionRemoteAddress, String channelNumber, String consumerName); static UUID generateGroupMemberUUID(String groupProviderName, String groupName, String groupMemberName); static UUID generateBrokerChildUUID(String type, String childName); }### Answer:
@Test public void testQueueIdGeneration() throws Exception { UUID queue1 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_1); UUID queue2 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_1); assertEquals("Queue IDs should be equal", queue1, queue2); queue1 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_1); queue2 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_2, VIRTUAL_HOST_NAME_1); assertFalse("Queue IDs should not be equal", queue1.equals(queue2)); queue1 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_1); queue2 = UUIDGenerator.generateQueueUUID(QUEUE_NAME_1, VIRTUAL_HOST_NAME_2); assertFalse("Queue IDs should not be equal", queue1.equals(queue2)); } |
### Question:
UUIDGenerator { public static UUID generateExchangeUUID(String exchangeName, String virtualHostName) { return createUUID(Exchange.class.getName(), virtualHostName, exchangeName); } static UUID generateRandomUUID(); static UUID generateExchangeUUID(String exchangeName, String virtualHostName); static UUID generateQueueUUID(String queueName, String virtualHostName); static UUID generateBindingUUID(String exchangeName, String queueName, String bindingKey, String virtualHostName); static UUID generateUserUUID(String authenticationProviderName, String userName); static UUID generateGroupUUID(String groupProviderName, String groupName); static UUID generateVhostUUID(String virtualHostName); static UUID generateVhostAliasUUID(String virtualHostName, String portName); static UUID generateConsumerUUID(String virtualHostName, String queueName, String connectionRemoteAddress, String channelNumber, String consumerName); static UUID generateGroupMemberUUID(String groupProviderName, String groupName, String groupMemberName); static UUID generateBrokerChildUUID(String type, String childName); }### Answer:
@Test public void testExchangeIdGeneration() throws Exception { UUID exchange1 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_1); UUID exchange2 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_1); assertEquals("Exchange IDs should be equal", exchange1, exchange2); exchange1 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_1); exchange2 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_2, VIRTUAL_HOST_NAME_1); assertFalse("Exchange IDs should not be equal", exchange1.equals(exchange2)); exchange1 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_1); exchange2 = UUIDGenerator.generateExchangeUUID(EXCHANGE_NAME_1, VIRTUAL_HOST_NAME_2); assertFalse("Exchange IDs should not be equal", exchange1.equals(exchange2)); } |
### Question:
UUIDGenerator { public static UUID generateVhostUUID(String virtualHostName) { return createUUID(VirtualHost.class.getName(), virtualHostName); } static UUID generateRandomUUID(); static UUID generateExchangeUUID(String exchangeName, String virtualHostName); static UUID generateQueueUUID(String queueName, String virtualHostName); static UUID generateBindingUUID(String exchangeName, String queueName, String bindingKey, String virtualHostName); static UUID generateUserUUID(String authenticationProviderName, String userName); static UUID generateGroupUUID(String groupProviderName, String groupName); static UUID generateVhostUUID(String virtualHostName); static UUID generateVhostAliasUUID(String virtualHostName, String portName); static UUID generateConsumerUUID(String virtualHostName, String queueName, String connectionRemoteAddress, String channelNumber, String consumerName); static UUID generateGroupMemberUUID(String groupProviderName, String groupName, String groupMemberName); static UUID generateBrokerChildUUID(String type, String childName); }### Answer:
@Test public void testVhostIdGeneration() throws Exception { UUID vhost1 = UUIDGenerator.generateVhostUUID(VIRTUAL_HOST_NAME_1); UUID vhost2 = UUIDGenerator.generateVhostUUID(VIRTUAL_HOST_NAME_1); assertTrue("Virtualhost IDs should be equal", vhost1.equals(vhost2)); vhost1 = UUIDGenerator.generateVhostUUID(VIRTUAL_HOST_NAME_1); vhost2 = UUIDGenerator.generateVhostUUID(VIRTUAL_HOST_NAME_2); assertFalse("Virtualhost IDs should not be equal", vhost1.equals(vhost2)); } |
### Question:
UUIDGenerator { public static UUID generateVhostAliasUUID(String virtualHostName, String portName) { return createUUID(VirtualHostAlias.class.getName(), virtualHostName, portName); } static UUID generateRandomUUID(); static UUID generateExchangeUUID(String exchangeName, String virtualHostName); static UUID generateQueueUUID(String queueName, String virtualHostName); static UUID generateBindingUUID(String exchangeName, String queueName, String bindingKey, String virtualHostName); static UUID generateUserUUID(String authenticationProviderName, String userName); static UUID generateGroupUUID(String groupProviderName, String groupName); static UUID generateVhostUUID(String virtualHostName); static UUID generateVhostAliasUUID(String virtualHostName, String portName); static UUID generateConsumerUUID(String virtualHostName, String queueName, String connectionRemoteAddress, String channelNumber, String consumerName); static UUID generateGroupMemberUUID(String groupProviderName, String groupName, String groupMemberName); static UUID generateBrokerChildUUID(String type, String childName); }### Answer:
@Test public void testVhostAliasIdGeneration() throws Exception { UUID alias1 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_1); UUID alias2 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_1); assertTrue("Virtualhost Alias IDs should be equal", alias1.equals(alias2)); alias1 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_1); alias2 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_2, PORT_1); assertFalse("Virtualhost Alias IDs should not be equal", alias1.equals(alias2)); alias1 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_1); alias2 = UUIDGenerator.generateVhostAliasUUID(VHOST_ALIAS_1, PORT_2); assertFalse("Virtualhost Alias IDs should not be equal", alias1.equals(alias2)); } |
### Question:
UUIDGenerator { public static UUID generateUserUUID(String authenticationProviderName, String userName) { return createUUID(User.class.getName(), authenticationProviderName, userName); } static UUID generateRandomUUID(); static UUID generateExchangeUUID(String exchangeName, String virtualHostName); static UUID generateQueueUUID(String queueName, String virtualHostName); static UUID generateBindingUUID(String exchangeName, String queueName, String bindingKey, String virtualHostName); static UUID generateUserUUID(String authenticationProviderName, String userName); static UUID generateGroupUUID(String groupProviderName, String groupName); static UUID generateVhostUUID(String virtualHostName); static UUID generateVhostAliasUUID(String virtualHostName, String portName); static UUID generateConsumerUUID(String virtualHostName, String queueName, String connectionRemoteAddress, String channelNumber, String consumerName); static UUID generateGroupMemberUUID(String groupProviderName, String groupName, String groupMemberName); static UUID generateBrokerChildUUID(String type, String childName); }### Answer:
@Test public void testUserIdGeneration() throws Exception { UUID user1 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_1); UUID user2 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_1); assertTrue("User IDs should be equal", user1.equals(user2)); user1 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_1); user2 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_2); assertFalse("User IDs should not be equal", user1.equals(user2)); user1 = UUIDGenerator.generateUserUUID(PROVIDER_1, USER_1); user2 = UUIDGenerator.generateUserUUID(PROVIDER_2, USER_1); assertFalse("User IDs should not be equal", user1.equals(user2)); } |
### Question:
ConfiguredObjectJacksonModule extends SimpleModule { public static ObjectMapper newObjectMapper(final boolean forPersistence) { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(forPersistence ? PERSISTENCE_INSTANCE : INSTANCE); return objectMapper; } private ConfiguredObjectJacksonModule(final boolean forPersistence); static ObjectMapper newObjectMapper(final boolean forPersistence); }### Answer:
@Test public void testPrincipalSerialisation() throws Exception { final String username = "testuser@withFunky%"; final String originType = "authType"; final String originName = "authName('also')with%funky@Characters'"; final String expectedSerialisation = String.format("\"%s@%s('%s')\"", URLEncoder.encode(username, UTF8), originType, URLEncoder.encode(originName, UTF8)); AuthenticationProvider<?> authProvider = mock(AuthenticationProvider.class); when(authProvider.getType()).thenReturn(originType); when(authProvider.getName()).thenReturn(originName); Principal p = new UsernamePrincipal(username, authProvider); ObjectMapper mapper = ConfiguredObjectJacksonModule.newObjectMapper(false); String json = mapper.writeValueAsString(p); assertEquals("unexpected principal serialisation", expectedSerialisation, json); }
@Test public void testManageableAttributeType() throws IOException { ManagedAttributeValue testType = new TestManagedAttributeValue(); ObjectMapper encoder = ConfiguredObjectJacksonModule.newObjectMapper(false); String encodedValue = encoder.writeValueAsString(testType); ObjectMapper decoder = new ObjectMapper(); Map decodedMap = decoder.readValue(encodedValue, Map.class); assertEquals((long) 3, (long) decodedMap.size()); assertTrue(decodedMap.containsKey("name")); assertTrue(decodedMap.containsKey("map")); assertTrue(decodedMap.containsKey("type")); assertEquals("foo", decodedMap.get("name")); assertEquals(Collections.singletonMap("key", "value"), decodedMap.get("map")); assertEquals(Collections.singletonMap("nested", true), decodedMap.get("type")); } |
### Question:
RollingPolicyDecorator implements RollingPolicy { @Override public void stop() { _decorated.stop(); synchronized (_publishResultsLock) { if (_currentScanTask != null) { _currentScanTask.cancel(); } _previousScanResults = null; } } RollingPolicyDecorator(RollingPolicyBase decorated, RolloverListener listener, ScheduledExecutorService executorService); @Override void rollover(); @Override String getActiveFileName(); @Override CompressionMode getCompressionMode(); @Override void setParent(FileAppender appender); @Override void start(); @Override void stop(); @Override boolean isStarted(); RollingPolicyBase getDecorated(); static final int DEFAULT_RESCAN_DELAY; static final String ROLLOVER_RESCAN_DELAY_MS_PROPERTY_NAME; static final int DEFAULT_RESCAN_LIMIT; static final String ROLLOVER_RESCAN_LIMIT_PROPERTY_NAME; }### Answer:
@Test public void testStop() { _policy.stop(); verify(_delegate).stop(); } |
### Question:
ArrivalTimeFilterFactory implements MessageFilterFactory { @Override public MessageFilter newInstance(final List<String> arguments) { if(arguments == null || arguments.size() != 1) { throw new IllegalArgumentException(String.format("Cannot create a %s filter from these arguments: %s", getType(), arguments)); } final String periodArgument = arguments.get(0); try { long periodInSeconds = Long.parseLong(periodArgument); return new ArrivalTimeFilter(System.currentTimeMillis() - (periodInSeconds * 1000L), periodInSeconds == 0L); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("Cannot create a %s filter. Period value '%s' does not contain a parsable long value", getType(), periodArgument), e); } } @Override MessageFilter newInstance(final List<String> arguments); @Override String getType(); }### Answer:
@Test public void testNewInstance() throws Exception { long currentTime = System.currentTimeMillis(); int periodInSeconds = 60; MessageFilter filter = new ArrivalTimeFilterFactory().newInstance(Collections.singletonList(String.valueOf(periodInSeconds))); Filterable message = mock(Filterable.class); when(message.getArrivalTime()).thenReturn(currentTime - periodInSeconds * 1000 - 1); assertFalse("Message arrived before '1 minute before filter creation' should not be accepted", filter.matches(message)); when(message.getArrivalTime()).thenReturn(currentTime - periodInSeconds * 1000 / 2); assertTrue("Message arrived after '1 minute before filter creation' should be accepted", filter.matches(message)); when(message.getArrivalTime()).thenReturn(System.currentTimeMillis()); assertTrue("Message arrived after filter creation should be accepted", filter.matches(message)); } |
### Question:
JMSSelectorFilter implements MessageFilter { @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final JMSSelectorFilter that = (JMSSelectorFilter) o; return getSelector().equals(that.getSelector()); } JMSSelectorFilter(String selector); @Override String getName(); @Override boolean matches(Filterable message); @Override boolean startAtTail(); String getSelector(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEqualsAndHashCodeUsingSelectorString() throws Exception { final String selectorString = "1 = 1"; JMSSelectorFilter filter1 = new JMSSelectorFilter(new String(selectorString)); JMSSelectorFilter filter2 = new JMSSelectorFilter(new String(selectorString)); assertEquals(filter1 + " should equal itself", filter1, filter1); assertFalse(filter1 + " should not equal null", filter1.equals(null)); assertEqualsAndHashCodeMatch(filter1, filter2); JMSSelectorFilter differentFilter = new JMSSelectorFilter("2 = 2"); assertNotEqual(filter1, differentFilter); } |
### Question:
ExchangeMessages { public static LogMessage DELETED() { String rawMessage = _messages.getString("DELETED"); final String message = rawMessage; return new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return DELETED_LOG_HIERARCHY; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LogMessage that = (LogMessage) o; return getLogHierarchy().equals(that.getLogHierarchy()) && toString().equals(that.toString()); } @Override public int hashCode() { int result = toString().hashCode(); result = 31 * result + getLogHierarchy().hashCode(); return result; } }; } private ExchangeMessages(); static LogMessage CREATED(String param1, String param2, boolean opt1); static LogMessage DELETED(); static LogMessage DISCARDMSG(String param1, String param2); static LogMessage OPERATION(String param1); static final String EXCHANGE_LOG_HIERARCHY; static final String CREATED_LOG_HIERARCHY; static final String DELETED_LOG_HIERARCHY; static final String DISCARDMSG_LOG_HIERARCHY; static final String OPERATION_LOG_HIERARCHY; }### Answer:
@Test public void testExchangeDeleted() { _logMessage = ExchangeMessages.DELETED(); List<Object> log = performLog(); String[] expected = {"Deleted"}; validateLogMessage(log, "EXH-1002", expected); } |
### Question:
ExchangeMessages { public static LogMessage DISCARDMSG(String param1, String param2) { String rawMessage = _messages.getString("DISCARDMSG"); final Object[] messageArguments = {param1, param2}; MessageFormat formatter = new MessageFormat(rawMessage, _currentLocale); final String message = formatter.format(messageArguments); return new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return DISCARDMSG_LOG_HIERARCHY; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LogMessage that = (LogMessage) o; return getLogHierarchy().equals(that.getLogHierarchy()) && toString().equals(that.toString()); } @Override public int hashCode() { int result = toString().hashCode(); result = 31 * result + getLogHierarchy().hashCode(); return result; } }; } private ExchangeMessages(); static LogMessage CREATED(String param1, String param2, boolean opt1); static LogMessage DELETED(); static LogMessage DISCARDMSG(String param1, String param2); static LogMessage OPERATION(String param1); static final String EXCHANGE_LOG_HIERARCHY; static final String CREATED_LOG_HIERARCHY; static final String DELETED_LOG_HIERARCHY; static final String DISCARDMSG_LOG_HIERARCHY; static final String OPERATION_LOG_HIERARCHY; }### Answer:
@Test public void testExchangeDiscardedMessage() throws Exception { Exchange<?> exchange = BrokerTestHelper.createExchange("test", false, getEventLogger()); final String name = exchange.getName(); final String routingKey = "routingKey"; clearLog(); _logMessage = ExchangeMessages.DISCARDMSG(name, routingKey); List<Object> log = performLog(); String[] expected = {"Discarded Message :","Name:", "\"" + name + "\"", "Routing Key:", "\"" + routingKey + "\""}; validateLogMessage(log, "EXH-1003", expected); } |
### Question:
RollingPolicyDecorator implements RollingPolicy { @Override public boolean isStarted() { return _decorated.isStarted(); } RollingPolicyDecorator(RollingPolicyBase decorated, RolloverListener listener, ScheduledExecutorService executorService); @Override void rollover(); @Override String getActiveFileName(); @Override CompressionMode getCompressionMode(); @Override void setParent(FileAppender appender); @Override void start(); @Override void stop(); @Override boolean isStarted(); RollingPolicyBase getDecorated(); static final int DEFAULT_RESCAN_DELAY; static final String ROLLOVER_RESCAN_DELAY_MS_PROPERTY_NAME; static final int DEFAULT_RESCAN_LIMIT; static final String ROLLOVER_RESCAN_LIMIT_PROPERTY_NAME; }### Answer:
@Test public void testIsStarted() { _policy.isStarted(); verify(_delegate).isStarted(); } |
### Question:
VirtualHostMessages { public static LogMessage CREATED(String param1) { String rawMessage = _messages.getString("CREATED"); final Object[] messageArguments = {param1}; MessageFormat formatter = new MessageFormat(rawMessage, _currentLocale); final String message = formatter.format(messageArguments); return new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return CREATED_LOG_HIERARCHY; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LogMessage that = (LogMessage) o; return getLogHierarchy().equals(that.getLogHierarchy()) && toString().equals(that.toString()); } @Override public int hashCode() { int result = toString().hashCode(); result = 31 * result + getLogHierarchy().hashCode(); return result; } }; } private VirtualHostMessages(); static LogMessage CLOSED(String param1); static LogMessage CREATED(String param1); static LogMessage ERRORED(String param1); static LogMessage FILESYSTEM_FULL(Number param1); static LogMessage FILESYSTEM_NOTFULL(Number param1); static LogMessage OPERATION(String param1); static final String VIRTUALHOST_LOG_HIERARCHY; static final String CLOSED_LOG_HIERARCHY; static final String CREATED_LOG_HIERARCHY; static final String ERRORED_LOG_HIERARCHY; static final String FILESYSTEM_FULL_LOG_HIERARCHY; static final String FILESYSTEM_NOTFULL_LOG_HIERARCHY; static final String OPERATION_LOG_HIERARCHY; }### Answer:
@Test public void testVirtualhostCreated() { String name = "test"; _logMessage = VirtualHostMessages.CREATED(name); List<Object> log = performLog(); String[] expected = {"Created :", name}; validateLogMessage(log, "VHT-1001", expected); } |
### Question:
VirtualHostMessages { public static LogMessage CLOSED(String param1) { String rawMessage = _messages.getString("CLOSED"); final Object[] messageArguments = {param1}; MessageFormat formatter = new MessageFormat(rawMessage, _currentLocale); final String message = formatter.format(messageArguments); return new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return CLOSED_LOG_HIERARCHY; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LogMessage that = (LogMessage) o; return getLogHierarchy().equals(that.getLogHierarchy()) && toString().equals(that.toString()); } @Override public int hashCode() { int result = toString().hashCode(); result = 31 * result + getLogHierarchy().hashCode(); return result; } }; } private VirtualHostMessages(); static LogMessage CLOSED(String param1); static LogMessage CREATED(String param1); static LogMessage ERRORED(String param1); static LogMessage FILESYSTEM_FULL(Number param1); static LogMessage FILESYSTEM_NOTFULL(Number param1); static LogMessage OPERATION(String param1); static final String VIRTUALHOST_LOG_HIERARCHY; static final String CLOSED_LOG_HIERARCHY; static final String CREATED_LOG_HIERARCHY; static final String ERRORED_LOG_HIERARCHY; static final String FILESYSTEM_FULL_LOG_HIERARCHY; static final String FILESYSTEM_NOTFULL_LOG_HIERARCHY; static final String OPERATION_LOG_HIERARCHY; }### Answer:
@Test public void testVirtualhostClosed() { String name = "test"; _logMessage = VirtualHostMessages.CLOSED(name); List<Object> log = performLog(); String[] expected = {"Closed :", name}; validateLogMessage(log, "VHT-1002", expected); } |
### Question:
AppenderUtils { static void validateMaxFileSize(final int maxFileSize) { if (maxFileSize < 1) { throw new IllegalConfigurationException(String.format("Maximum file size must be at least 1. Cannot set to %d.", maxFileSize)); } } static void configureRollingFileAppender(FileLoggerSettings fileLoggerSettings,
Context loggerContext,
RollingFileAppender<ILoggingEvent> appender); }### Answer:
@Test public void testMaxFileSizeLimit() throws Exception { try { AppenderUtils.validateMaxFileSize(0); fail("exception not thrown."); } catch (IllegalConfigurationException ice) { } } |
### Question:
ManagementConsoleMessages { public static LogMessage STARTUP(String param1) { String rawMessage = _messages.getString("STARTUP"); final Object[] messageArguments = {param1}; MessageFormat formatter = new MessageFormat(rawMessage, _currentLocale); final String message = formatter.format(messageArguments); return new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return STARTUP_LOG_HIERARCHY; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LogMessage that = (LogMessage) o; return getLogHierarchy().equals(that.getLogHierarchy()) && toString().equals(that.toString()); } @Override public int hashCode() { int result = toString().hashCode(); result = 31 * result + getLogHierarchy().hashCode(); return result; } }; } private ManagementConsoleMessages(); static LogMessage CLOSE(String param1); static LogMessage LISTENING(String param1, String param2, Number param3); static LogMessage OPEN(String param1); static LogMessage READY(String param1); static LogMessage SHUTTING_DOWN(String param1, Number param2); static LogMessage STARTUP(String param1); static LogMessage STOPPED(String param1); static final String MANAGEMENTCONSOLE_LOG_HIERARCHY; static final String CLOSE_LOG_HIERARCHY; static final String LISTENING_LOG_HIERARCHY; static final String OPEN_LOG_HIERARCHY; static final String READY_LOG_HIERARCHY; static final String SHUTTING_DOWN_LOG_HIERARCHY; static final String STARTUP_LOG_HIERARCHY; static final String STOPPED_LOG_HIERARCHY; }### Answer:
@Test public void testManagementStartup() { _logMessage = ManagementConsoleMessages.STARTUP("My"); List<Object> log = performLog(); String[] expected = {"My Management Startup"}; validateLogMessage(log, "MNG-1001", expected); } |
### Question:
ManagementConsoleMessages { public static LogMessage READY(String param1) { String rawMessage = _messages.getString("READY"); final Object[] messageArguments = {param1}; MessageFormat formatter = new MessageFormat(rawMessage, _currentLocale); final String message = formatter.format(messageArguments); return new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return READY_LOG_HIERARCHY; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LogMessage that = (LogMessage) o; return getLogHierarchy().equals(that.getLogHierarchy()) && toString().equals(that.toString()); } @Override public int hashCode() { int result = toString().hashCode(); result = 31 * result + getLogHierarchy().hashCode(); return result; } }; } private ManagementConsoleMessages(); static LogMessage CLOSE(String param1); static LogMessage LISTENING(String param1, String param2, Number param3); static LogMessage OPEN(String param1); static LogMessage READY(String param1); static LogMessage SHUTTING_DOWN(String param1, Number param2); static LogMessage STARTUP(String param1); static LogMessage STOPPED(String param1); static final String MANAGEMENTCONSOLE_LOG_HIERARCHY; static final String CLOSE_LOG_HIERARCHY; static final String LISTENING_LOG_HIERARCHY; static final String OPEN_LOG_HIERARCHY; static final String READY_LOG_HIERARCHY; static final String SHUTTING_DOWN_LOG_HIERARCHY; static final String STARTUP_LOG_HIERARCHY; static final String STOPPED_LOG_HIERARCHY; }### Answer:
@Test public void testManagementReady() { _logMessage = ManagementConsoleMessages.READY("My"); List<Object> log = performLog(); String[] expected = {"My Management Ready"}; validateLogMessage(log, "MNG-1004", expected); } |
### Question:
MessageStoreMessages { public static LogMessage CREATED() { String rawMessage = _messages.getString("CREATED"); final String message = rawMessage; return new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return CREATED_LOG_HIERARCHY; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LogMessage that = (LogMessage) o; return getLogHierarchy().equals(that.getLogHierarchy()) && toString().equals(that.toString()); } @Override public int hashCode() { int result = toString().hashCode(); result = 31 * result + getLogHierarchy().hashCode(); return result; } }; } private MessageStoreMessages(); static LogMessage CLOSED(); static LogMessage CREATED(); static LogMessage OVERFULL(); static LogMessage RECOVERED(Number param1); static LogMessage RECOVERY_COMPLETE(); static LogMessage RECOVERY_START(); static LogMessage STORE_LOCATION(String param1); static LogMessage UNDERFULL(); static final String MESSAGESTORE_LOG_HIERARCHY; static final String CLOSED_LOG_HIERARCHY; static final String CREATED_LOG_HIERARCHY; static final String OVERFULL_LOG_HIERARCHY; static final String RECOVERED_LOG_HIERARCHY; static final String RECOVERY_COMPLETE_LOG_HIERARCHY; static final String RECOVERY_START_LOG_HIERARCHY; static final String STORE_LOCATION_LOG_HIERARCHY; static final String UNDERFULL_LOG_HIERARCHY; }### Answer:
@Test public void testMessageStoreCreated() { _logMessage = MessageStoreMessages.CREATED(); List<Object> log = performLog(); String[] expected = {"Created"}; validateLogMessage(log, "MST-1001", expected); } |
### Question:
QpidLoggerTurboFilter extends TurboFilter { public static void uninstall(LoggerContext context) { context.getTurboFilterList().remove(new QpidLoggerTurboFilter()); } QpidLoggerTurboFilter(); @Override FilterReply decide(final Marker marker,
final Logger logger,
final Level level,
final String format,
final Object[] params,
final Throwable t); void filterAdded(EffectiveLevelFilter filter); void filterRemoved(EffectiveLevelFilter filter); void filterChanged(EffectiveLevelFilter filter); @Override boolean equals(final Object o); @Override int hashCode(); static QpidLoggerTurboFilter installIfNecessary(LoggerContext loggerContext); static QpidLoggerTurboFilter installIfNecessaryToRootContext(); static void uninstallFromRootContext(); static void uninstall(LoggerContext context); static void filterAdded(EffectiveLevelFilter filter, LoggerContext context); static void filterRemoved(EffectiveLevelFilter filter, LoggerContext context); static void filterAddedToRootContext(EffectiveLevelFilter filter); static void filterRemovedFromRootContext(EffectiveLevelFilter filter); static void filterChangedOnRootContext(final EffectiveLevelFilter filter); }### Answer:
@Test public void testUninstall() { Logger fooBarLogger = _loggerContext.getLogger("foo.bar"); assertFalse( "Debug should not be enabled when QpidLoggerTurboFilter is installed but no regular filter is set", fooBarLogger.isDebugEnabled()); QpidLoggerTurboFilter.uninstall(_loggerContext); assertTrue("Debug should be enabled as per test logback configuration", fooBarLogger.isDebugEnabled()); } |
### Question:
MessageStoreMessages { public static LogMessage CLOSED() { String rawMessage = _messages.getString("CLOSED"); final String message = rawMessage; return new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return CLOSED_LOG_HIERARCHY; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LogMessage that = (LogMessage) o; return getLogHierarchy().equals(that.getLogHierarchy()) && toString().equals(that.toString()); } @Override public int hashCode() { int result = toString().hashCode(); result = 31 * result + getLogHierarchy().hashCode(); return result; } }; } private MessageStoreMessages(); static LogMessage CLOSED(); static LogMessage CREATED(); static LogMessage OVERFULL(); static LogMessage RECOVERED(Number param1); static LogMessage RECOVERY_COMPLETE(); static LogMessage RECOVERY_START(); static LogMessage STORE_LOCATION(String param1); static LogMessage UNDERFULL(); static final String MESSAGESTORE_LOG_HIERARCHY; static final String CLOSED_LOG_HIERARCHY; static final String CREATED_LOG_HIERARCHY; static final String OVERFULL_LOG_HIERARCHY; static final String RECOVERED_LOG_HIERARCHY; static final String RECOVERY_COMPLETE_LOG_HIERARCHY; static final String RECOVERY_START_LOG_HIERARCHY; static final String STORE_LOCATION_LOG_HIERARCHY; static final String UNDERFULL_LOG_HIERARCHY; }### Answer:
@Test public void testMessageStoreClosed() { _logMessage = MessageStoreMessages.CLOSED(); List<Object> log = performLog(); String[] expected = {"Closed"}; validateLogMessage(log, "MST-1003", expected); } |
### Question:
MessageStoreMessages { public static LogMessage RECOVERY_START() { String rawMessage = _messages.getString("RECOVERY_START"); final String message = rawMessage; return new LogMessage() { @Override public String toString() { return message; } @Override public String getLogHierarchy() { return RECOVERY_START_LOG_HIERARCHY; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final LogMessage that = (LogMessage) o; return getLogHierarchy().equals(that.getLogHierarchy()) && toString().equals(that.toString()); } @Override public int hashCode() { int result = toString().hashCode(); result = 31 * result + getLogHierarchy().hashCode(); return result; } }; } private MessageStoreMessages(); static LogMessage CLOSED(); static LogMessage CREATED(); static LogMessage OVERFULL(); static LogMessage RECOVERED(Number param1); static LogMessage RECOVERY_COMPLETE(); static LogMessage RECOVERY_START(); static LogMessage STORE_LOCATION(String param1); static LogMessage UNDERFULL(); static final String MESSAGESTORE_LOG_HIERARCHY; static final String CLOSED_LOG_HIERARCHY; static final String CREATED_LOG_HIERARCHY; static final String OVERFULL_LOG_HIERARCHY; static final String RECOVERED_LOG_HIERARCHY; static final String RECOVERY_COMPLETE_LOG_HIERARCHY; static final String RECOVERY_START_LOG_HIERARCHY; static final String STORE_LOCATION_LOG_HIERARCHY; static final String UNDERFULL_LOG_HIERARCHY; }### Answer:
@Test public void testMessageStoreRecoveryStart() { _logMessage = MessageStoreMessages.RECOVERY_START(); List<Object> log = performLog(); String[] expected = {"Recovery Start"}; validateLogMessage(log, "MST-1004", expected); } |
### Question:
TrustStoreMessageSource extends AbstractSystemMessageSource { @Override public <T extends ConsumerTarget<T>> Consumer<T> addConsumer(final T target, final FilterManager filters, final Class<? extends ServerMessage> messageClass, final String consumerName, final EnumSet<ConsumerOption> options, final Integer priority) throws ExistingExclusiveConsumer, ExistingConsumerPreventsExclusive, ConsumerAccessRefused, QueueDeleted { final Consumer<T> consumer = super.addConsumer(target, filters, messageClass, consumerName, options, priority); consumer.send(createMessage()); target.noMessagesAvailable(); return consumer; } TrustStoreMessageSource(final TrustStore<?> trustStore, final VirtualHost<?> virtualHost); @Override Consumer<T> addConsumer(final T target,
final FilterManager filters,
final Class<? extends ServerMessage> messageClass,
final String consumerName,
final EnumSet<ConsumerOption> options, final Integer priority); @Override void close(); static String getSourceNameFromTrustStore(final TrustStore<?> trustStore); }### Answer:
@Test public void testAddConsumer() throws Exception { final EnumSet<ConsumerOption> options = EnumSet.noneOf(ConsumerOption.class); final ConsumerTarget target = mock(ConsumerTarget.class); when(target.allocateCredit(any(ServerMessage.class))).thenReturn(true); MessageInstanceConsumer consumer = _trustStoreMessageSource.addConsumer(target, null, ServerMessage.class, getTestName(), options, 0); final MessageContainer messageContainer = consumer.pullMessage(); assertNotNull("Could not pull message of TrustStore", messageContainer); final ServerMessage message = messageContainer.getMessageInstance().getMessage(); assertCertificates(getCertificatesFromMessage(message)); } |
### Question:
AESKeyFileEncrypter implements ConfigurationSecretEncrypter { @Override public String encrypt(final String unencrypted) { byte[] unencryptedBytes = unencrypted.getBytes(StandardCharsets.UTF_8); try { byte[] ivbytes = new byte[AES_INITIALIZATION_VECTOR_LENGTH]; _random.nextBytes(ivbytes); Cipher cipher = Cipher.getInstance(CIPHER_NAME); cipher.init(Cipher.ENCRYPT_MODE, _secretKey, new IvParameterSpec(ivbytes)); byte[] encryptedBytes = readFromCipherStream(unencryptedBytes, cipher); byte[] output = new byte[AES_INITIALIZATION_VECTOR_LENGTH + encryptedBytes.length]; System.arraycopy(ivbytes, 0, output, 0, AES_INITIALIZATION_VECTOR_LENGTH); System.arraycopy(encryptedBytes, 0, output, AES_INITIALIZATION_VECTOR_LENGTH, encryptedBytes.length); return Base64.getEncoder().encodeToString(output); } catch (IOException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) { throw new IllegalArgumentException("Unable to encrypt secret", e); } } AESKeyFileEncrypter(SecretKey secretKey); @Override String encrypt(final String unencrypted); @Override String decrypt(final String encrypted); }### Answer:
@Test public void testEncryptingNullFails() throws Exception { if(isStrongEncryptionEnabled()) { try { SecretKeySpec secretKey = createSecretKey(); AESKeyFileEncrypter encrypter = new AESKeyFileEncrypter(secretKey); String encrypted = encrypter.encrypt(null); fail("Attempting to encrypt null should fail"); } catch (NullPointerException e) { } } } |
### Question:
GroupPrincipal implements QpidPrincipal { @Override public String getName() { return _groupName; } GroupPrincipal(final String groupName, final ConfiguredObject<?> origin); @Override String getName(); boolean addMember(Principal user); boolean removeMember(Principal user); boolean isMember(Principal member); Enumeration<? extends Principal> members(); @Override ConfiguredObject<?> getOrigin(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testGetName() { final GroupPrincipal principal = new GroupPrincipal("group", (GroupProvider) null); assertEquals("group", principal.getName()); } |
### Question:
GroupPrincipal implements QpidPrincipal { public boolean addMember(Principal user) { throw new UnsupportedOperationException(msgException); } GroupPrincipal(final String groupName, final ConfiguredObject<?> origin); @Override String getName(); boolean addMember(Principal user); boolean removeMember(Principal user); boolean isMember(Principal member); Enumeration<? extends Principal> members(); @Override ConfiguredObject<?> getOrigin(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testAddRejected() { final GroupPrincipal principal = new GroupPrincipal("group", (GroupProvider) null); final UsernamePrincipal user = new UsernamePrincipal("name", null); try { principal.addMember(user); fail("Exception not thrown"); } catch (UnsupportedOperationException uso) { } } |
### Question:
GroupPrincipal implements QpidPrincipal { @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final GroupPrincipal that = (GroupPrincipal) o; if (!_groupName.equals(that._groupName)) { return false; } return _origin != null ? _origin.equals(that._origin) : that._origin == null; } GroupPrincipal(final String groupName, final ConfiguredObject<?> origin); @Override String getName(); boolean addMember(Principal user); boolean removeMember(Principal user); boolean isMember(Principal member); Enumeration<? extends Principal> members(); @Override ConfiguredObject<?> getOrigin(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEqualitySameName() { final String string = "string"; final GroupPrincipal principal1 = new GroupPrincipal(string, (GroupProvider) null); final GroupPrincipal principal2 = new GroupPrincipal(string, (GroupProvider) null); assertTrue(principal1.equals(principal2)); }
@Test public void testEqualityEqualName() { final GroupPrincipal principal1 = new GroupPrincipal(new String("string"), (GroupProvider) null); final GroupPrincipal principal2 = new GroupPrincipal(new String("string"), (GroupProvider) null); assertTrue(principal1.equals(principal2)); }
@Test public void testInequalityDifferentGroupPrincipals() { GroupPrincipal principal1 = new GroupPrincipal("string1", (GroupProvider) null); GroupPrincipal principal2 = new GroupPrincipal("string2", (GroupProvider) null); assertFalse(principal1.equals(principal2)); }
@Test public void testInequalityNonGroupPrincipal() { GroupPrincipal principal = new GroupPrincipal("string", (GroupProvider) null); assertFalse(principal.equals(new UsernamePrincipal("string", null))); }
@Test public void testInequalityNull() { GroupPrincipal principal = new GroupPrincipal("string", (GroupProvider) null); assertFalse(principal.equals(null)); } |
### Question:
FileGroupDatabase implements GroupDatabase { @Override public Set<String> getAllGroups() { return Collections.unmodifiableSet(_groupToUserMap.keySet()); } FileGroupDatabase(FileBasedGroupProvider<?> groupProvider); @Override Set<String> getAllGroups(); synchronized void setGroupFile(String groupFile); @Override Set<String> getUsersInGroup(String group); @Override synchronized void addUserToGroup(String user, String group); @Override synchronized void removeUserFromGroup(String user, String group); @Override Set<String> getGroupsForUser(String user); @Override synchronized void createGroup(String group); @Override synchronized void removeGroup(String group); }### Answer:
@Test public void testGetAllGroups() throws Exception { _util.writeAndSetGroupFile("myGroup.users", USER1); Set<String> groups = _fileGroupDatabase.getAllGroups(); assertEquals(1, groups.size()); assertTrue(groups.contains(MY_GROUP)); }
@Test public void testGetAllGroupsWhenGroupFileEmpty() { Set<String> groups = _fileGroupDatabase.getAllGroups(); assertTrue(groups.isEmpty()); } |
### Question:
StartupAppender extends AppenderBase<ILoggingEvent> { public synchronized void replayAccumulatedEvents(Appender<ILoggingEvent> appender) { for (ILoggingEvent event: _accumulatedLoggingEvents) { appender.doAppend(event); } } StartupAppender(); synchronized void replayAccumulatedEvents(Appender<ILoggingEvent> appender); void logToConsole(); @Override void stop(); static final String PROPERTY_STARTUP_FAILOVER_CONSOLE_LOG_LEVEL; }### Answer:
@SuppressWarnings("unchecked") @Test public void testReplayAccumulatedEvents() { ILoggingEvent event1 = createMockLoggingEvent("org.apache.qpid.Test", Level.DEBUG, "Test1", "Test-Thread-1"); _startupAppender.doAppend(event1); ILoggingEvent event2 = createMockLoggingEvent("non.qpid.Test", Level.INFO, "Test2", "Test-Thread-2"); _startupAppender.doAppend(event2); Appender mockAppender = mock(Appender.class); _startupAppender.replayAccumulatedEvents(mockAppender); verify(mockAppender).doAppend(event1); verify(mockAppender).doAppend(event2); } |
### Question:
FileGroupDatabase implements GroupDatabase { public synchronized void setGroupFile(String groupFile) throws IOException { File file = new File(groupFile); if (!file.canRead()) { throw new FileNotFoundException(groupFile + " cannot be found or is not readable"); } readGroupFile(groupFile); } FileGroupDatabase(FileBasedGroupProvider<?> groupProvider); @Override Set<String> getAllGroups(); synchronized void setGroupFile(String groupFile); @Override Set<String> getUsersInGroup(String group); @Override synchronized void addUserToGroup(String user, String group); @Override synchronized void removeUserFromGroup(String user, String group); @Override Set<String> getGroupsForUser(String user); @Override synchronized void createGroup(String group); @Override synchronized void removeGroup(String group); }### Answer:
@Test public void testMissingGroupFile() throws Exception { try { _fileGroupDatabase.setGroupFile("/not/a/file"); fail("Exception not thrown"); } catch (FileNotFoundException fnfe) { } } |
### Question:
VirtualHostLogEventExcludingFilter extends Filter<ILoggingEvent> implements LogBackLogInclusionRule { @Override public FilterReply decide(ILoggingEvent event) { if (!_brokerLogger.isVirtualHostLogEventExcluded() || !subjectContainsVirtualHostPrincipal()) { return FilterReply.NEUTRAL; } return FilterReply.DENY; } VirtualHostLogEventExcludingFilter(BrokerLogger<?> brokerLogger); @Override Filter<ILoggingEvent> asFilter(); @Override String getName(); @Override FilterReply decide(ILoggingEvent event); }### Answer:
@Test public void testDecideOnVirtualHostLogEventNotExcludedAndNullSubject() throws Exception { FilterReply reply = _filter.decide(_loggingEvent); assertEquals(" BrokerLogger#virtualHostLogEventExcluded=false and subject=null", FilterReply.NEUTRAL, reply); assertNull("Subject should not be set in test environment", Subject.getSubject(AccessController.getContext())); }
@Test public void testDecideOnVirtualHostLogEventExcludedAndNullSubject() throws Exception { when(_brokerLogger.isVirtualHostLogEventExcluded()).thenReturn(true); FilterReply reply = _filter.decide(_loggingEvent); assertEquals(" BrokerLogger#virtualHostLogEventExcluded=true and subject=null", FilterReply.NEUTRAL, reply); assertNull("Subject should not be set in test environment", Subject.getSubject(AccessController.getContext())); } |
### Question:
SimpleAuthenticationManager extends AbstractAuthenticationManager<SimpleAuthenticationManager> implements PasswordCredentialManagingAuthenticationProvider<SimpleAuthenticationManager> { @Override public List<String> getMechanisms() { return Collections.unmodifiableList(Arrays.asList(PLAIN_MECHANISM, CRAM_MD5_MECHANISM, SCRAM_SHA1_MECHANISM, SCRAM_SHA256_MECHANISM)); } SimpleAuthenticationManager(final Map<String, Object> attributes, final Container<?> container); void addUser(String username, String password); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); @Override AuthenticationResult authenticate(String username, String password); @Override boolean createUser(final String username, final String password, final Map<String, String> attributes); @Override void deleteUser(final String username); @Override void setPassword(final String username, final String password); @Override Map<String, Map<String, String>> getUsers(); @Override void reload(); }### Answer:
@Test public void testGetMechanisms() { List<String> mechanisms = _authenticationManager.getMechanisms(); assertEquals("Unexpected number of mechanisms", (long) 4, (long) mechanisms.size()); assertTrue("PLAIN was not present: " + mechanisms, mechanisms.contains("PLAIN")); assertTrue("CRAM-MD5 was not present: " + mechanisms, mechanisms.contains("CRAM-MD5")); assertTrue("SCRAM-SHA-1 was not present: " + mechanisms, mechanisms.contains("SCRAM-SHA-1")); assertTrue("SCRAM-SHA-256 was not present: " + mechanisms, mechanisms.contains("SCRAM-SHA-256")); } |
### Question:
SimpleAuthenticationManager extends AbstractAuthenticationManager<SimpleAuthenticationManager> implements PasswordCredentialManagingAuthenticationProvider<SimpleAuthenticationManager> { @Override public AuthenticationResult authenticate(String username, String password) { if (_users.containsKey(username)) { String userPassword = _users.get(username); if (userPassword.equals(password)) { return new AuthenticationResult(new UsernamePrincipal(username, this)); } } return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR); } SimpleAuthenticationManager(final Map<String, Object> attributes, final Container<?> container); void addUser(String username, String password); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); @Override AuthenticationResult authenticate(String username, String password); @Override boolean createUser(final String username, final String password, final Map<String, String> attributes); @Override void deleteUser(final String username); @Override void setPassword(final String username, final String password); @Override Map<String, Map<String, String>> getUsers(); @Override void reload(); }### Answer:
@Test public void testAuthenticateValidCredentials() { AuthenticationResult result = _authenticationManager.authenticate(TEST_USER, TEST_PASSWORD); assertEquals("Unexpected authentication result", AuthenticationStatus.SUCCESS, result.getStatus()); assertAuthenticated(result); }
@Test public void testAuthenticateInvalidPassword() { AuthenticationResult result = _authenticationManager.authenticate(TEST_USER, "invalid"); assertUnauthenticated(result); }
@Test public void testAuthenticateInvalidUserName() { AuthenticationResult result = _authenticationManager.authenticate("invalid", TEST_PASSWORD); assertUnauthenticated(result); } |
### Question:
AnonymousAuthenticationManager extends AbstractAuthenticationManager<AnonymousAuthenticationManager> { @Override public List<String> getMechanisms() { return Collections.singletonList(MECHANISM_NAME); } @ManagedObjectFactoryConstructor protected AnonymousAuthenticationManager(final Map<String, Object> attributes, final Container<?> container); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); Principal getAnonymousPrincipal(); AuthenticationResult getAnonymousAuthenticationResult(); static final String PROVIDER_TYPE; static final String MECHANISM_NAME; static final String ANONYMOUS_USERNAME; }### Answer:
@Test public void testGetMechanisms() throws Exception { assertEquals(Collections.singletonList("ANONYMOUS"), _manager.getMechanisms()); } |
### Question:
AnonymousAuthenticationManager extends AbstractAuthenticationManager<AnonymousAuthenticationManager> { @Override public SaslNegotiator createSaslNegotiator(final String mechanism, final SaslSettings saslSettings, final NamedAddressSpace addressSpace) { if(MECHANISM_NAME.equals(mechanism)) { return new AnonymousNegotiator(_anonymousAuthenticationResult); } else { return null; } } @ManagedObjectFactoryConstructor protected AnonymousAuthenticationManager(final Map<String, Object> attributes, final Container<?> container); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); Principal getAnonymousPrincipal(); AuthenticationResult getAnonymousAuthenticationResult(); static final String PROVIDER_TYPE; static final String MECHANISM_NAME; static final String ANONYMOUS_USERNAME; }### Answer:
@Test public void testCreateSaslNegotiator() throws Exception { SaslNegotiator negotiator = _manager.createSaslNegotiator("ANONYMOUS", null, null); assertNotNull("Could not create SASL negotiator for mechanism 'ANONYMOUS'", negotiator); negotiator = _manager.createSaslNegotiator("PLAIN", null, null); assertNull("Should not be able to create SASL negotiator for mechanism 'PLAIN'", negotiator); } |
### Question:
RolloverWatcher implements RollingPolicyDecorator.RolloverListener { @Override public void onRollover(Path baseFolder, String[] relativeFileNames) { _rolledFiles = Collections.unmodifiableCollection(Arrays.asList(relativeFileNames)); _baseFolder = baseFolder; } RolloverWatcher(final String activeFileName); @Override void onRollover(Path baseFolder, String[] relativeFileNames); @Override void onNoRolloverDetected(final Path baseFolder, final String[] relativeFileNames); PathContent getFileContent(String fileName); Collection<String> getRolledFiles(); List<LogFileDetails> getLogFileDetails(); String getContentType(String fileName); ZippedContent getFilesAsZippedContent(Set<String> fileNames); ZippedContent getAllFilesAsZippedContent(); }### Answer:
@Test public void testOnRollover() throws Exception { String[] files = {"test1", "test2"}; _rolloverWatcher.onRollover(_baseFolder.toPath(), files); assertEquals("Unexpected rolled files. Expected " + Arrays.toString(files) + " but got " + _rolloverWatcher.getRolledFiles(), new HashSet<>(Arrays.asList(files)), new HashSet<>(_rolloverWatcher.getRolledFiles())); } |
### Question:
KerberosAuthenticationManager extends AbstractAuthenticationManager<KerberosAuthenticationManager> { @Override public SaslNegotiator createSaslNegotiator(final String mechanism, final SaslSettings saslSettings, final NamedAddressSpace addressSpace) { if(GSSAPI_MECHANISM.equals(mechanism)) { final String serverName = _serverName == null ? saslSettings.getLocalFQDN(): _serverName; return new KerberosNegotiator(this, serverName); } else { return null; } } @ManagedObjectFactoryConstructor protected KerberosAuthenticationManager(final Map<String, Object> attributes, final Container<?> container); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); AuthenticationResult authenticate(String authorizationHeader); String getSpnegoLoginConfigScope(); boolean isStripRealmFromPrincipalName(); static final String PROVIDER_TYPE; static final String GSSAPI_MECHANISM; }### Answer:
@Test public void testCreateSaslNegotiator() throws Exception { final SaslSettings saslSettings = mock(SaslSettings.class); when(saslSettings.getLocalFQDN()).thenReturn(HOST_NAME); final SaslNegotiator negotiator = _kerberosAuthenticationProvider.createSaslNegotiator(GSSAPI_MECHANISM, saslSettings, null); assertNotNull("Could not create SASL negotiator", negotiator); try { final AuthenticationResult result = authenticate(negotiator); assertEquals(AuthenticationResult.AuthenticationStatus.SUCCESS, result.getStatus()); assertEquals(new KerberosPrincipal(CLIENT_PRINCIPAL_FULL_NAME).getName(), result.getMainPrincipal().getName()); } finally { negotiator.dispose(); } } |
### Question:
KerberosAuthenticationManager extends AbstractAuthenticationManager<KerberosAuthenticationManager> { public AuthenticationResult authenticate(String authorizationHeader) { return _authenticator.authenticate(authorizationHeader); } @ManagedObjectFactoryConstructor protected KerberosAuthenticationManager(final Map<String, Object> attributes, final Container<?> container); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); AuthenticationResult authenticate(String authorizationHeader); String getSpnegoLoginConfigScope(); boolean isStripRealmFromPrincipalName(); static final String PROVIDER_TYPE; static final String GSSAPI_MECHANISM; }### Answer:
@Test public void testAuthenticateUsingNegotiationToken() throws Exception { byte[] negotiationTokenBytes = UTILS.buildToken(CLIENT_PRINCIPAL_NAME, _clientKeyTabFile, SERVICE_PRINCIPAL_NAME); final String token = Base64.getEncoder().encodeToString(negotiationTokenBytes); final String authenticationHeader = SpnegoAuthenticator.NEGOTIATE_PREFIX + token; final AuthenticationResult result = _kerberosAuthenticationProvider.authenticate(authenticationHeader); assertNotNull(result); assertEquals(AuthenticationResult.AuthenticationStatus.SUCCESS, result.getStatus()); } |
### Question:
PrincipalDatabaseAuthenticationManager extends AbstractAuthenticationManager<T> implements ExternalFileBasedAuthenticationManager<T> { public void initialise() { try { _principalDatabase.open(new File(_path)); } catch (FileNotFoundException e) { throw new IllegalConfigurationException("Exception opening password database: " + e.getMessage(), e); } catch (IOException e) { throw new IllegalConfigurationException("Cannot use password database at :" + _path, e); } } protected PrincipalDatabaseAuthenticationManager(final Map<String, Object> attributes, final Container<?> broker); @Override String getPath(); void initialise(); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); @Override AuthenticationResult authenticate(final String username, final String password); PrincipalDatabase getPrincipalDatabase(); @Override @StateTransition(currentState = {State.UNINITIALIZED,State.ERRORED}, desiredState = State.ACTIVE) ListenableFuture<Void> activate(); @Override boolean createUser(String username, String password, Map<String, String> attributes); @Override void deleteUser(String username); @Override void setPassword(String username, String password); @Override Map<String, Map<String, String>> getUsers(); @Override void reload(); }### Answer:
@Test public void testInitialiseWhenPasswordFileNotFound() throws Exception { PasswordCredentialManagingAuthenticationProvider mockAuthProvider = mock(PasswordCredentialManagingAuthenticationProvider.class); when(mockAuthProvider.getContextValue(Integer.class, AbstractScramAuthenticationManager.QPID_AUTHMANAGER_SCRAM_ITERATION_COUNT)).thenReturn(4096); _principalDatabase = new PlainPasswordFilePrincipalDatabase(mockAuthProvider); setupManager(true); try { _manager.initialise(); fail("Initialisiation should fail when users file does not exist"); } catch (IllegalConfigurationException e) { final boolean condition = e.getCause() instanceof FileNotFoundException; assertTrue(condition); } } |
### Question:
PrincipalDatabaseAuthenticationManager extends AbstractAuthenticationManager<T> implements ExternalFileBasedAuthenticationManager<T> { @Override public SaslNegotiator createSaslNegotiator(final String mechanism, final SaslSettings saslSettings, final NamedAddressSpace addressSpace) { return _principalDatabase.createSaslNegotiator(mechanism, saslSettings); } protected PrincipalDatabaseAuthenticationManager(final Map<String, Object> attributes, final Container<?> broker); @Override String getPath(); void initialise(); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); @Override AuthenticationResult authenticate(final String username, final String password); PrincipalDatabase getPrincipalDatabase(); @Override @StateTransition(currentState = {State.UNINITIALIZED,State.ERRORED}, desiredState = State.ACTIVE) ListenableFuture<Void> activate(); @Override boolean createUser(String username, String password, Map<String, String> attributes); @Override void deleteUser(String username); @Override void setPassword(String username, String password); @Override Map<String, Map<String, String>> getUsers(); @Override void reload(); }### Answer:
@Test public void testSaslMechanismCreation() throws Exception { setupMocks(); SaslSettings saslSettings = mock(SaslSettings.class); SaslNegotiator saslNegotiator = _manager.createSaslNegotiator(MOCK_MECH_NAME, saslSettings, null); assertNotNull(saslNegotiator); } |
### Question:
RolloverWatcher implements RollingPolicyDecorator.RolloverListener { public PathContent getFileContent(String fileName) { if (fileName == null) { throw new IllegalArgumentException("File name cannot be null"); } Path path = getPath(fileName); return new PathContent(path, getContentType(fileName)); } RolloverWatcher(final String activeFileName); @Override void onRollover(Path baseFolder, String[] relativeFileNames); @Override void onNoRolloverDetected(final Path baseFolder, final String[] relativeFileNames); PathContent getFileContent(String fileName); Collection<String> getRolledFiles(); List<LogFileDetails> getLogFileDetails(); String getContentType(String fileName); ZippedContent getFilesAsZippedContent(Set<String> fileNames); ZippedContent getAllFilesAsZippedContent(); }### Answer:
@Test public void testGetTypedForNullFile() throws Exception { try { _rolloverWatcher.getFileContent(null); fail("IllegalArgumentException is expected for null file name"); } catch (IllegalArgumentException e) { } } |
### Question:
PrincipalDatabaseAuthenticationManager extends AbstractAuthenticationManager<T> implements ExternalFileBasedAuthenticationManager<T> { @Override protected void onCreate() { super.onCreate(); File passwordFile = new File(_path); if (!passwordFile.exists()) { try { Path path = new FileHelper().createNewFile(passwordFile, getContextValue(String.class, SystemConfig.POSIX_FILE_PERMISSIONS)); if (!Files.exists(path)) { throw new IllegalConfigurationException(String.format("Cannot create password file at '%s'", _path)); } } catch (IOException e) { throw new IllegalConfigurationException(String.format("Cannot create password file at '%s'", _path), e); } } } protected PrincipalDatabaseAuthenticationManager(final Map<String, Object> attributes, final Container<?> broker); @Override String getPath(); void initialise(); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); @Override AuthenticationResult authenticate(final String username, final String password); PrincipalDatabase getPrincipalDatabase(); @Override @StateTransition(currentState = {State.UNINITIALIZED,State.ERRORED}, desiredState = State.ACTIVE) ListenableFuture<Void> activate(); @Override boolean createUser(String username, String password, Map<String, String> attributes); @Override void deleteUser(String username); @Override void setPassword(String username, String password); @Override Map<String, Map<String, String>> getUsers(); @Override void reload(); }### Answer:
@Test public void testOnCreate() throws Exception { setupMocks(); assertTrue("Password file was not created", new File(_passwordFileLocation).exists()); } |
### Question:
PrincipalDatabaseAuthenticationManager extends AbstractAuthenticationManager<T> implements ExternalFileBasedAuthenticationManager<T> { @Override protected ListenableFuture<Void> onDelete() { return doAfterAlways(closeChildren(), () -> { File file = new File(_path); if (file.exists() && file.isFile()) { file.delete(); } }); } protected PrincipalDatabaseAuthenticationManager(final Map<String, Object> attributes, final Container<?> broker); @Override String getPath(); void initialise(); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism,
final SaslSettings saslSettings,
final NamedAddressSpace addressSpace); @Override AuthenticationResult authenticate(final String username, final String password); PrincipalDatabase getPrincipalDatabase(); @Override @StateTransition(currentState = {State.UNINITIALIZED,State.ERRORED}, desiredState = State.ACTIVE) ListenableFuture<Void> activate(); @Override boolean createUser(String username, String password, Map<String, String> attributes); @Override void deleteUser(String username); @Override void setPassword(String username, String password); @Override Map<String, Map<String, String>> getUsers(); @Override void reload(); }### Answer:
@Test public void testOnDelete() throws Exception { setupMocks(); assertTrue("Password file was not created", new File(_passwordFileLocation).exists()); _manager.delete(); assertFalse("Password file was not deleted", new File(_passwordFileLocation).exists()); } |
### Question:
AuthenticatedPrincipal implements QpidPrincipal { public static AuthenticatedPrincipal getAuthenticatedPrincipalFromSubject(final Subject authSubject) { return getAuthenticatedPrincipalFromSubject(authSubject, false); } AuthenticatedPrincipal(Principal wrappedPrincipal); static AuthenticatedPrincipal getCurrentUser(); @Override ConfiguredObject<?> getOrigin(); @Override String getName(); @Override int hashCode(); @Override boolean equals(Object obj); static AuthenticatedPrincipal getOptionalAuthenticatedPrincipalFromSubject(final Subject authSubject); static AuthenticatedPrincipal getAuthenticatedPrincipalFromSubject(final Subject authSubject); @Override String toString(); }### Answer:
@Test public void testGetAuthenticatedPrincipalFromSubject() { final Subject subject = createSubjectContainingAuthenticatedPrincipal(); final AuthenticatedPrincipal actual = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); assertSame(_authenticatedPrincipal, actual); }
@Test public void testAuthenticatedPrincipalNotInSubject() { try { AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(new Subject()); fail("Exception not thrown"); } catch (IllegalArgumentException iae) { } }
@Test public void testTooManyAuthenticatedPrincipalsInSubject() { final Subject subject = new Subject(); subject.getPrincipals().add(new AuthenticatedPrincipal(new UsernamePrincipal("name1", null))); subject.getPrincipals().add(new AuthenticatedPrincipal(new UsernamePrincipal("name2", null))); try { AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); fail("Exception not thrown"); } catch (IllegalArgumentException iae) { } } |
### Question:
AuthenticatedPrincipal implements QpidPrincipal { public static AuthenticatedPrincipal getOptionalAuthenticatedPrincipalFromSubject(final Subject authSubject) { return getAuthenticatedPrincipalFromSubject(authSubject, true); } AuthenticatedPrincipal(Principal wrappedPrincipal); static AuthenticatedPrincipal getCurrentUser(); @Override ConfiguredObject<?> getOrigin(); @Override String getName(); @Override int hashCode(); @Override boolean equals(Object obj); static AuthenticatedPrincipal getOptionalAuthenticatedPrincipalFromSubject(final Subject authSubject); static AuthenticatedPrincipal getAuthenticatedPrincipalFromSubject(final Subject authSubject); @Override String toString(); }### Answer:
@Test public void testGetOptionalAuthenticatedPrincipalFromSubject() { final Subject subject = createSubjectContainingAuthenticatedPrincipal(); final AuthenticatedPrincipal actual = AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(subject); assertSame(_authenticatedPrincipal, actual); }
@Test public void testGetOptionalAuthenticatedPrincipalFromSubjectReturnsNullIfMissing() { Subject subjectWithNoPrincipals = new Subject(); assertNull(AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(subjectWithNoPrincipals)); Subject subjectWithoutAuthenticatedPrincipal = new Subject(); subjectWithoutAuthenticatedPrincipal.getPrincipals().add(new UsernamePrincipal("name1", null)); assertNull("Should return null for a subject containing a principal that isn't an AuthenticatedPrincipal", AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(subjectWithoutAuthenticatedPrincipal)); } |
### Question:
AuthenticatedPrincipal implements QpidPrincipal { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof AuthenticatedPrincipal)) { return false; } AuthenticatedPrincipal other = (AuthenticatedPrincipal) obj; return _wrappedPrincipal.equals(other._wrappedPrincipal); } AuthenticatedPrincipal(Principal wrappedPrincipal); static AuthenticatedPrincipal getCurrentUser(); @Override ConfiguredObject<?> getOrigin(); @Override String getName(); @Override int hashCode(); @Override boolean equals(Object obj); static AuthenticatedPrincipal getOptionalAuthenticatedPrincipalFromSubject(final Subject authSubject); static AuthenticatedPrincipal getAuthenticatedPrincipalFromSubject(final Subject authSubject); @Override String toString(); }### Answer:
@Test public void testEqualsWithDifferentUsernames() { AuthenticatedPrincipal user1principal1 = new AuthenticatedPrincipal(new UsernamePrincipal("user1", null)); AuthenticatedPrincipal user1principal2 = new AuthenticatedPrincipal(new UsernamePrincipal("user2", null)); assertFalse(user1principal1.equals(user1principal2)); assertFalse(user1principal2.equals(user1principal1)); }
@Test public void testEqualsWithDissimilarObjects() { UsernamePrincipal wrappedPrincipal = new UsernamePrincipal("user1", null); AuthenticatedPrincipal authenticatedPrincipal = new AuthenticatedPrincipal(wrappedPrincipal); assertFalse(authenticatedPrincipal.equals(wrappedPrincipal)); assertFalse(wrappedPrincipal.equals(authenticatedPrincipal)); } |
### Question:
RolloverWatcher implements RollingPolicyDecorator.RolloverListener { public String getContentType(String fileName) { String fileNameLower = fileName.toLowerCase(); if (fileNameLower.endsWith(".gz")) { return "application/x-gzip"; } else if (fileNameLower.endsWith(".zip")) { return "application/x-zip"; } else { return "text/plain"; } } RolloverWatcher(final String activeFileName); @Override void onRollover(Path baseFolder, String[] relativeFileNames); @Override void onNoRolloverDetected(final Path baseFolder, final String[] relativeFileNames); PathContent getFileContent(String fileName); Collection<String> getRolledFiles(); List<LogFileDetails> getLogFileDetails(); String getContentType(String fileName); ZippedContent getFilesAsZippedContent(Set<String> fileNames); ZippedContent getAllFilesAsZippedContent(); }### Answer:
@Test public void testGetContentType() throws Exception { assertEquals("Unexpected content type for log file", "text/plain", _rolloverWatcher.getContentType("test.log")); assertEquals("Unexpected content type for gzip file", "application/x-gzip", _rolloverWatcher.getContentType("test.gz")); assertEquals("Unexpected content type for zip file", "application/x-zip", _rolloverWatcher.getContentType("test.zip")); } |
### Question:
PlainPasswordFilePrincipalDatabase extends AbstractPasswordFilePrincipalDatabase<PlainUser> { @Override public boolean verifyPassword(String principal, char[] password) throws AccountNotFoundException { char[] pwd = lookupPassword(principal); if (pwd == null) { throw new AccountNotFoundException("Unable to lookup the specified users password"); } return compareCharArray(pwd, password); } PlainPasswordFilePrincipalDatabase(PasswordCredentialManagingAuthenticationProvider<?> authenticationProvider); @Override boolean verifyPassword(String principal, char[] password); @Override List<String> getMechanisms(); @Override SaslNegotiator createSaslNegotiator(final String mechanism, final SaslSettings saslSettings); }### Answer:
@Test public void testVerifyPassword() throws IOException, AccountNotFoundException { createUserPrincipal(); assertFalse(_database.verifyPassword(TEST_USERNAME, new char[]{})); assertFalse(_database.verifyPassword(TEST_USERNAME, "massword".toCharArray())); assertTrue(_database.verifyPassword(TEST_USERNAME, TEST_PASSWORD_CHARS)); try { _database.verifyPassword("made.up.username", TEST_PASSWORD_CHARS); fail("Should not have been able to verify this non-existant users password."); } catch (AccountNotFoundException e) { } }
@Test public void testUpdatePassword() throws IOException, AccountNotFoundException { createUserPrincipal(); char[] newPwd = "newpassword".toCharArray(); _database.updatePassword(_principal, newPwd); assertFalse(_database.verifyPassword(TEST_USERNAME, TEST_PASSWORD_CHARS)); assertTrue(_database.verifyPassword(TEST_USERNAME, newPwd)); } |
### Question:
AnonymousNegotiator implements SaslNegotiator { @Override public AuthenticationResult handleResponse(final byte[] response) { if (_isComplete) { return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalStateException( "Multiple Authentications not permitted.")); } else { _isComplete = true; } return _anonymousAuthenticationResult; } AnonymousNegotiator(final AuthenticationResult anonymousAuthenticationResult); @Override AuthenticationResult handleResponse(final byte[] response); @Override void dispose(); @Override String getAttemptedAuthenticationId(); }### Answer:
@Test public void testHandleResponse() throws Exception { final AuthenticationResult result = mock(AuthenticationResult.class); AnonymousNegotiator negotiator = new AnonymousNegotiator(result); final Object actual = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected result", result, actual); AuthenticationResult secondResult = negotiator.handleResponse(new byte[0]); assertEquals("Only first call to handleResponse should be successful", AuthenticationResult.AuthenticationStatus.ERROR, secondResult.getStatus()); } |
### Question:
SubjectCreator { public SubjectAuthenticationResult authenticate(SaslNegotiator saslNegotiator, byte[] response) { AuthenticationResult authenticationResult = saslNegotiator.handleResponse(response); if(authenticationResult.getStatus() == AuthenticationStatus.SUCCESS) { return createResultWithGroups(authenticationResult); } else { if (authenticationResult.getStatus() == AuthenticationStatus.ERROR) { String authenticationId = saslNegotiator.getAttemptedAuthenticationId(); _authenticationProvider.getEventLogger().message(AUTHENTICATION_FAILED(authenticationId, authenticationId != null)); } return new SubjectAuthenticationResult(authenticationResult); } } SubjectCreator(AuthenticationProvider<?> authenticationProvider,
Collection<GroupProvider<?>> groupProviders,
NamedAddressSpace addressSpace); AuthenticationProvider<?> getAuthenticationProvider(); SaslNegotiator createSaslNegotiator(String mechanism, final SaslSettings saslSettings); SubjectAuthenticationResult authenticate(SaslNegotiator saslNegotiator, byte[] response); SubjectAuthenticationResult createResultWithGroups(final AuthenticationResult authenticationResult); Subject createSubjectWithGroups(Principal userPrincipal); }### Answer:
@Test public void testSaslAuthenticationSuccessReturnsSubjectWithUserAndGroupPrincipals() throws Exception { when(_testSaslNegotiator.handleResponse(_saslResponseBytes)).thenReturn(_authenticationResult); SubjectAuthenticationResult result = _subjectCreator.authenticate(_testSaslNegotiator, _saslResponseBytes); final Subject actualSubject = result.getSubject(); assertEquals("Should contain one user principal and two groups ", (long) 3, (long) actualSubject.getPrincipals().size()); assertTrue(actualSubject.getPrincipals().contains(new AuthenticatedPrincipal(USERNAME_PRINCIPAL))); assertTrue(actualSubject.getPrincipals().contains(_group1)); assertTrue(actualSubject.getPrincipals().contains(_group2)); assertTrue(actualSubject.isReadOnly()); } |
### Question:
SubjectCreator { Set<Principal> getGroupPrincipals(Principal userPrincipal) { Set<Principal> principals = new HashSet<Principal>(); for (GroupProvider groupProvider : _groupProviders) { Set<Principal> groups = groupProvider.getGroupPrincipalsForUser(userPrincipal); if (groups != null) { principals.addAll(groups); } } return Collections.unmodifiableSet(principals); } SubjectCreator(AuthenticationProvider<?> authenticationProvider,
Collection<GroupProvider<?>> groupProviders,
NamedAddressSpace addressSpace); AuthenticationProvider<?> getAuthenticationProvider(); SaslNegotiator createSaslNegotiator(String mechanism, final SaslSettings saslSettings); SubjectAuthenticationResult authenticate(SaslNegotiator saslNegotiator, byte[] response); SubjectAuthenticationResult createResultWithGroups(final AuthenticationResult authenticationResult); Subject createSubjectWithGroups(Principal userPrincipal); }### Answer:
@Test public void testGetGroupPrincipals() { getAndAssertGroupPrincipals(_group1, _group2); } |
### Question:
CompositeInputStream extends InputStream { @Override public void close() throws IOException { IOException ioException = null; try { if (_current != null) { try { _current.close(); _current = null; } catch (IOException e) { ioException = e; } } for (InputStream is : _inputStreams) { try { is.close(); } catch (IOException e) { if (ioException != null) { ioException = e; } } } } finally { if (ioException != null) { throw ioException; } } } CompositeInputStream(Collection<InputStream> streams); @Override int read(); @Override int read(byte[] b, int off, int len); @Override int read(byte[] b); @Override int available(); @Override boolean markSupported(); @Override void mark(final int readlimit); @Override void reset(); @Override void close(); }### Answer:
@Test public void testClose() throws Exception { InputStream bis1 = mock(InputStream.class); InputStream bis2 = mock(InputStream.class); CompositeInputStream cis = new CompositeInputStream(Arrays.asList(bis1, bis2)); cis.close(); verify(bis1).close(); verify(bis1).close(); when(bis1.read()).thenThrow(new IOException("mocked stream closed")); try { cis.read(); fail("Excetion not thrown"); } catch(IOException ioe) { } } |
### Question:
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { @Override public int getConnectionCount() { return _connectionCount; } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void getOpenConnectionCount() { final ConnectionPrincipalStatistics stats = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(System.currentTimeMillis())); assertEquals(1, stats.getConnectionCount()); } |
### Question:
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { @Override public int getConnectionFrequency() { return _latestConnectionCreatedTimes.size(); } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void getOpenConnectionFrequency() { final long connectionCreatedTime = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats = new ConnectionPrincipalStatisticsImpl(1, Arrays.asList(connectionCreatedTime - 1000, connectionCreatedTime)); assertEquals(2, stats.getConnectionFrequency()); } |
### Question:
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { List<Long> getLatestConnectionCreatedTimes() { return _latestConnectionCreatedTimes; } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void getLatestConnectionCreatedTimes() { final long connectionCreatedTime = System.currentTimeMillis(); final List<Long> connectionCreatedTimes = Arrays.asList(connectionCreatedTime - 1000, connectionCreatedTime); final ConnectionPrincipalStatisticsImpl stats = new ConnectionPrincipalStatisticsImpl(1, connectionCreatedTimes); assertEquals(connectionCreatedTimes, stats.getLatestConnectionCreatedTimes()); } |
### Question:
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final ConnectionPrincipalStatisticsImpl that = (ConnectionPrincipalStatisticsImpl) o; if (_connectionCount != that._connectionCount) { return false; } return _latestConnectionCreatedTimes.equals(that._latestConnectionCreatedTimes); } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void equals() { final long connectionCreatedTime = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats1 = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(connectionCreatedTime)); final ConnectionPrincipalStatistics stats2 = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(connectionCreatedTime)); assertEquals(stats1, stats2); final long connectionCreatedTime2 = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats3 = new ConnectionPrincipalStatisticsImpl(2, Arrays.asList(connectionCreatedTime, connectionCreatedTime2)); assertNotEquals(stats2, stats3); assertNotEquals(stats1, stats3); } |
### Question:
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { @Override public int hashCode() { int result = _connectionCount; result = 31 * result + _latestConnectionCreatedTimes.hashCode(); return result; } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testHashCode() { final long connectionCreatedTime = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats1 = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(connectionCreatedTime)); final ConnectionPrincipalStatistics stats2 = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(connectionCreatedTime)); assertEquals(stats1.hashCode(), stats2.hashCode()); final long connectionCreatedTime2 = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats3 = new ConnectionPrincipalStatisticsImpl(2, Arrays.asList(connectionCreatedTime, connectionCreatedTime2)); assertNotEquals(stats2.hashCode(), stats3.hashCode()); assertNotEquals(stats1.hashCode(), stats3.hashCode()); } |
### Question:
ConnectionPrincipalStatisticsCheckingTask extends HouseKeepingTask { @Override public void execute() { _connectionPrincipalStatisticsRegistry.reevaluateConnectionStatistics(); } ConnectionPrincipalStatisticsCheckingTask(final QueueManagingVirtualHost virtualHost,
final AccessControlContext controlContext,
final ConnectionPrincipalStatisticsRegistry connectionPrincipalStatisticsRegistry); @Override void execute(); }### Answer:
@Test public void execute() { final QueueManagingVirtualHost vh = mock(QueueManagingVirtualHost.class); when(vh.getName()).thenReturn(getTestName()); final ConnectionPrincipalStatisticsRegistry registry = mock(ConnectionPrincipalStatisticsRegistry.class); ConnectionPrincipalStatisticsCheckingTask task = new ConnectionPrincipalStatisticsCheckingTask(vh, AccessController.getContext(), registry); task.execute(); verify(registry).reevaluateConnectionStatistics(); } |
### Question:
CacheFactory { public static <K, V> Cache<K, V> getCache(final String cacheName, final Cache<K, V> defaultCache) { Cache<K, V> cache = defaultCache; Subject subject = Subject.getSubject(AccessController.getContext()); if (subject != null) { VirtualHostPrincipal principal = QpidPrincipal.getSingletonPrincipal(subject, true, VirtualHostPrincipal.class); if (principal != null && principal.getVirtualHost() instanceof CacheProvider) { CacheProvider cacheProvider = (CacheProvider) principal.getVirtualHost(); cache = cacheProvider.getNamedCache(cacheName); } } return cache; } static Cache<K, V> getCache(final String cacheName, final Cache<K, V> defaultCache); }### Answer:
@Test public void getCache() { String cacheName = "test"; final Cache<Object, Object> cache = new NullCache<>(); final CacheProvider virtualHost = mock(CacheProvider.class, withSettings().extraInterfaces(VirtualHost.class)); when(virtualHost.getNamedCache(cacheName)).thenReturn(cache); final Subject subject = new Subject(); subject.getPrincipals().add(new VirtualHostPrincipal((VirtualHost<?>) virtualHost)); subject.setReadOnly(); Cache<String, String> actualCache = Subject.doAs(subject, (PrivilegedAction<Cache<String, String>>) () -> CacheFactory.getCache(cacheName, null)); assertSame(actualCache, cache); verify(virtualHost).getNamedCache(cacheName); } |
### Question:
RolloverWatcher implements RollingPolicyDecorator.RolloverListener { public ZippedContent getAllFilesAsZippedContent() { Set<String> fileNames = new HashSet<>(_rolledFiles); fileNames.add(getDisplayName(_activeFilePath)); return getFilesAsZippedContent(fileNames); } RolloverWatcher(final String activeFileName); @Override void onRollover(Path baseFolder, String[] relativeFileNames); @Override void onNoRolloverDetected(final Path baseFolder, final String[] relativeFileNames); PathContent getFileContent(String fileName); Collection<String> getRolledFiles(); List<LogFileDetails> getLogFileDetails(); String getContentType(String fileName); ZippedContent getFilesAsZippedContent(Set<String> fileNames); ZippedContent getAllFilesAsZippedContent(); }### Answer:
@Test public void testGetAllFilesAsZippedContent() throws Exception { String[] fileNames = createTestRolledFilesAndNotifyWatcher(); ZippedContent content = _rolloverWatcher.getAllFilesAsZippedContent(); assertZippedContent(fileNames, content); } |
### Question:
HouseKeepingTask implements Runnable { @Override final public void run() { String originalThreadName = Thread.currentThread().getName(); Thread.currentThread().setName(_name); try { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { execute(); } catch (ConnectionScopedRuntimeException e) { LOGGER.warn("Execution of housekeeping task failed", e); } return null; } }, _accessControlContext); } finally { Thread.currentThread().setName(originalThreadName); } } HouseKeepingTask(String name, VirtualHost vhost, AccessControlContext context); @Override final void run(); abstract void execute(); synchronized void cancel(); }### Answer:
@Test public void runExecuteThrowsConnectionScopeRuntimeException() { final VirtualHost virualHost = mock(VirtualHost.class); final AccessControlContext context = AccessController.getContext(); final HouseKeepingTask task = new HouseKeepingTask(getTestName(), virualHost, context) { @Override public void execute() { throw new ConnectionScopedRuntimeException("Test"); } }; task.run(); } |
### Question:
VirtualHostPropertiesNode extends AbstractSystemMessageSource { @Override public <T extends ConsumerTarget<T>> Consumer<T> addConsumer(final T target, final FilterManager filters, final Class<? extends ServerMessage> messageClass, final String consumerName, final EnumSet<ConsumerOption> options, final Integer priority) throws ExistingExclusiveConsumer, ExistingConsumerPreventsExclusive, ConsumerAccessRefused, QueueDeleted { final Consumer<T> consumer = super.addConsumer(target, filters, messageClass, consumerName, options, priority); consumer.send(createMessage()); target.noMessagesAvailable(); return consumer; } VirtualHostPropertiesNode(final NamedAddressSpace virtualHost); VirtualHostPropertiesNode(final NamedAddressSpace virtualHost, String name); @Override Consumer<T> addConsumer(final T target,
final FilterManager filters,
final Class<? extends ServerMessage> messageClass,
final String consumerName,
final EnumSet<ConsumerOption> options, final Integer priority); @Override void close(); }### Answer:
@Test public void testAddConsumer() throws Exception { final EnumSet<ConsumerOption> options = EnumSet.noneOf(ConsumerOption.class); final ConsumerTarget target = mock(ConsumerTarget.class); when(target.allocateCredit(any(ServerMessage.class))).thenReturn(true); MessageInstanceConsumer consumer = _virtualHostPropertiesNode.addConsumer(target, null, ServerMessage.class, getTestName(), options, 0); final MessageContainer messageContainer = consumer.pullMessage(); assertNotNull("Could not pull message from VirtualHostPropertyNode", messageContainer); if (messageContainer.getMessageReference() != null) { messageContainer.getMessageReference().release(); } } |
### Question:
PrincipalLogEventFilter extends Filter<ILoggingEvent> implements LogBackLogInclusionRule { @Override public FilterReply decide(ILoggingEvent event) { Subject subject = Subject.getSubject(AccessController.getContext()); if (subject != null && subject.getPrincipals().contains(_principal)) { return FilterReply.NEUTRAL; } return FilterReply.DENY; } PrincipalLogEventFilter(final Principal principal); @Override FilterReply decide(ILoggingEvent event); @Override Filter<ILoggingEvent> asFilter(); @Override String getName(); }### Answer:
@Test public void testNoSubject() { _subject.getPrincipals().add(mock(Principal.class)); assertEquals(FilterReply.DENY, _principalLogEventFilter.decide(_event)); } |
### Question:
JsonFileConfigStore extends AbstractJsonFileStore implements DurableConfigurationStore { @Override public void init(ConfiguredObject<?> parent) { assertState(State.CLOSED); _parent = parent; _classNameMapping = generateClassNameMap(_parent.getModel(), _rootClass); FileBasedSettings fileBasedSettings = (FileBasedSettings) _parent; setup(parent.getName(), fileBasedSettings.getStorePath(), parent.getContextValue(String.class, SystemConfig.POSIX_FILE_PERMISSIONS), Collections.emptyMap()); changeState(State.CLOSED, State.CONFIGURED); } JsonFileConfigStore(Class<? extends ConfiguredObject> rootClass); @Override void upgradeStoreStructure(); @Override void init(ConfiguredObject<?> parent); @Override boolean openConfigurationStore(ConfiguredObjectRecordHandler handler,
final ConfiguredObjectRecord... initialRecords); @Override void reload(ConfiguredObjectRecordHandler handler); @Override synchronized void create(ConfiguredObjectRecord record); @Override synchronized UUID[] remove(final ConfiguredObjectRecord... objects); @Override synchronized void update(final boolean createIfNecessary, final ConfiguredObjectRecord... records); @Override void closeConfigurationStore(); @Override void onDelete(ConfiguredObject<?> parent); }### Answer:
@Test public void testNoStorePath() throws Exception { when(_parent.getStorePath()).thenReturn(null); try { _store.init(_parent); fail("Store should not successfully configure if there is no path set"); } catch (ServerScopedRuntimeException e) { } }
@Test public void testInvalidStorePath() throws Exception { String unwritablePath = System.getProperty("file.separator"); assumeThat(new File(unwritablePath).canWrite(), is(equalTo(false))); when(_parent.getStorePath()).thenReturn(unwritablePath); try { _store.init(_parent); fail("Store should not successfully configure if there is an invalid path set"); } catch (ServerScopedRuntimeException e) { } } |
### Question:
JsonFilePreferenceStore extends AbstractJsonFileStore implements PreferenceStore { @Override public synchronized void updateOrCreate(final Collection<PreferenceRecord> preferenceRecords) { if (_storeState != StoreState.OPENED) { throw new IllegalStateException("PreferenceStore is not opened"); } if (preferenceRecords.isEmpty()) { return; } updateOrCreateInternal(preferenceRecords); } JsonFilePreferenceStore(String path, String posixFilePermissions); @Override synchronized Collection<PreferenceRecord> openAndLoad(final PreferenceStoreUpdater updater); @Override synchronized void close(); @Override synchronized void updateOrCreate(final Collection<PreferenceRecord> preferenceRecords); @Override synchronized void replace(final Collection<UUID> preferenceRecordsToRemove,
final Collection<PreferenceRecord> preferenceRecordsToAdd); @Override synchronized void onDelete(); }### Answer:
@Test public void testUpdateOrCreate() throws Exception { final UUID id = UUID.randomUUID(); final Map<String, Object> attributes = new HashMap<>(); attributes.put("test1", "test2"); final PreferenceRecord record = new PreferenceRecordImpl(id, attributes); _store.openAndLoad(_updater); _store.updateOrCreate(Collections.singleton(record)); assertSinglePreferenceRecordInStore(id, attributes); }
@Test public void testUpdateFailIfNotOpened() throws Exception { try { _store.updateOrCreate(Collections.<PreferenceRecord>emptyList()); fail("Should not be able to update or create"); } catch (IllegalStateException e) { } } |
### Question:
JsonFilePreferenceStore extends AbstractJsonFileStore implements PreferenceStore { @Override public synchronized void replace(final Collection<UUID> preferenceRecordsToRemove, final Collection<PreferenceRecord> preferenceRecordsToAdd) { if (_storeState != StoreState.OPENED) { throw new IllegalStateException("PreferenceStore is not opened"); } if (preferenceRecordsToRemove.isEmpty() && preferenceRecordsToAdd.isEmpty()) { return; } _recordMap.keySet().removeAll(preferenceRecordsToRemove); updateOrCreateInternal(preferenceRecordsToAdd); } JsonFilePreferenceStore(String path, String posixFilePermissions); @Override synchronized Collection<PreferenceRecord> openAndLoad(final PreferenceStoreUpdater updater); @Override synchronized void close(); @Override synchronized void updateOrCreate(final Collection<PreferenceRecord> preferenceRecords); @Override synchronized void replace(final Collection<UUID> preferenceRecordsToRemove,
final Collection<PreferenceRecord> preferenceRecordsToAdd); @Override synchronized void onDelete(); }### Answer:
@Test public void testReplace() throws Exception { UUID prefId = UUID.randomUUID(); Map<String, Object> attributes = Collections.<String, Object>singletonMap("test1", "test2"); createSingleEntryTestFile(prefId, attributes); final UUID newPrefId = UUID.randomUUID(); final Map<String, Object> newAttributes = new HashMap<>(); newAttributes.put("test3", "test4"); final PreferenceRecord newRecord = new PreferenceRecordImpl(newPrefId, newAttributes); _store.openAndLoad(_updater); _store.replace(Collections.singleton(prefId), Collections.singleton(newRecord)); assertSinglePreferenceRecordInStore(newPrefId, newAttributes); }
@Test public void testReplaceFailIfNotOpened() throws Exception { try { _store.replace(Collections.<UUID>emptyList(), Collections.<PreferenceRecord>emptyList()); fail("Should not be able to replace"); } catch (IllegalStateException e) { } } |
### Question:
UpgraderHelper { public static Map<String, String> renameContextVariables(final Map<String, String> context, final Map<String, String> oldToNewNameMapping) { final Map<String, String> newContext = new HashMap<>(context); oldToNewNameMapping.forEach((oldName, newName) -> { if (newContext.containsKey(oldName)) { final String value = newContext.remove(oldName); newContext.put(newName, value); } }); return newContext; } static Map<String, String> renameContextVariables(final Map<String, String> context,
final Map<String, String> oldToNewNameMapping); static Map<String, String> reverse(Map<String, String> map); static final Map<String, String> MODEL9_MAPPING_FOR_RENAME_TO_ALLOW_DENY_CONTEXT_VARIABLES; }### Answer:
@Test public void renameContextVariables() { final Map<String, String> context = new HashMap<>(); context.put("foo", "fooValue"); context.put("bar", "barValue"); final Map<String, String> newContext = UpgraderHelper.renameContextVariables(context, Collections.singletonMap("foo", "newFoo")); assertThat(newContext, is(notNullValue())); assertThat(newContext.size(), equalTo(context.size())); assertThat(newContext.get("bar"), equalTo(context.get("bar"))); assertThat(newContext.get("newFoo"), equalTo(context.get("foo"))); } |
### Question:
AbstractConsumerTarget implements ConsumerTarget<T> { @Override final public boolean close() { if (_state.compareAndSet(State.OPEN, State.CLOSED)) { setNotifyWorkDesired(false); List<MessageInstanceConsumer> consumers = new ArrayList<>(_consumers); _consumers.clear(); for (MessageInstanceConsumer consumer : consumers) { consumer.close(); } getSession().removeTicker(_suspendedConsumerLoggingTicker); return true; } else { return false; } } protected AbstractConsumerTarget(final boolean isMultiQueue,
final AMQPConnection<?> amqpConnection); @Override void acquisitionRemoved(final MessageInstance node); @Override boolean isMultiQueue(); @Override void notifyWork(); @Override final boolean isNotifyWorkDesired(); @Override boolean processPending(); @Override void consumerAdded(final MessageInstanceConsumer sub); @Override ListenableFuture<Void> consumerRemoved(final MessageInstanceConsumer sub); List<MessageInstanceConsumer> getConsumers(); @Override final boolean isSuspended(); @Override final State getState(); @Override final void send(final MessageInstanceConsumer consumer, MessageInstance entry, boolean batch); @Override long getUnacknowledgedMessages(); @Override long getUnacknowledgedBytes(); @Override boolean sendNextMessage(); @Override final boolean close(); @Override void queueDeleted(final Queue queue, final MessageInstanceConsumer sub); }### Answer:
@Test public void testClose() throws Exception { _consumerTarget = new TestAbstractConsumerTarget(); assertEquals("Unexpected number of consumers", (long) 0, (long) _consumerTarget.getConsumers().size()); _consumerTarget.consumerAdded(_consumer); assertEquals("Unexpected number of consumers after add", (long) 1, (long) _consumerTarget.getConsumers().size()); _consumerTarget.close(); assertEquals("Unexpected number of consumers after close", (long) 0, (long) _consumerTarget.getConsumers().size()); verify(_consumer, times(1)).close(); } |
### Question:
AbstractConsumerTarget implements ConsumerTarget<T> { @Override public void notifyWork() { @SuppressWarnings("unchecked") final T target = (T) this; getSession().notifyWork(target); } protected AbstractConsumerTarget(final boolean isMultiQueue,
final AMQPConnection<?> amqpConnection); @Override void acquisitionRemoved(final MessageInstance node); @Override boolean isMultiQueue(); @Override void notifyWork(); @Override final boolean isNotifyWorkDesired(); @Override boolean processPending(); @Override void consumerAdded(final MessageInstanceConsumer sub); @Override ListenableFuture<Void> consumerRemoved(final MessageInstanceConsumer sub); List<MessageInstanceConsumer> getConsumers(); @Override final boolean isSuspended(); @Override final State getState(); @Override final void send(final MessageInstanceConsumer consumer, MessageInstance entry, boolean batch); @Override long getUnacknowledgedMessages(); @Override long getUnacknowledgedBytes(); @Override boolean sendNextMessage(); @Override final boolean close(); @Override void queueDeleted(final Queue queue, final MessageInstanceConsumer sub); }### Answer:
@Test public void testNotifyWork() throws Exception { InOrder order = inOrder(_consumer); _consumerTarget = new TestAbstractConsumerTarget(); assertEquals("Unexpected number of consumers", (long) 0, (long) _consumerTarget.getConsumers().size()); _consumerTarget.consumerAdded(_consumer); _consumerTarget.setNotifyWorkDesired(true); order.verify(_consumer, times(1)).setNotifyWorkDesired(true); _consumerTarget.setNotifyWorkDesired(false); order.verify(_consumer, times(1)).setNotifyWorkDesired(false); _consumerTarget.setNotifyWorkDesired(true); order.verify(_consumer, times(1)).setNotifyWorkDesired(true); _consumerTarget.setNotifyWorkDesired(true); _consumerTarget.close(); order.verify(_consumer, times(1)).setNotifyWorkDesired(false); order.verify(_consumer, times(1)).close(); verifyNoMoreInteractions(_consumer); } |
### Question:
UpgradeFrom8To9 extends AbstractStoreUpgrade { @Override public void performUpgrade(final Environment environment, final UpgradeInteractionHandler handler, final ConfiguredObject<?> parent) { reportStarting(environment, 8); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setTransactional(true); dbConfig.setAllowCreate(true); final Transaction transaction = environment.beginTransaction(null, null); try { Database userPreferencesDb = environment.openDatabase(transaction, "USER_PREFERENCES", dbConfig); userPreferencesDb.close(); try (Database userPreferencesVersionDb = environment.openDatabase(transaction, "USER_PREFERENCES_VERSION", dbConfig)) { if (userPreferencesVersionDb.count() == 0L) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry value = new DatabaseEntry(); StringBinding.stringToEntry(DEFAULT_VERSION, key); LongBinding.longToEntry(System.currentTimeMillis(), value); OperationStatus status = userPreferencesVersionDb.put(transaction, key, value); if (status != OperationStatus.SUCCESS) { throw new StoreException("Error initialising user preference version: " + status); } } } transaction.commit(); reportFinished(environment, 9); } catch (RuntimeException e) { try { if (transaction.isValid()) { transaction.abort(); } } finally { throw e; } } } @Override void performUpgrade(final Environment environment,
final UpgradeInteractionHandler handler,
final ConfiguredObject<?> parent); }### Answer:
@Test public void testPerformUpgrade() throws Exception { UpgradeFrom8To9 upgrade = new UpgradeFrom8To9(); upgrade.performUpgrade(_environment, UpgradeInteractionHandler.DEFAULT_HANDLER, getVirtualHost()); assertDatabaseRecordCount(PREFERENCES_DB_NAME, 0); assertDatabaseRecordCount(PREFERENCES_VERSION_DB_NAME, 1); List<String> versions = loadVersions(); assertEquals("Unexpected number of versions loaded", 1, versions.size()); assertEquals("Unexpected version", "6.1", versions.get(0)); } |
### Question:
Upgrader { void upgrade(final int fromVersion, final int toVersion) throws StoreException { try { @SuppressWarnings("unchecked") Class<StoreUpgrade> upgradeClass = (Class<StoreUpgrade>) Class.forName("org.apache.qpid.server.store.berkeleydb.upgrade." + "UpgradeFrom"+fromVersion+"To"+toVersion); Constructor<StoreUpgrade> ctr = upgradeClass.getConstructor(); StoreUpgrade upgrade = ctr.newInstance(); upgrade.performUpgrade(_environment, UpgradeInteractionHandler.DEFAULT_HANDLER, _parent); } catch (ClassNotFoundException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } catch (NoSuchMethodException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } catch (InvocationTargetException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } catch (InstantiationException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } catch (IllegalAccessException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } } Upgrader(Environment environment, ConfiguredObject<?> parent); void upgradeIfNecessary(); }### Answer:
@Test public void testUpgrade() throws Exception { assertEquals("Unexpected store version", -1, getStoreVersion(_environment)); _upgrader.upgradeIfNecessary(); assertEquals("Unexpected store version", BDBConfigurationStore.VERSION, getStoreVersion(_environment)); assertContent(); } |
### Question:
CompositeFilter extends Filter<ILoggingEvent> { @Override public FilterReply decide(ILoggingEvent event) { FilterReply reply = DENY; for(Filter<ILoggingEvent> filter : _filterList) { FilterReply filterReply = filter.decide(event); if (filterReply == DENY) { reply = filterReply; break; } if (filterReply == ACCEPT) { reply = filterReply; } } if(reply == ACCEPT) { switch(event.getLevel().toInt()) { case WARN_INT: _warnCount.incrementAndGet(); break; case ERROR_INT: _errorCount.incrementAndGet(); break; default: } return ACCEPT; } return DENY; } void addLogInclusionRule(LogBackLogInclusionRule logInclusionRule); void removeLogInclusionRule(LogBackLogInclusionRule logInclusionRule); @Override FilterReply decide(ILoggingEvent event); long getErrorCount(); long getWarnCount(); }### Answer:
@Test public void testDecideWithNoRule() { CompositeFilter compositeFilter = new CompositeFilter(); FilterReply reply = compositeFilter.decide(mock(ILoggingEvent.class)); assertEquals("Unexpected reply with no rule added", FilterReply.DENY, reply); } |
### Question:
Upgrader { public void upgradeIfNecessary() { boolean isEmpty = _environment.getDatabaseNames().isEmpty(); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setTransactional(true); dbConfig.setAllowCreate(true); Database versionDb = null; try { versionDb = _environment.openDatabase(null, VERSION_DB_NAME, dbConfig); if(versionDb.count() == 0L) { int sourceVersion = isEmpty ? BDBConfigurationStore.VERSION: identifyOldStoreVersion(); DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(sourceVersion, key); DatabaseEntry value = new DatabaseEntry(); LongBinding.longToEntry(System.currentTimeMillis(), value); versionDb.put(null, key, value); } int version = getSourceVersion(versionDb); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Source message store version is " + version); } if(version > BDBConfigurationStore.VERSION) { throw new StoreException("Database version " + version + " is higher than the most recent known version: " + BDBConfigurationStore.VERSION); } performUpgradeFromVersion(version, versionDb); } finally { if (versionDb != null) { versionDb.close(); } } } Upgrader(Environment environment, ConfiguredObject<?> parent); void upgradeIfNecessary(); }### Answer:
@Test public void testEmptyDatabaseUpgradeDoesNothing() throws Exception { File nonExistentStoreLocation = new File(TMP_FOLDER, getTestName()); deleteDirectoryIfExists(nonExistentStoreLocation); nonExistentStoreLocation.mkdir(); Environment emptyEnvironment = createEnvironment(nonExistentStoreLocation); try { _upgrader = new Upgrader(emptyEnvironment, getVirtualHost()); _upgrader.upgradeIfNecessary(); List<String> databaseNames = emptyEnvironment.getDatabaseNames(); List<String> expectedDatabases = new ArrayList<String>(); expectedDatabases.add(Upgrader.VERSION_DB_NAME); assertEquals("Expectedonly VERSION table in initially empty store after upgrade: ", expectedDatabases, databaseNames); assertEquals("Unexpected store version", BDBConfigurationStore.VERSION, getStoreVersion(emptyEnvironment)); } finally { emptyEnvironment.close(); nonExistentStoreLocation.delete(); } } |
### Question:
DatabaseTemplate { public void run(DatabaseRunnable databaseRunnable) { DatabaseCallable<Void> callable = runnableToCallable(databaseRunnable); call(callable); } DatabaseTemplate(Environment environment, String sourceDatabaseName, Transaction transaction); DatabaseTemplate(Environment environment, String sourceDatabaseName, String targetDatabaseName,
Transaction parentTransaction); void run(DatabaseRunnable databaseRunnable); T call(DatabaseCallable<T> databaseCallable); }### Answer:
@Test public void testExecuteWithTwoDatabases() { String targetDatabaseName = "targetDatabase"; Database targetDatabase = mock(Database.class); Transaction txn = mock(Transaction.class); when(_environment.openDatabase(same(txn), same(targetDatabaseName), isA(DatabaseConfig.class))) .thenReturn(targetDatabase); DatabaseTemplate databaseTemplate = new DatabaseTemplate(_environment, SOURCE_DATABASE, targetDatabaseName, txn); DatabaseRunnable databaseOperation = mock(DatabaseRunnable.class); databaseTemplate.run(databaseOperation); verify(databaseOperation).run(_sourceDatabase, targetDatabase, txn); verify(_sourceDatabase).close(); verify(targetDatabase).close(); }
@Test public void testExecuteWithOneDatabases() { DatabaseTemplate databaseTemplate = new DatabaseTemplate(_environment, SOURCE_DATABASE, null, null); DatabaseRunnable databaseOperation = mock(DatabaseRunnable.class); databaseTemplate.run(databaseOperation); verify(databaseOperation).run(eq(_sourceDatabase), isNull(), isNull()); verify(_sourceDatabase).close(); } |
### Question:
CompositeFilter extends Filter<ILoggingEvent> { public void removeLogInclusionRule(LogBackLogInclusionRule logInclusionRule) { Iterator<Filter<ILoggingEvent>> it = _filterList.iterator(); while(it.hasNext()) { Filter f = it.next(); if (f.getName().equals(logInclusionRule.getName())) { _filterList.remove(f); break; } } } void addLogInclusionRule(LogBackLogInclusionRule logInclusionRule); void removeLogInclusionRule(LogBackLogInclusionRule logInclusionRule); @Override FilterReply decide(ILoggingEvent event); long getErrorCount(); long getWarnCount(); }### Answer:
@Test public void testRemoveLogInclusionRule() { CompositeFilter compositeFilter = new CompositeFilter(); LogBackLogInclusionRule neutral = createRule(FilterReply.NEUTRAL, "neutral"); compositeFilter.addLogInclusionRule(neutral); LogBackLogInclusionRule deny = createRule(FilterReply.DENY, "deny"); compositeFilter.addLogInclusionRule(deny); LogBackLogInclusionRule accept = createRule(FilterReply.ACCEPT, "accept"); compositeFilter.addLogInclusionRule(accept); FilterReply reply = compositeFilter.decide(mock(ILoggingEvent.class)); assertEquals("Unexpected reply", FilterReply.DENY, reply); compositeFilter.removeLogInclusionRule(deny); final ILoggingEvent loggingEvent = mock(ILoggingEvent.class); when(loggingEvent.getLevel()).thenReturn(Level.ERROR); FilterReply reply2 = compositeFilter.decide(loggingEvent); assertEquals("Unexpected reply", FilterReply.ACCEPT, reply2); verify(neutral.asFilter(), times(2)).decide(any(ILoggingEvent.class)); verify(deny.asFilter()).decide(any(ILoggingEvent.class)); verify(accept.asFilter()).decide(any(ILoggingEvent.class)); } |
### Question:
ObjectUtils { public static boolean isValueType(Class<?> retType) { if (retType.isPrimitive() && retType != void.class) return true; if (Number.class.isAssignableFrom(retType)) return true; if (Boolean.class == retType) return true; if (Character.class == retType) return true; if (String.class == retType) return true; if (byte[].class.isAssignableFrom(retType)) return true; return Enum.class.isAssignableFrom(retType); } private ObjectUtils(); static String getEntityName(Class<T> type); static String findRepositoryName(Class<T> type, String key); static String findRepositoryName(String entityName, String key); static String getKeyName(String collectionName); static String getKeyedRepositoryType(String collectionName); @SuppressWarnings("rawtypes") static boolean deepEquals(Object o1, Object o2); @SuppressWarnings({"unchecked", "rawtypes"}) static T newInstance(Class<T> type, boolean createSkeleton); static boolean isValueType(Class<?> retType); static boolean isCompatibleTypes(Class<?> type1, Class<?> type2); static Object[] convertToObjectArray(Object array); static int compare(T c1, T c2); @SuppressWarnings("unchecked") static T deepCopy(T oldObj); }### Answer:
@Test public void testIsValueType() { assertFalse(ObjectUtils.isValueType(Object.class)); } |
### Question:
ObjectUtils { public static boolean isCompatibleTypes(Class<?> type1, Class<?> type2) { if (type1.equals(type2)) return true; if (type1.isAssignableFrom(type2)) return true; if (type1.isPrimitive()) { Class<?> wrapperType = toWrapperType(type1); return isCompatibleTypes(wrapperType, type2); } else if (type2.isPrimitive()) { Class<?> wrapperType = toWrapperType(type2); return isCompatibleTypes(type1, wrapperType); } return false; } private ObjectUtils(); static String getEntityName(Class<T> type); static String findRepositoryName(Class<T> type, String key); static String findRepositoryName(String entityName, String key); static String getKeyName(String collectionName); static String getKeyedRepositoryType(String collectionName); @SuppressWarnings("rawtypes") static boolean deepEquals(Object o1, Object o2); @SuppressWarnings({"unchecked", "rawtypes"}) static T newInstance(Class<T> type, boolean createSkeleton); static boolean isValueType(Class<?> retType); static boolean isCompatibleTypes(Class<?> type1, Class<?> type2); static Object[] convertToObjectArray(Object array); static int compare(T c1, T c2); @SuppressWarnings("unchecked") static T deepCopy(T oldObj); }### Answer:
@Test public void testIsCompatibleTypes() { Class<?> type1 = Object.class; assertTrue(ObjectUtils.isCompatibleTypes(type1, Object.class)); } |
### Question:
ObjectUtils { @SuppressWarnings("unchecked") public static <T extends Serializable> T deepCopy(T oldObj) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(bos)) { oos.writeObject(oldObj); oos.flush(); try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))) { return (T) ois.readObject(); } } catch (IOException | ClassNotFoundException e) { throw new NitriteIOException("error while deep copying object", e); } } private ObjectUtils(); static String getEntityName(Class<T> type); static String findRepositoryName(Class<T> type, String key); static String findRepositoryName(String entityName, String key); static String getKeyName(String collectionName); static String getKeyedRepositoryType(String collectionName); @SuppressWarnings("rawtypes") static boolean deepEquals(Object o1, Object o2); @SuppressWarnings({"unchecked", "rawtypes"}) static T newInstance(Class<T> type, boolean createSkeleton); static boolean isValueType(Class<?> retType); static boolean isCompatibleTypes(Class<?> type1, Class<?> type2); static Object[] convertToObjectArray(Object array); static int compare(T c1, T c2); @SuppressWarnings("unchecked") static T deepCopy(T oldObj); }### Answer:
@Test public void testDeepCopy() { assertNull(ObjectUtils.deepCopy(null)); assertEquals(NitriteId.createId("42"), ObjectUtils.deepCopy(NitriteId.createId("42"))); assertNotEquals(NitriteId.createId("41"), ObjectUtils.deepCopy(NitriteId.createId("42"))); assertEquals(Document.createDocument("foo", "foo"), ObjectUtils.deepCopy(Document.createDocument("foo", "foo"))); assertNotEquals(this, ObjectUtils.deepCopy(this)); } |
### Question:
Numbers { public static int compare(Number x, Number y) { if (isSpecial(x) || isSpecial(y)) { return Double.compare(x.doubleValue(), y.doubleValue()); } else { return toBigDecimal(x).compareTo(toBigDecimal(y)); } } private Numbers(); static int compare(Number x, Number y); static Object castNumber(Object value, Class<?> type); }### Answer:
@Test public void testCompare() { assertEquals(compare(x, y), result); }
@Test public void testCompare2() { Integer x = new Integer(1); assertEquals(0, Numbers.compare(x, new Integer(1))); } |
### Question:
DocumentUtils { public static boolean isRecent(Document recent, Document older) { if (Objects.deepEquals(recent.getRevision(), older.getRevision())) { return recent.getLastModifiedSinceEpoch() >= older.getLastModifiedSinceEpoch(); } return recent.getRevision() > older.getRevision(); } private DocumentUtils(); static boolean isRecent(Document recent, Document older); static Filter createUniqueFilter(Document document); static Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type); static boolean isSimilar(Document document, Document other, String... fields); }### Answer:
@Test public void testIsRecent() throws InterruptedException { Document first = createDocument("key1", "value1"); Thread.sleep(500); Document second = createDocument("key1", "value2"); assertTrue(isRecent(second, first)); second = first.clone(); second.put(DOC_REVISION, 1); first.put("key2", "value3"); first.put(DOC_REVISION, 2); assertTrue(isRecent(first, second)); }
@Test public void testIsRecent2() { Document recent = Document.createDocument(); assertTrue(DocumentUtils.isRecent(recent, Document.createDocument())); } |
### Question:
DocumentUtils { public static Filter createUniqueFilter(Document document) { return Filter.byId(document.getId()); } private DocumentUtils(); static boolean isRecent(Document recent, Document older); static Filter createUniqueFilter(Document document); static Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type); static boolean isSimilar(Document document, Document other, String... fields); }### Answer:
@Test public void testCreateUniqueFilter() { Document doc = createDocument("score", 1034) .put("location", createDocument("state", "NY") .put("city", "New York") .put("address", createDocument("line1", "40") .put("line2", "ABC Street") .put("house", new String[]{"1", "2", "3"}))) .put("category", new String[]{"food", "produce", "grocery"}) .put("objArray", new Document[]{createDocument("value", 1), createDocument("value", 2)}); doc.getId(); Filter filter = createUniqueFilter(doc); assertNotNull(filter); assertTrue(filter instanceof IndexAwareFilter); } |
### Question:
DocumentUtils { public static <T> Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type) { if (nitriteMapper.isValueType(type)) { return Document.createDocument(); } T dummy = newInstance(type, true); Document document = nitriteMapper.convert(dummy, Document.class); return removeValues(document); } private DocumentUtils(); static boolean isRecent(Document recent, Document older); static Filter createUniqueFilter(Document document); static Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type); static boolean isSimilar(Document document, Document other, String... fields); }### Answer:
@Test public void testSkeletonDocument() { Class type = Object.class; assertNull(DocumentUtils.skeletonDocument(new NitriteBuilderTest.CustomNitriteMapper(), type)); }
@Test public void testSkeletonDocument2() { Class<?> forNameResult = Object.class; Class<?> forNameResult1 = Object.class; MappableMapper nitriteMapper = new MappableMapper(forNameResult, forNameResult1, Object.class); assertEquals(0, DocumentUtils.skeletonDocument(nitriteMapper, Object.class).size()); }
@Test public void testDummyDocument() { NitriteMapper nitriteMapper = new MappableMapper(); Document document = skeletonDocument(nitriteMapper, DummyTest.class); assertTrue(document.containsKey("first")); assertTrue(document.containsKey("second")); assertNull(document.get("first")); assertNull(document.get("second")); } |
### Question:
DocumentUtils { public static boolean isSimilar(Document document, Document other, String... fields) { boolean result = true; if (document == null && other != null) return false; if (document != null && other == null) return false; if (document == null) return true; for (String field : fields) { result = result && Objects.deepEquals(document.get(field), other.get(field)); } return result; } private DocumentUtils(); static boolean isRecent(Document recent, Document older); static Filter createUniqueFilter(Document document); static Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type); static boolean isSimilar(Document document, Document other, String... fields); }### Answer:
@Test public void testIsSimilar() { assertFalse(DocumentUtils.isSimilar(null, Document.createDocument(), "fields")); assertFalse(DocumentUtils.isSimilar(null, Document.createDocument(), (String) null)); assertTrue(DocumentUtils.isSimilar(null, null, "fields")); assertFalse(DocumentUtils.isSimilar(Document.createDocument(), null, "fields")); }
@Test public void testIsSimilar2() { Document document = Document.createDocument(); assertTrue(DocumentUtils.isSimilar(document, Document.createDocument(), "fields")); } |
### Question:
ThreadPoolManager { public static ExecutorService getThreadPool(int size, String threadName) { ExecutorService threadPool = Executors.newFixedThreadPool(size, threadFactory(threadName)); threadPools.add(threadPool); return threadPool; } static ExecutorService workerPool(); static ExecutorService getThreadPool(int size, String threadName); static ErrorAwareThreadFactory threadFactory(String name); static void runAsync(Runnable runnable); static void shutdownThreadPools(); }### Answer:
@Test public void testGetThreadPool() { assertTrue(ThreadPoolManager.getThreadPool(3, "threadName") instanceof java.util.concurrent.ThreadPoolExecutor); } |
### Question:
LockService { public synchronized Lock getReadLock(String name) { if (lockRegistry.containsKey(name)) { ReentrantReadWriteLock rwLock = lockRegistry.get(name); return rwLock.readLock(); } ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); lockRegistry.put(name, rwLock); return rwLock.readLock(); } LockService(); synchronized Lock getReadLock(String name); synchronized Lock getWriteLock(String name); }### Answer:
@Test public void testGetReadLock() { assertTrue( (new LockService()).getReadLock("name") instanceof java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock); } |
### Question:
LockService { public synchronized Lock getWriteLock(String name) { if (lockRegistry.containsKey(name)) { ReentrantReadWriteLock rwLock = lockRegistry.get(name); return rwLock.writeLock(); } ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); lockRegistry.put(name, rwLock); return rwLock.writeLock(); } LockService(); synchronized Lock getReadLock(String name); synchronized Lock getWriteLock(String name); }### Answer:
@Test public void testGetWriteLock() { assertTrue((new LockService()) .getWriteLock("name") instanceof java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock); } |
### Question:
NotEqualsFilter extends IndexAwareFilter { @Override @SuppressWarnings("rawtypes") protected Set<NitriteId> findIndexedIdSet() { Set<NitriteId> idSet = new LinkedHashSet<>(); if (getIsFieldIndexed()) { if (getValue() == null || getValue() instanceof Comparable) { if (getIndexer() instanceof ComparableIndexer) { ComparableIndexer comparableIndexer = (ComparableIndexer) getIndexer(); idSet = comparableIndexer.findNotEqual(getCollectionName(), getField(), (Comparable) getValue()); } else if (getIndexer() instanceof TextIndexer && getValue() instanceof String) { setIsFieldIndexed(false); } else { throw new FilterException("notEq filter is not supported on indexed field " + getField()); } } else { throw new FilterException(getValue() + " is not comparable"); } } return idSet; } protected NotEqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }### Answer:
@Test public void testFindIndexedIdSet() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", null); notEqualsFilter.setIsFieldIndexed(true); assertThrows(FilterException.class, () -> notEqualsFilter.findIndexedIdSet()); }
@Test public void testFindIndexedIdSet2() { assertEquals(0, (new NotEqualsFilter("field", "value")).findIndexedIdSet().size()); } |
### Question:
NotEqualsFilter extends IndexAwareFilter { @Override protected Set<NitriteId> findIdSet(NitriteMap<NitriteId, Document> collection) { Set<NitriteId> idSet = new LinkedHashSet<>(); if (getOnIdField() && getValue() instanceof String) { NitriteId nitriteId = NitriteId.createId((String) getValue()); if (!collection.containsKey(nitriteId)) { idSet.add(nitriteId); } } return idSet; } protected NotEqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }### Answer:
@Test public void testFindIdSet() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); assertEquals(0, notEqualsFilter.findIdSet(new InMemoryMap<NitriteId, Document>("mapName", null)).size()); }
@Test public void testFindIdSet2() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", 42); notEqualsFilter.setOnIdField(true); assertEquals(0, notEqualsFilter.findIdSet(new InMemoryMap<>("mapName", null)).size()); assertTrue(notEqualsFilter.getValue() instanceof Integer); }
@Test(expected = InvalidIdException.class) public void testFindIdSet3() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); notEqualsFilter.setOnIdField(true); notEqualsFilter.findIdSet(new InMemoryMap<>("mapName", null)); assertTrue(notEqualsFilter.getValue() instanceof String); } |
### Question:
NotEqualsFilter extends IndexAwareFilter { @Override public boolean apply(Pair<NitriteId, Document> element) { Document document = element.getSecond(); Object fieldValue = document.get(getField()); return !deepEquals(fieldValue, getValue()); } protected NotEqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }### Answer:
@Test public void testApply() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); NitriteId first = NitriteId.newId(); assertTrue(notEqualsFilter.apply(new Pair<>(first, Document.createDocument()))); assertTrue(notEqualsFilter.getValue() instanceof String); }
@Test public void testApply2() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); Pair<NitriteId, Document> pair = new Pair<>(); pair.setSecond(Document.createDocument()); assertTrue(notEqualsFilter.apply(pair)); assertTrue(notEqualsFilter.getValue() instanceof String); } |
### Question:
NotEqualsFilter extends IndexAwareFilter { @Override public void setIsFieldIndexed(Boolean isFieldIndexed) { if (!(getIndexer() instanceof TextIndexer && getValue() instanceof String)) { super.setIsFieldIndexed(isFieldIndexed); } } protected NotEqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }### Answer:
@Test public void testSetIsFieldIndexed() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", 42); notEqualsFilter.setIndexer(new NitriteTextIndexer()); notEqualsFilter.setIsFieldIndexed(true); assertTrue(notEqualsFilter.getValue() instanceof Integer); assertTrue(notEqualsFilter.getIsFieldIndexed()); }
@Test public void testSetIsFieldIndexed2() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", 42); notEqualsFilter.setObjectFilter(true); notEqualsFilter.setIndexer(null); notEqualsFilter.setIsFieldIndexed(true); assertTrue(notEqualsFilter.getIsFieldIndexed()); }
@Test public void testSetIsFieldIndexed3() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); notEqualsFilter.setIsFieldIndexed(true); assertTrue(notEqualsFilter.getIsFieldIndexed()); }
@Test public void testSetIsFieldIndexed4() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); notEqualsFilter.setIndexer(new NitriteTextIndexer()); notEqualsFilter.setIsFieldIndexed(true); assertTrue(notEqualsFilter.getValue() instanceof String); } |
### Question:
RegexFilter extends FieldBasedFilter { @Override public boolean apply(Pair<NitriteId, Document> element) { Document document = element.getSecond(); Object fieldValue = document.get(getField()); if (fieldValue != null) { if (fieldValue instanceof String) { Matcher matcher = pattern.matcher((String) fieldValue); if (matcher.find()) { return true; } matcher.reset(); } else { throw new FilterException(getField() + " does not contain string value"); } } return false; } RegexFilter(String field, String value); @Override boolean apply(Pair<NitriteId, Document> element); }### Answer:
@Test public void testApply() { RegexFilter regexFilter = new RegexFilter("field", "value"); Pair<NitriteId, Document> pair = new Pair<NitriteId, Document>(); pair.setSecond(Document.createDocument()); assertFalse(regexFilter.apply(pair)); }
@Test public void testApply2() { RegexFilter regexFilter = new RegexFilter("field", "value"); NitriteId first = NitriteId.newId(); assertFalse(regexFilter.apply(new Pair<NitriteId, Document>(first, Document.createDocument()))); } |
### Question:
NitriteBuilder { public NitriteBuilder fieldSeparator(String separator) { this.nitriteConfig.fieldSeparator(separator); return this; } NitriteBuilder(); NitriteBuilder fieldSeparator(String separator); NitriteBuilder loadModule(NitriteModule module); NitriteBuilder addMigrations(Migration... migrations); NitriteBuilder schemaVersion(Integer version); Nitrite openOrCreate(); Nitrite openOrCreate(String username, String password); }### Answer:
@Test public void testFieldSeparator() { db = Nitrite.builder() .fieldSeparator("::") .openOrCreate(); Document document = createDocument("firstName", "John") .put("colorCodes", new Document[]{createDocument("color", "Red"), createDocument("color", "Green")}) .put("address", createDocument("street", "ABCD Road")); String street = document.get("address::street", String.class); assertEquals("ABCD Road", street); street = document.get("address.street", String.class); assertNull(street); assertEquals(document.get("colorCodes::1::color"), "Green"); } |
### Question:
FluentFilter { public Filter eq(Object value) { return new EqualsFilter(field, value); } private FluentFilter(); static FluentFilter where("$"); static FluentFilter where(String field); Filter eq(Object value); Filter notEq(Object value); Filter gt(Comparable<?> value); Filter gte(Comparable<?> value); Filter lt(Comparable<?> value); Filter lte(Comparable<?> value); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean inclusive); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean lowerInclusive, boolean upperInclusive); Filter text(String value); Filter regex(String value); Filter in(Comparable<?>... values); Filter notIn(Comparable<?>... values); Filter elemMatch(Filter filter); }### Answer:
@Test public void testEq() { assertFalse(((EqualsFilter) FluentFilter.where("field").eq("value")).getOnIdField()); assertTrue(((EqualsFilter) FluentFilter.where("field").eq("value")).getValue() instanceof String); assertFalse(((EqualsFilter) FluentFilter.where("field").eq("value")).getObjectFilter()); assertFalse(((EqualsFilter) FluentFilter.where("field").eq("value")).getIsFieldIndexed()); assertEquals("field", ((EqualsFilter) FluentFilter.where("field").eq("value")).getField()); } |
### Question:
FluentFilter { public Filter notEq(Object value) { return new NotEqualsFilter(field, value); } private FluentFilter(); static FluentFilter where("$"); static FluentFilter where(String field); Filter eq(Object value); Filter notEq(Object value); Filter gt(Comparable<?> value); Filter gte(Comparable<?> value); Filter lt(Comparable<?> value); Filter lte(Comparable<?> value); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean inclusive); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean lowerInclusive, boolean upperInclusive); Filter text(String value); Filter regex(String value); Filter in(Comparable<?>... values); Filter notIn(Comparable<?>... values); Filter elemMatch(Filter filter); }### Answer:
@Test public void testNotEq() { assertFalse(((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getOnIdField()); assertTrue(((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getValue() instanceof String); assertFalse(((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getObjectFilter()); assertFalse(((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getIsFieldIndexed()); assertEquals("field", ((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getField()); } |
### Question:
FluentFilter { public Filter text(String value) { return new TextFilter(field, value); } private FluentFilter(); static FluentFilter where("$"); static FluentFilter where(String field); Filter eq(Object value); Filter notEq(Object value); Filter gt(Comparable<?> value); Filter gte(Comparable<?> value); Filter lt(Comparable<?> value); Filter lte(Comparable<?> value); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean inclusive); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean lowerInclusive, boolean upperInclusive); Filter text(String value); Filter regex(String value); Filter in(Comparable<?>... values); Filter notIn(Comparable<?>... values); Filter elemMatch(Filter filter); }### Answer:
@Test public void testText() { assertEquals("value", ((TextFilter) FluentFilter.where("field").text("value")).getStringValue()); assertFalse(((TextFilter) FluentFilter.where("field").text("value")).getOnIdField()); assertFalse(((TextFilter) FluentFilter.where("field").text("value")).getObjectFilter()); assertFalse(((TextFilter) FluentFilter.where("field").text("value")).getIsFieldIndexed()); assertEquals("field", ((TextFilter) FluentFilter.where("field").text("value")).getField()); } |
### Question:
FluentFilter { public Filter regex(String value) { return new RegexFilter(field, value); } private FluentFilter(); static FluentFilter where("$"); static FluentFilter where(String field); Filter eq(Object value); Filter notEq(Object value); Filter gt(Comparable<?> value); Filter gte(Comparable<?> value); Filter lt(Comparable<?> value); Filter lte(Comparable<?> value); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean inclusive); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean lowerInclusive, boolean upperInclusive); Filter text(String value); Filter regex(String value); Filter in(Comparable<?>... values); Filter notIn(Comparable<?>... values); Filter elemMatch(Filter filter); }### Answer:
@Test public void testRegex() { assertEquals("field", ((RegexFilter) FluentFilter.where("field").regex("value")).getField()); assertFalse(((RegexFilter) FluentFilter.where("field").regex("value")).getObjectFilter()); assertEquals("FieldBasedFilter(field=field, value=value, processed=true)", ((RegexFilter) FluentFilter.where("field").regex("value")).toString()); } |
### Question:
TextFilter extends StringFilter { @Override protected Set<NitriteId> findIndexedIdSet() { Set<NitriteId> idSet = new LinkedHashSet<>(); if (getIsFieldIndexed()) { if (getIndexer() instanceof TextIndexer) { TextIndexer textIndexer = (TextIndexer) getIndexer(); idSet = textIndexer.findText(getCollectionName(), getField(), getStringValue()); } else { throw new FilterException(getField() + " is not full-text indexed"); } } return idSet; } TextFilter(String field, String value); @Override boolean apply(Pair<NitriteId, Document> element); }### Answer:
@Test public void testFindIndexedIdSet() { assertEquals(0, (new TextFilter("field", "value")).findIndexedIdSet().size()); }
@Test public void testFindIndexedIdSet2() { TextFilter textFilter = new TextFilter("field", "value"); textFilter.setIndexer(null); textFilter.setIsFieldIndexed(true); assertThrows(FilterException.class, () -> textFilter.findIndexedIdSet()); }
@Test public void testFindIndexedIdSet3() { TextFilter textFilter = new TextFilter("field", "value"); textFilter.setIsFieldIndexed(true); assertThrows(FilterException.class, () -> textFilter.findIndexedIdSet()); } |
### Question:
EqualsFilter extends IndexAwareFilter { @Override @SuppressWarnings("rawtypes") protected Set<NitriteId> findIndexedIdSet() { Set<NitriteId> idSet = new LinkedHashSet<>(); if (getIsFieldIndexed()) { if (getValue() == null || getValue() instanceof Comparable) { if (getIndexer() instanceof ComparableIndexer) { ComparableIndexer comparableIndexer = (ComparableIndexer) getIndexer(); idSet = comparableIndexer.findEqual(getCollectionName(), getField(), (Comparable) getValue()); } else if (getIndexer() instanceof TextIndexer && getValue() instanceof String) { setIsFieldIndexed(false); } else { throw new FilterException("eq filter is not supported on indexed field " + getField()); } } else { throw new FilterException(getValue() + " is not comparable"); } } return idSet; } EqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }### Answer:
@Test public void testFindIndexedIdSet() { EqualsFilter equalsFilter = new EqualsFilter("field", "value"); equalsFilter.setIndexer(new NitriteTextIndexer()); equalsFilter.setIsFieldIndexed(null); assertEquals(0, equalsFilter.findIndexedIdSet().size()); }
@Test public void testFindIndexedIdSet6() { assertEquals(0, (new EqualsFilter("field", "value")).findIndexedIdSet().size()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.