src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
LoggingEvent implements ILoggingEvent { @Override public void prepareForDeferredProcessing() { _event.prepareForDeferredProcessing(); } private LoggingEvent(ILoggingEvent event); static ILoggingEvent wrap(ILoggingEvent event); @Override String getThreadName(); @Override Level getLevel(); @Override String getMessage();... | @Test public void testPrepareForDeferredProcessing() { TestLoggingEvent event = new TestLoggingEvent(); ILoggingEvent wrapper = LoggingEvent.wrap(event); assertNotNull(wrapper); assertFalse(event.isPreparedForDeferredProcessing()); wrapper.prepareForDeferredProcessing(); assertTrue(event.isPreparedForDeferredProcessing... |
BBDecoder extends AbstractDecoder { public void init(ByteBuffer in) { this.in = in; this.in.order(ByteOrder.BIG_ENDIAN); } void init(ByteBuffer in); void releaseBuffer(); @Override boolean hasRemaining(); @Override short readUint8(); @Override int readUint16(); @Override long readUint32(); @Override long readUint64();... | @Test public void str8Caching() { String testString = "Test"; BBEncoder encoder = new BBEncoder(64); encoder.writeStr8(testString); encoder.writeStr8(testString); ByteBuffer buffer = encoder.buffer(); BBDecoder decoder = new BBDecoder(); decoder.init(buffer); Cache<Binary, String> original = BBDecoder.getStringCache();... |
DeliveryRegistryImpl implements DeliveryRegistry { @Override public UnsettledDelivery getDelivery(final UnsignedInteger deliveryId) { return _deliveries.get(deliveryId); } @Override void addDelivery(final UnsignedInteger deliveryId, final UnsettledDelivery unsettledDelivery); @Override void removeDelivery(final Unsign... | @Test public void getDelivery() { _registry.addDelivery(DELIVERY_ID, _unsettledDelivery); assertThat(_registry.size(), is(equalTo(1))); final UnsettledDelivery expected = new UnsettledDelivery(_unsettledDelivery.getDeliveryTag(), _unsettledDelivery.getLinkEndpoint()); assertThat(_registry.getDelivery(UnsignedInteger.ZE... |
BBEncoder extends AbstractEncoder { private void grow(int size) { ByteBuffer old = out; int capacity = old.capacity(); out = ByteBuffer.allocate(Math.max(capacity + size, 2*capacity)); out.order(ByteOrder.BIG_ENDIAN); old.flip(); out.put(old); } BBEncoder(int capacity); @Override void init(); ByteBuffer segment(); Byte... | @Test public void testGrow() { BBEncoder enc = new BBEncoder(4); enc.writeInt32(0xDEADBEEF); ByteBuffer buf = enc.buffer(); assertEquals((long) 0xDEADBEEF, (long) buf.getInt(0)); enc.writeInt32(0xBEEFDEAD); buf = enc.buffer(); assertEquals((long) 0xDEADBEEF, (long) buf.getInt(0)); assertEquals((long) 0xBEEFDEAD, (long)... |
ServerSessionDelegate extends MethodDelegate<ServerSession> implements ProtocolDelegate<ServerSession> { @Override public void exchangeDelete(ServerSession session, ExchangeDelete method) { if (nameNullOrEmpty(method.getExchange())) { exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "Delete not allowed f... | @Test public void testExchangeDeleteWhenIfUsedIsSetAndExchangeHasBindings() throws Exception { Exchange<?> exchange = mock(Exchange.class); when(exchange.hasBindings()).thenReturn(true); doReturn(exchange).when(_host).getAttainedMessageDestination(eq(getTestName()), anyBoolean()); final ExchangeDelete method = new Exch... |
MessageTransferMessageMutator implements ServerMessageMutator<MessageTransferMessage> { @Override public void setPriority(final byte priority) { if (_deliveryProperties == null) { _deliveryProperties = new DeliveryProperties(); } _deliveryProperties.setPriority(MessageDeliveryPriority.get(priority)); } MessageTransferM... | @Test public void setPriority() { _messageMutator.setPriority((byte) (TEST_PRIORITY + 1)); assertThat(_messageMutator.getPriority(), is(equalTo((byte) (TEST_PRIORITY + 1)))); } |
MessageTransferMessageMutator implements ServerMessageMutator<MessageTransferMessage> { @Override public byte getPriority() { MessageDeliveryPriority priority = _deliveryProperties == null || !_deliveryProperties.hasPriority() ? MessageDeliveryPriority.MEDIUM : _deliveryProperties.getPriority(); return (byte) priority.... | @Test public void getPriority() { assertThat((int) _messageMutator.getPriority(), is(equalTo((int) TEST_PRIORITY))); } |
MessageTransferMessageMutator implements ServerMessageMutator<MessageTransferMessage> { @Override public MessageTransferMessage create() { final Header header = new Header(_deliveryProperties, _messageProperties); final MessageMetaData_0_10 messageMetaData = new MessageMetaData_0_10(header, (int) _message.getSize(), _m... | @Test public void create() { _messageMutator.setPriority((byte) (TEST_PRIORITY + 1)); MessageTransferMessage newMessage = _messageMutator.create(); assertThat(newMessage.getMessageHeader().getPriority(), is(equalTo((byte) (TEST_PRIORITY + 1)))); assertThat(newMessage.getMessageHeader().getMimeType(), is(equalTo(TEST_CO... |
DerbyMessageStore extends AbstractDerbyMessageStore { @Override public void onDelete(ConfiguredObject parent) { if (isMessageStoreOpen()) { throw new IllegalStateException("Cannot delete the store as store is still open"); } FileBasedSettings fileBasedSettings = (FileBasedSettings)parent; String storePath = fileBasedSe... | @Test public void testOnDelete() throws Exception { File location = new File(_storeLocation); assertTrue("Store does not exist at " + _storeLocation, location.exists()); getStore().closeMessageStore(); assertTrue("Store does not exist at " + _storeLocation, location.exists()); DerbyVirtualHost mockVH = mock(DerbyVirtua... |
BoneCPConnectionProvider implements ConnectionProvider { static BoneCPConfig createBoneCPConfig(final String connectionUrl, final String username, final String password, final Map<String, String> providerAttributes) { BoneCPConfig config = new BoneCPConfig(); config.setJdbcUrl(connectionUrl); if (username != null) { co... | @Test public void testCreateBoneCPConfig() { final Map<String, String> attributes = new HashMap<>(); attributes.put("qpid.jdbcstore.bonecp.idleMaxAgeInMinutes", "123"); attributes.put("qpid.jdbcstore.bonecp.connectionTimeoutInMs", "1234"); attributes.put("qpid.jdbcstore.bonecp.connectionTestStatement", "select 1"); att... |
BoneCPConnectionProviderFactory implements JDBCConnectionProviderFactory { @Override public Set<String> getProviderAttributeNames() { return _supportedAttributes; } BoneCPConnectionProviderFactory(); @Override String getType(); @Override ConnectionProvider getConnectionProvider(String connectionUrl, String username, St... | @Test public void testGetProviderAttributeNames() { BoneCPConnectionProviderFactory factory = new BoneCPConnectionProviderFactory(); Set<String> supported = factory.getProviderAttributeNames(); assertFalse("Supported settings cannot be empty", supported.isEmpty()); assertTrue("partitionCount is not found", supported.co... |
LegacyAccessControlAdapter { private Model getModel() { return _model; } LegacyAccessControlAdapter(final LegacyAccessControl accessControl,
final Model model); } | @Test public void testAuthoriseCreateGroup() { GroupProvider groupProvider = mock(GroupProvider.class); when(groupProvider.getCategoryClass()).thenReturn(GroupProvider.class); when(groupProvider.getAttribute(GroupProvider.NAME)).thenReturn("testGroupProvider"); when(groupProvider.getName()).thenReturn("testGroupProvide... |
DeliveryRegistryImpl implements DeliveryRegistry { @Override public void removeDeliveriesForLinkEndpoint(final LinkEndpoint<?, ?> linkEndpoint) { Iterator<UnsettledDelivery> iterator = _deliveries.values().iterator(); while (iterator.hasNext()) { UnsettledDelivery unsettledDelivery = iterator.next(); if (unsettledDeliv... | @Test public void removeDeliveriesForLinkEndpoint() { _registry.addDelivery(DELIVERY_ID, _unsettledDelivery); _registry.addDelivery(DELIVERY_ID_2, new UnsettledDelivery(DELIVERY_TAG_2, _unsettledDelivery.getLinkEndpoint())); _registry.addDelivery(UnsignedInteger.valueOf(2), new UnsettledDelivery(DELIVERY_TAG, mock(Link... |
LegacyAccessControlAdapter { Result authoriseMethod(final PermissionedObject configuredObject, final String methodName, final Map<String, Object> arguments) { Class<? extends ConfiguredObject> categoryClass = configuredObject.getCategoryClass(); Result invokeResult = _accessControl.authorise(INVOKE, getACLObjectTypeMan... | @Test public void testAuthoriseMethod() { when(_accessControl.authorise(same(LegacyOperation.INVOKE), any(ObjectType.class), any(ObjectProperties.class))).thenReturn(Result.DENIED); when(_accessControl.authorise(same(LegacyOperation.UPDATE), same(ObjectType.METHOD), any(ObjectProperties.class))).thenReturn(Result.ALLOW... |
ConnectionPrincipalLimitRule extends ConnectionPrincipalStatisticsRule { protected boolean matches(final AMQPConnection<?> connection) { return connection.getAuthenticatedPrincipalConnectionCount() <= getLimit(); } ConnectionPrincipalLimitRule(final int limit); @Override String toString(); } | @Test public void limitBreached() { when(_connection.getAuthenticatedPrincipalConnectionCount()).thenReturn(2); final ConnectionPrincipalLimitRule rule = new ConnectionPrincipalLimitRule(1); assertThat(rule.matches(_subject), is(false)); }
@Test public void frequencyEqualsLimit() { when(_connection.getAuthenticatedPrin... |
ConnectionPrincipalFrequencyLimitRule extends ConnectionPrincipalStatisticsRule { @Override boolean matches(final AMQPConnection<?> connection) { return connection.getAuthenticatedPrincipalConnectionFrequency() <= getLimit(); } ConnectionPrincipalFrequencyLimitRule(final int limit); @Override String toString(); } | @Test public void limitBreached() { when(_connection.getAuthenticatedPrincipalConnectionFrequency()).thenReturn(2); final ConnectionPrincipalFrequencyLimitRule rule = new ConnectionPrincipalFrequencyLimitRule(1); assertThat(rule.matches(_subject), is(false)); }
@Test public void frequencyEqualsLimit() { when(_connectio... |
DeliveryRegistryImpl implements DeliveryRegistry { @Override public UnsignedInteger getDeliveryId(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint) { return _deliveryIds.get(new UnsettledDelivery(deliveryTag, linkEndpoint)); } @Override void addDelivery(final UnsignedInteger deliveryId, final UnsettledD... | @Test public void getDeliveryId() { _registry.addDelivery(DELIVERY_ID, _unsettledDelivery); _registry.addDelivery(DELIVERY_ID_2, new UnsettledDelivery(DELIVERY_TAG, mock(LinkEndpoint.class))); final UnsignedInteger deliveryId = _registry.getDeliveryId(DELIVERY_TAG, _unsettledDelivery.getLinkEndpoint()); assertThat(deli... |
RuleBasedAccessControl implements AccessControl<CachingSecurityToken>, LegacyAccessControl { @Override public Result authorise(LegacyOperation operation, ObjectType objectType, ObjectProperties properties) { final Subject subject = Subject.getSubject(AccessController.getContext()); if (subject == null || subject.getPri... | @Test public void testNoSubjectAlwaysDefers() { setUpGroupAccessControl(); final Result result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); assertEquals(Result.DEFER, result); }
@Test public void testUsernameAllowsOperation() { setUpGroupAccessControl(); Subject.doAs(Test... |
DeliveryRegistryImpl implements DeliveryRegistry { @Override public int size() { return _deliveries.size(); } @Override void addDelivery(final UnsignedInteger deliveryId, final UnsettledDelivery unsettledDelivery); @Override void removeDelivery(final UnsignedInteger deliveryId); @Override UnsettledDelivery getDelivery... | @Test public void size() { assertThat(_registry.size(), is(equalTo(0))); _registry.addDelivery(DELIVERY_ID, _unsettledDelivery); assertThat(_registry.size(), is(equalTo(1))); _registry.removeDelivery(DELIVERY_ID); assertThat(_registry.size(), is(equalTo(0))); } |
AclAction { public Map<ObjectProperties.Property, String> getAttributes() { return _predicates.getParsedProperties(); } AclAction(LegacyOperation operation, ObjectType object, AclRulePredicates predicates); AclAction(LegacyOperation operation); AclAction(LegacyOperation operation, ObjectType object, ObjectProperties ... | @Test public void testGetAttributes() { final ObjectType objectType = ObjectType.VIRTUALHOST; final LegacyOperation operation = LegacyOperation.ACCESS; final AclRulePredicates predicates = new AclRulePredicates(); predicates.parse(ObjectProperties.Property.FROM_HOSTNAME.name(), TEST_HOSTNAME); predicates.parse(ObjectPr... |
ClientAction { public boolean matches(AclAction ruleAction, final Subject subject) { return _clientAction.matches(ruleAction.getAction()) && dynamicMatches(ruleAction.getDynamicRule(), subject); } ClientAction(Action clientAction); ClientAction(LegacyOperation operation, ObjectType objectType, ObjectProperties propert... | @Test public void testMatches_returnsTrueWhenActionsMatchAndNoFirewallRule() { when(_action.matches(any(Action.class))).thenReturn(true); when(_ruleAction.getDynamicRule()).thenReturn(null); when(_ruleAction.getAction()).thenReturn(mock(Action.class)); assertTrue(_clientAction.matches(_ruleAction, _subject)); }
@Test p... |
RuleSet implements EventLoggerProvider { public Result check(Subject subject, LegacyOperation operation, ObjectType objectType, ObjectProperties properties) { ClientAction action = new ClientAction(operation, objectType, properties); LOGGER.debug("Checking action: {}", action); List<Rule> rules = getRules(subject, oper... | @Test public void testVirtualHostNodeCreateAllowPermissionWithVirtualHostName() throws Exception { _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.ALLOW, LegacyOperation.CREATE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY); RuleSet ruleSet = createRuleSet(); assertEquals(Result.ALLOWED, ruleSet.check(_testSubj... |
Message_1_0_Mutator implements ServerMessageMutator<Message_1_0> { @Override public void setPriority(final byte priority) { if (_header == null) { _header = new Header(); } _header.setPriority(UnsignedByte.valueOf(priority)); } Message_1_0_Mutator(final Message_1_0 message, final MessageStore messageStore); @Override v... | @Test public void setPriority() { _messageMutator.setPriority((byte) (TEST_PRIORITY + 1)); assertThat(_messageMutator.getPriority(), is(equalTo((byte) (TEST_PRIORITY + 1)))); } |
Action { private boolean propertiesMatch(Action a) { boolean propertiesMatch = false; if (_properties != null) { propertiesMatch = _properties.propertiesMatch(a.getProperties()); } else if (a.getProperties() == null) { propertiesMatch = true; } return propertiesMatch; } Action(LegacyOperation operation); Action(Legacy... | @Test public void testMatchesReturnsTrueForMatchingActions() { when(_properties1.propertiesMatch(_properties2)).thenReturn(true); assertMatches( new Action(LegacyOperation.CONSUME, ObjectType.QUEUE, _properties1), new Action(LegacyOperation.CONSUME, ObjectType.QUEUE, _properties2)); } |
Message_1_0_Mutator implements ServerMessageMutator<Message_1_0> { @Override public byte getPriority() { if (_header == null || _header.getPriority() == null) { return 4; } else { return _header.getPriority().byteValue(); } } Message_1_0_Mutator(final Message_1_0 message, final MessageStore messageStore); @Override voi... | @Test public void getPriority() { assertThat((int) _messageMutator.getPriority(), is(equalTo((int) TEST_PRIORITY))); } |
HostnameFirewallRule extends FirewallRule { @Override protected boolean matches(InetAddress remote) { String hostname = getHostname(remote); if (hostname == null) { throw new AccessControlFirewallException("DNS lookup failed for address " + remote); } for (Pattern pattern : _hostnamePatterns) { boolean hostnameMatches ... | @Test public void testSingleHostname() throws Exception { String hostnameInRule = "hostnameInRule"; InetAddress addressWithMatchingHostname = mock(InetAddress.class); when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn(hostnameInRule); _HostnameFirewallRule = new HostnameFirewallRule(hostnameInRule); as... |
NetworkFirewallRule extends FirewallRule { @Override protected boolean matches(InetAddress ip) { for (InetNetwork network : _networks) { if (network.contains(ip)) { LOGGER.debug("Client address {} matches configured network {}", ip, network); return true; } } LOGGER.debug("Client address {} does not match any configure... | @Test public void testIpRule() throws Exception { String ipAddressInRule = OTHER_IP_1; _networkFirewallRule = new NetworkFirewallRule(ipAddressInRule); assertFalse(_networkFirewallRule.matches(_addressNotInRule)); assertTrue(_networkFirewallRule.matches(InetAddress.getByName(ipAddressInRule))); }
@Test public void test... |
MessageConverter_1_0_to_v0_10 implements MessageConverter<Message_1_0, MessageTransferMessage> { @Override public MessageTransferMessage convert(Message_1_0 serverMsg, NamedAddressSpace addressSpace) { return new MessageTransferMessage(convertToStoredMessage(serverMsg, addressSpace), null); } @Override Class<Message_1... | @Test public void testAmqpValueWithNullWithTextMessageAnnotation() throws Exception { final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(TEXT_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection()); final MessageTransferMessag... |
Message_1_0_Mutator implements ServerMessageMutator<Message_1_0> { @Override public Message_1_0 create() { final long contentSize = _message.getSize(); HeaderSection headerSection = null; if (_header != null) { headerSection = _header.createEncodingRetainingSection(); } DeliveryAnnotationsSection deliveryAnnotationsSec... | @Test public void create() throws Exception { _messageMutator.setPriority((byte) (TEST_PRIORITY + 1)); final Message_1_0 newMessage = _messageMutator.create(); assertThat(newMessage.getMessageHeader().getPriority(), is(equalTo((byte) (TEST_PRIORITY + 1)))); assertThat(newMessage.getMessageHeader().getMimeType(), is(equ... |
ConsumerTarget_1_0 extends AbstractConsumerTarget<ConsumerTarget_1_0> { @Override public void doSend(final MessageInstanceConsumer consumer, final MessageInstance entry, boolean batch) { ServerMessage serverMessage = entry.getMessage(); Message_1_0 message; final MessageConverter<? super ServerMessage, Message_1_0> con... | @Test public void testTTLAdjustedOnSend() throws Exception { final MessageInstanceConsumer comsumer = mock(MessageInstanceConsumer.class); long ttl = 2000L; long arrivalTime = System.currentTimeMillis() - 1000L; final Header header = new Header(); header.setTtl(UnsignedInteger.valueOf(ttl)); final Message_1_0 message =... |
Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget_1_0> implements LogSubject, org.apache.qpid.server.util.Deletable<Session_1_0> { public void receiveAttach(final Attach attach) { receivedComplete(); if(_sessionState == SessionState.ACTIVE) { UnsignedInteger inputHandle = attach.getHandle(); if (_inpu... | @Test public void testReceiveAttachTopicNonDurableNoContainer() throws Exception { final String linkName = "testLink"; final String address = "amq.direct/" + TOPIC_NAME; Attach attach = createTopicAttach(false, linkName, address, true); _session.receiveAttach(attach); assertAttachSent(_connection, _session, attach); as... |
MessageConverter_0_10_to_1_0 extends MessageConverter_to_1_0<MessageTransferMessage> { @Override public String getType() { return "v0-10 to v1-0"; } @Override Class<MessageTransferMessage> getInputClass(); @Override String getType(); } | @Test public void testConvertJmsStreamMessageBody() throws Exception { final List<Object> expected = Lists.newArrayList("apple", 43, 31.42D); final byte[] messageBytes = getJmsStreamMessageBytes(expected); final String mimeType = "jms/stream-message"; doTestStreamMessage(messageBytes, mimeType, expected, JmsMessageType... |
JDBCSettingsDrivenConnectionSource extends ConnectionSourceBase { @Override public void start() { _connectionProvider.getAndUpdate(provider -> provider == null ? create() : provider); discoverConnectionProperties(); if (!supportsGetGeneratedKeys() && getSQLDialectCode() == SQLDialectCode.UNKNOWN_DIALECT) { addWarn("Con... | @Test public void testStart() throws SQLException { try { _connectionSource.getConnection(); fail("connection should fail for non started ConnectionSource"); } catch (IllegalConfigurationException e) { } _connectionSource.start(); final Connection connection = _connectionSource.getConnection(); connection.close(); } |
JDBCSettingsDrivenConnectionSource extends ConnectionSourceBase { @Override public void stop() { super.stop(); final ConnectionProvider connectionProvider = _connectionProvider.getAndSet(null); if (connectionProvider != null) { try { connectionProvider.close(); } catch (SQLException e) { LOGGER.warn("Unable to close co... | @Test public void testStop() throws SQLException { _connectionSource.start(); _connectionSource.stop(); try { _connectionSource.getConnection(); fail("connection should fail for stopped ConnectionSource"); } catch (IllegalConfigurationException e) { } } |
JDBCSettingsDrivenConnectionSource extends ConnectionSourceBase { @Override public Connection getConnection() throws SQLException { final ConnectionProvider connectionProvider = _connectionProvider.get(); if (connectionProvider == null) { throw new IllegalConfigurationException("Connection provider does not exist"); } ... | @Test public void testGetConnection() throws SQLException { _connectionSource.start(); final Connection connection = _connectionSource.getConnection(); connection.close(); } |
JDBCVirtualHostLoggerImpl extends AbstractVirtualHostLogger<JDBCVirtualHostLoggerImpl> implements JDBCVirtualHostLogger<JDBCVirtualHostLoggerImpl> { @Override public String getTableNamePrefix() { return _tableNamePrefix; } @ManagedObjectFactoryConstructor protected JDBCVirtualHostLoggerImpl(final Map<String, Object> a... | @Test public void changeTablePrefix() { _logger.create(); final Map<String, Object> attributes = Collections.singletonMap(JDBCSettings.TABLE_NAME_PREFIX, TABLE_PREFIX); _logger.setAttributes(attributes); assertEquals(TABLE_PREFIX, _logger.getTableNamePrefix()); } |
JDBCBrokerLoggerImpl extends AbstractBrokerLogger<JDBCBrokerLoggerImpl> implements JDBCBrokerLogger<JDBCBrokerLoggerImpl> { @Override public String getTableNamePrefix() { return _tableNamePrefix; } @ManagedObjectFactoryConstructor protected JDBCBrokerLoggerImpl(final Map<String, Object> attributes, Broker<?> broker); ... | @Test public void changeTablePrefix() { _logger.create(); final Map<String, Object> attributes = Collections.singletonMap(JDBCSettings.TABLE_NAME_PREFIX, TABLE_PREFIX); _logger.setAttributes(attributes); assertEquals(TABLE_PREFIX, _logger.getTableNamePrefix()); } |
JDBCSettingsDBNameResolver implements DBNameResolver { @Override public <N extends Enum<?>> String getTableName(final N tableName) { final String settingsTableNamePrefix = _settings.getTableNamePrefix(); final String prefix = settingsTableNamePrefix == null ? "" : settingsTableNamePrefix; final String name = prefix + t... | @Test public void getTableName() { assertEquals((TABLE_PREFIX + TableName.LOGGING_EVENT.name()).toLowerCase(), _dbNameResolver.getTableName(TableName.LOGGING_EVENT)); } |
JDBCSettingsDBNameResolver implements DBNameResolver { @Override public <N extends Enum<?>> String getColumnName(final N columnName) { return columnName.toString().toLowerCase(); } JDBCSettingsDBNameResolver(final JDBCSettings settings); @Override String getTableName(final N tableName); @Override String getColumnName(f... | @Test public void getColumnName() { assertEquals(ColumnName.LOGGER_NAME.name().toLowerCase(), _dbNameResolver.getColumnName(ColumnName.LOGGER_NAME)); } |
JDBCLoggerHelper { Appender<ILoggingEvent> createAppenderInstance(final Context context, final ConfiguredObject<?> logger, final JDBCSettings settings) { try { final JDBCSettingsDBNameResolver dbNameResolver = new JDBCSettingsDBNameResolver(settings); final ConnectionSource connectionSource = createConnectionSource(con... | @Test public void createAppenderInstance() { final LoggerContext context = ROOT_LOGGER.getLoggerContext(); final Appender<ILoggingEvent> appender = _jdbcLoggerHelper.createAppenderInstance(context, _broker, _jdbcSettings); assertTrue(appender instanceof DBAppender); assertTrue(appender.isStarted()); assertEquals(contex... |
JDBCLoggerHelper { void restartAppenderIfExists(final Appender appender) { if (appender != null) { appender.stop(); appender.start(); } } } | @Test public void restartAppenderIfExists() { final Appender appender = mock(Appender.class); _jdbcLoggerHelper.restartAppenderIfExists(appender); verify(appender).stop(); verify(appender).start(); verifyNoMoreInteractions(appender); } |
JDBCLoggerHelper { void restartConnectionSourceIfExists(final Appender appender) { if (appender instanceof DBAppender) { final ConnectionSource connectionSource = ((DBAppender) appender).getConnectionSource(); if (connectionSource != null) { connectionSource.stop(); connectionSource.start(); } } } } | @Test public void restartConnectionSourceIfExists() { final ConnectionSource connectionSource = mock(ConnectionSource.class); final DBAppender appender = mock(DBAppender.class); when(appender.getConnectionSource()).thenReturn(connectionSource); _jdbcLoggerHelper.restartConnectionSourceIfExists(appender); verify(connect... |
JDBCLoggerHelper { void validateConnectionSourceSettings(final ConfiguredObject<?> logger, final JDBCSettings settings) { try { final ConnectionSource connectionSource = createConnectionSource(logger, settings); connectionSource.getConnection().close(); } catch (Exception e) { throw new IllegalConfigurationException( "... | @Test public void validateConnectionSourceSettings() { _jdbcLoggerHelper.validateConnectionSourceSettings(_broker, _jdbcSettings); }
@Test public void validateConnectionSourceSettingsForInvalidURL() { when(_jdbcSettings.getConnectionUrl()).thenReturn(INVALID_JDBC_URL); try { _jdbcLoggerHelper.validateConnectionSourceSe... |
StoreConfigurationChangeListener implements ConfigurationChangeListener { @Override public void stateChanged(ConfiguredObject object, State oldState, State newState) { if (newState == State.DELETED) { if(object.isDurable()) { _store.remove(object.asObjectRecord()); } object.removeChangeListener(this); } } StoreConfigur... | @Test public void testStateChanged() { notifyBrokerStarted(); UUID id = UUID.randomUUID(); ConfiguredObject object = mock(VirtualHost.class); when(object.isDurable()).thenReturn(true); when(object.getId()).thenReturn(id); ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class); when(object.asObjectRecord()).... |
StoreConfigurationChangeListener implements ConfigurationChangeListener { @Override public void childAdded(ConfiguredObject<?> object, ConfiguredObject<?> child) { if (!object.managesChildStorage()) { if(object.isDurable() && child.isDurable()) { Model model = child.getModel(); Class<? extends ConfiguredObject> parentT... | @Test public void testChildAdded() { notifyBrokerStarted(); Broker broker = mock(Broker.class); when(broker.getCategoryClass()).thenReturn(Broker.class); when(broker.isDurable()).thenReturn(true); VirtualHost child = mock(VirtualHost.class); when(child.getCategoryClass()).thenReturn(VirtualHost.class); Model model = mo... |
StoreConfigurationChangeListener implements ConfigurationChangeListener { @Override public void attributeSet(ConfiguredObject object, String attributeName, Object oldAttributeValue, Object newAttributeValue) { if (object.isDurable() && !_bulkChanges) { _store.update(false, object.asObjectRecord()); } } StoreConfigurati... | @Test public void testAttributeSet() { notifyBrokerStarted(); Broker broker = mock(Broker.class); when(broker.getCategoryClass()).thenReturn(Broker.class); when(broker.isDurable()).thenReturn(true); final ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class); when(broker.asObjectRecord()).thenReturn(record... |
ManagementModeStoreHandler implements DurableConfigurationStore { @Override public void init(final ConfiguredObject<?> parent) throws StoreException { changeState(StoreState.CLOSED, StoreState.CONFIGURED); _parent = parent; _store.init(parent); } ManagementModeStoreHandler(DurableConfigurationStore store,
... | @Test public void testGetRootEntryWithHttpPortOverriden() { _systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,9090); _handler = createManagementModeStoreHandler(); _handler.init(_systemConfig); Collection<ConfiguredObjectRecord> records = openAndGetRecords(); ConfiguredObjectRecord root = getR... |
ManagementModeStoreHandler implements DurableConfigurationStore { @Override public synchronized UUID[] remove(final ConfiguredObjectRecord... records) { assertState(StoreState.OPEN); synchronized (_store) { UUID[] idsToRemove = new UUID[records.length]; for(int i = 0; i < records.length; i++) { idsToRemove[i] = records... | @Test public void testRemove() { _systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,1000); _handler = createManagementModeStoreHandler(); _handler.init(_systemConfig); Collection<ConfiguredObjectRecord> records = openAndGetRecords(); ConfiguredObjectRecord record = new ConfiguredObjectRecord() ... |
LocalTransaction implements ServerTransaction { @Override public void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction) { sync(); _outstandingWork = true; initTransactionStartTimeIfNecessaryAndAdvanceUpdateTime(); _transactionObserver.onMessageEnqueue(this, message);... | @Test public void testEnqueueToNonDurableQueueOfNonPersistentMessage() throws Exception { _message = createTestMessage(false); _queue = createQueue(false); _transaction.enqueue(_queue, _message, _action1); assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", (long) 0, (long) _storeTra... |
LocalTransaction implements ServerTransaction { @Override public void dequeue(MessageEnqueueRecord record, Action postTransactionAction) { sync(); _outstandingWork = true; _postTransactionActions.add(postTransactionAction); initTransactionStartTimeIfNecessaryAndAdvanceUpdateTime(); if(record != null) { try { if (LOGGER... | @Test public void testDequeueFromNonDurableQueueOfNonPersistentMessage() throws Exception { _message = createTestMessage(false); _queue = createQueue(false); _transaction.dequeue((MessageEnqueueRecord)null, _action1); assertEquals("Dequeue of non-persistent message must not cause message to be enqueued", (long) 0, (lon... |
SendingLinkEndpoint extends AbstractLinkEndpoint<Source, Target> implements AsyncAutoCommitTransaction.FutureRecorder { @Override public void receiveFlow(final Flow flow) { UnsignedInteger receiverDeliveryCount = flow.getDeliveryCount(); UnsignedInteger receiverLinkCredit = flow.getLinkCredit(); setDrain(flow.getDrain(... | @Test public void receiveFlow() throws Exception { receiveAttach(_sendingLinkEndpoint); _sendingLinkEndpoint.setDeliveryCount(new SequenceNumber(-1)); Flow flow = new Flow(); flow.setDeliveryCount(new SequenceNumber(-1).unsignedIntegerValue()); flow.setLinkCredit(UnsignedInteger.ONE); _sendingLinkEndpoint.receiveFlow(f... |
LocalTransaction implements ServerTransaction { @Override public void addPostTransactionAction(Action postTransactionAction) { sync(); _postTransactionActions.add(postTransactionAction); } LocalTransaction(MessageStore transactionLog); LocalTransaction(MessageStore transactionLog, TransactionObserver transactionObserv... | @Test public void testAddingPostCommitActionNotFiredImmediately() throws Exception { _transaction.addPostTransactionAction(_action1); assertNotFired(_action1); } |
LocalTransaction implements ServerTransaction { @Override public void commit() { commit(null); } LocalTransaction(MessageStore transactionLog); LocalTransaction(MessageStore transactionLog, TransactionObserver transactionObserver); LocalTransaction(MessageStore transactionLog,
ActivityTime... | @Test public void testCommitNoWork() throws Exception { _transaction.commit(); assertEquals("Unexpected number of store dequeues", (long) 0, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected number of store enqueues", (long) 0, (long) _storeTransaction.getNumberOfEnqueuedMessages()); ass... |
LocalTransaction implements ServerTransaction { @Override public void rollback() { sync(); if (!_state.compareAndSet(LocalTransactionState.ACTIVE, LocalTransactionState.DISCHARGING) && !_state.compareAndSet(LocalTransactionState.ROLLBACK_ONLY, LocalTransactionState.DISCHARGING) && _state.get() != LocalTransactionState.... | @Test public void testRollbackNoWork() throws Exception { _transaction.rollback(); assertEquals("Unexpected number of store dequeues", (long) 0, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected number of store enqueues", (long) 0, (long) _storeTransaction.getNumberOfEnqueuedMessages());... |
AutoCommitTransaction implements ServerTransaction { @Override public void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction) { Transaction txn = null; try { final MessageEnqueueRecord record; if(queue.getMessageDurability().persist(message.isPersistent())) { LOGGER.d... | @Test public void testEnqueueToNonDurableQueueOfNonPersistentMessage() throws Exception { _message = createTestMessage(false); _queue = createTestAMQQueue(false); _transaction.enqueue(_queue, _message, _action); assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", (long) 0, (long) _st... |
AutoCommitTransaction implements ServerTransaction { @Override public void dequeue(MessageEnqueueRecord record, Action postTransactionAction) { Transaction txn = null; try { if(record != null) { LOGGER.debug("Dequeue of message number {} from transaction log. Queue : {}", record.getMessageNumber(), record.getQueueId())... | @Test public void testDequeueFromNonDurableQueueOfNonPersistentMessage() throws Exception { _message = createTestMessage(false); _queue = createTestAMQQueue(false); _transaction.dequeue((MessageEnqueueRecord)null, _action); assertEquals("Dequeue of non-persistent message must not cause message to be dequeued", (long) 0... |
AutoCommitTransaction implements ServerTransaction { @Override public void addPostTransactionAction(final Action immediateAction) { immediateAction.postCommit(); } AutoCommitTransaction(MessageStore transactionLog); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addP... | @Test public void testPostCommitActionFiredImmediately() throws Exception { _transaction.addPostTransactionAction(_action); assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); assertFalse("Rollback action must be fired", _action.isRollbackActionFired()); } |
AsyncAutoCommitTransaction implements ServerTransaction { @Override public void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction) { Transaction txn = null; try { ListenableFuture<Void> future; final MessageEnqueueRecord enqueueRecord; if(queue.getMessageDurability().... | @Test public void testEnqueuePersistentMessagePostCommitNotCalledWhenFutureAlreadyComplete() throws Exception { setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "false"); when(_message.isPersistent()).thenReturn(true); when(_future.isDone()).thenReturn(true); AsyncAutoCommitTransaction asyncAutoCommitTransaction = n... |
FlowToDiskTransactionObserver implements TransactionObserver { @Override public void onMessageEnqueue(final ServerTransaction transaction, final EnqueueableMessage<? extends StorableMessageMetaData> message) { StoredMessage<? extends StorableMessageMetaData> handle = message.getStoredMessage(); long messageSize = handl... | @Test public void testOnMessageEnqueue() throws Exception { EnqueueableMessage<?> message1 = createMessage(MAX_UNCOMMITTED_IN_MEMORY_SIZE); EnqueueableMessage<?> message2 = createMessage(1); EnqueueableMessage<?> message3 = createMessage(1); _flowToDiskMessageObserver.onMessageEnqueue(_transaction, message1); StoredMes... |
FlowToDiskTransactionObserver implements TransactionObserver { @Override public void onDischarge(final ServerTransaction transaction) { TransactionDetails transactionDetails = _uncommittedMessages.remove(transaction); if (transactionDetails != null) { _uncommittedMessageSize.addAndGet(-transactionDetails.getUncommitted... | @Test public void testOnDischarge() throws Exception { EnqueueableMessage<?> message1 = createMessage(MAX_UNCOMMITTED_IN_MEMORY_SIZE - 1); EnqueueableMessage<?> message2 = createMessage(1); EnqueueableMessage<?> message3 = createMessage(1); _flowToDiskMessageObserver.onMessageEnqueue(_transaction, message1); final Serv... |
HeadersBinding { public boolean matches(AMQMessageHeader headers) { if(headers == null) { return required.isEmpty() && matches.isEmpty(); } else { return matchAny ? or(headers) : and(headers); } } HeadersBinding(AbstractExchange.BindingIdentifier binding, Map<String,Object> arguments); AbstractExchange.BindingIdentifie... | @Test public void testDefault_1() throws Exception { bindHeaders.put("A", "Value of A"); matchHeaders.setString("A", "Value of A"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertTrue(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); }
@Test public ... |
ConnectionVersionValidator implements ConnectionValidator { @Override public boolean validateConnectionCreation(final AMQPConnection<?> connection, final QueueManagingVirtualHost<?> virtualHost) { String connectionVersion = connection.getClientVersion(); if (connectionVersion == null) { connectionVersion = ""; } boolea... | @Test public void testInvalidRegex() { Map<String, List<String>> contextValues = new HashMap<>(); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList("${}", "foo")); setContextValues(contextValues); when(_connectionMock.getClientVersion()).thenReturn("foo"); assertFalse(_... |
SSLUtil { static String[] filterEntries(final String[] enabledEntries, final String[] supportedEntries, final List<String> allowList, final List<String> denyList) { List<String> filteredList; if (allowList != null && !allowList.isEmpty()) { filteredList = new ArrayList<>(); List<String> supportedList = new ArrayList<>(... | @Test public void testFilterEntries_empty() { String[] enabled = {}; String[] supported = {}; List<String> allowList = Arrays.asList(); List<String> denyList = Arrays.asList(); String[] result = SSLUtil.filterEntries(enabled, supported, allowList, denyList); assertEquals("filtered list is not empty", (long) 0, (long) r... |
RollingPolicyDecorator implements RollingPolicy { @Override public void rollover() throws RolloverFailure { ScanTask task = createScanTaskAndCancelInProgress(); _decorated.rollover(); _executorService.execute(task); } RollingPolicyDecorator(RollingPolicyBase decorated, RolloverListener listener, ScheduledExecutorServic... | @Test public void testRollover() { _policy.rollover(); verify(_delegate).rollover(); }
@Test public void testRolloverListener() throws InterruptedException { _policy.rollover(); verify(_listener).onRollover(any(Path.class), any(String[].class)); }
@Test public void testRolloverWithFile() throws IOException { _policy.ro... |
SSLUtil { public static String getIdFromSubjectDN(String dn) { String cnStr = null; String dcStr = null; if(dn == null) { return ""; } else { try { LdapName ln = new LdapName(dn); for(Rdn rdn : ln.getRdns()) { if("CN".equalsIgnoreCase(rdn.getType())) { cnStr = rdn.getValue().toString(); } else if("DC".equalsIgnoreCase(... | @Test public void testGetIdFromSubjectDN() { assertEquals("user@somewhere.example.org", SSLUtil.getIdFromSubjectDN("cn=user,dc=somewhere,dc=example,dc=org")); assertEquals("user2@somewhere.example.org", SSLUtil.getIdFromSubjectDN("DC=somewhere, dc=example,cn=\"user2\",dc=org")); assertEquals("user@somewhere.example.org... |
SSLUtil { public static X509Certificate[] readCertificates(URL certFile) throws IOException, GeneralSecurityException { try (InputStream is = certFile.openStream()) { return readCertificates(is); } } private SSLUtil(); static CertificateFactory getCertificateFactory(); static void verifyHostname(SSLEngine engine,Strin... | @Test public void testReadCertificates() throws Exception { Certificate certificate = getTestCertificate(); assertNotNull("Certificate is not found", certificate); URL certificateURL = new URL(null, DataUrlUtils.getDataUrlForBytes(certificate.getEncoded()), new Handler()); X509Certificate[] certificates = SSLUtil.readC... |
TransactionTimeoutTicker implements Ticker, SchedulingDelayNotificationListener { @Override public void notifySchedulingDelay(final long schedulingDelay) { if (schedulingDelay > 0) { long accumulatedSchedulingDelay; do { accumulatedSchedulingDelay = _accumulatedSchedulingDelay.get(); } while (!_accumulatedSchedulingDel... | @Test public void testTickDuringSingleTransactionWithSchedulingDelay() throws Exception { final long timeNow = System.currentTimeMillis(); final long transactionTime = timeNow - 90; when(_dateSupplier.get()).thenReturn(transactionTime); _ticker = new TransactionTimeoutTicker(_timeoutValue, _notificationRepeatPeriod, _d... |
SystemLauncher { public void startup(final Map<String,Object> systemConfigAttributes) throws Exception { final SystemOutMessageLogger systemOutMessageLogger = new SystemOutMessageLogger(); _eventLogger = new EventLogger(systemOutMessageLogger); Subject.doAs(_brokerTaskSubject, new PrivilegedExceptionAction<Object>() { ... | @Test public void testInitialSystemPropertiesAreSetOnBrokerStartup() throws Exception { Map<String,Object> attributes = new HashMap<>(); attributes.put(SystemConfig.INITIAL_SYSTEM_PROPERTIES_LOCATION, _initialSystemProperties.getAbsolutePath()); attributes.put(SystemConfig.INITIAL_CONFIGURATION_LOCATION, _initialConfig... |
GZIPUtils { public static byte[] uncompressBufferToArray(ByteBuffer contentBuffer) { if(contentBuffer != null) { try (ByteBufferInputStream input = new ByteBufferInputStream(contentBuffer)) { return uncompressStreamToArray(input); } } else { return null; } } static byte[] compressBufferToArray(ByteBuffer input); stati... | @Test public void testUncompressNonZipReturnsNull() throws Exception { byte[] data = new byte[1024]; Arrays.fill(data, (byte)'a'); assertNull("Non zipped data should not uncompress", GZIPUtils.uncompressBufferToArray(ByteBuffer.wrap(data))); }
@Test public void testUncompressNullBufferReturnsNull() throws Exception { a... |
GZIPUtils { public static byte[] uncompressStreamToArray(InputStream stream) { if(stream != null) { try (GZIPInputStream gzipInputStream = new GZIPInputStream(stream)) { ByteArrayOutputStream inflatedContent = new ByteArrayOutputStream(); int read; byte[] buf = new byte[4096]; while ((read = gzipInputStream.read(buf)) ... | @Test public void testUncompressStreamWithErrorReturnsNull() throws Exception { InputStream is = new InputStream() { @Override public int read() throws IOException { throw new IOException(); } }; assertNull("Stream error should return null", GZIPUtils.uncompressStreamToArray(is)); }
@Test public void testUncompressNull... |
GZIPUtils { public static byte[] compressBufferToArray(ByteBuffer input) { if(input != null) { try (ByteArrayOutputStream compressedBuffer = new ByteArrayOutputStream()) { try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(compressedBuffer)) { if (input.hasArray()) { gzipOutputStream.write(input.array(), inp... | @Test public void testCompressNullArrayReturnsNull() { assertNull(GZIPUtils.compressBufferToArray(null)); } |
FileHelper { public Path createNewFile(File newFile, String posixFileAttributes) throws IOException { return createNewFile(newFile.toPath(), posixFileAttributes); } void writeFileSafely(Path targetFile, BaseAction<File, IOException> operation); void writeFileSafely(Path targetFile, Path backupFile, Path tmpFile, BaseA... | @Test public void testCreateNewFile() throws Exception { assertFalse("File should not exist", _testFile.exists()); Path path = _fileHelper.createNewFile(_testFile, TEST_FILE_PERMISSIONS); assertTrue("File was not created", path.toFile().exists()); if (Files.getFileAttributeView(path, PosixFileAttributeView.class) != nu... |
FileHelper { public void writeFileSafely(Path targetFile, BaseAction<File, IOException> operation) throws IOException { String name = targetFile.toFile().getName(); writeFileSafely(targetFile, targetFile.resolveSibling(name + ".bak"), targetFile.resolveSibling(name + ".tmp"), operation); } void writeFileSafely(Path ta... | @Test public void testWriteFileSafely() throws Exception { Path path = _fileHelper.createNewFile(_testFile, TEST_FILE_PERMISSIONS); _fileHelper.writeFileSafely(path, new BaseAction<File, IOException>() { @Override public void performAction(File file) throws IOException { Files.write(file.toPath(), "test".getBytes("UTF8... |
FileHelper { public Path atomicFileMoveOrReplace(Path sourceFile, Path targetFile) throws IOException { try { return Files.move(sourceFile, targetFile, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch(AtomicMoveNotSupportedException e) { if (sourceFile.toFile().renameTo(targetFile.toFile())... | @Test public void testAtomicFileMoveOrReplace() throws Exception { Path path = _fileHelper.createNewFile(_testFile, TEST_FILE_PERMISSIONS); Files.write(path, "test".getBytes("UTF8")); _testFile = _fileHelper.atomicFileMoveOrReplace(path, path.resolveSibling(_testFile.getName() + ".target")).toFile(); assertFalse("File ... |
FileHelper { public boolean isWritableDirectory(String path) { File storePath = new File(path).getAbsoluteFile(); if (storePath.exists()) { if (!storePath.isDirectory()) { return false; } } else { do { storePath = storePath.getParentFile(); if (storePath == null) { return false; } } while (!storePath.exists()); } retur... | @Test public void testIsWritableDirectoryForNonWritablePath() throws Exception { File workDir = TestFileUtils.createTestDirectory("test", true); try { if (Files.getFileAttributeView(workDir.toPath(), PosixFileAttributeView.class) != null) { File file = new File(workDir, getTestName()); file.mkdirs(); if (file.setWritab... |
Strings { public static String hexDump(ByteBuffer buf) { StringBuilder builder = new StringBuilder(); int count = 0; for(int p = buf.position(); p < buf.position() + buf.remaining(); p++) { if (count % 16 == 0) { if (count > 0) { builder.append(String.format("%n")); } builder.append(String.format("%07x ", count)); } bu... | @Test public void hexDumpSingleByte() { String expected = String.format("0000000 41%n" + "0000001%n"); String actual = Strings.hexDump(ByteBuffer.wrap("A".getBytes())); assertThat(actual, is(equalTo(expected))); }
@Test public void hexDumpManyBytes() { String expected = String.format("0000000 31 32 33 34 35 36 37 38 31... |
CommandLineParser { public String getOptionsInForce() { if (parsedProperties == null) { return ""; } StringBuilder result = new StringBuilder("Options in force:\n"); for (Map.Entry<Object, Object> property : parsedProperties.entrySet()) { result.append(property.getKey()) .append(" = ") .append(property.getValue()) .app... | @Test public void testGetOptionsInForceReturnsEmptyStringBeforeParsing() throws Exception { CommandLineParser parser = new CommandLineParser( new String[][] { { "t1", "Test Flag 1." }, { "t2", "Test Option 2.", "test" }, { "t3", "Test Option 3.", "test", "true" }, { "t4", "Test Option 4.", "test", null, "^test$" } }); ... |
CommandLineParser { public String getUsage() { String result = "Options:\n"; for (CommandLineOption optionInfo : optionMap.values()) { result += "-" + optionInfo.option + " " + ((optionInfo.argument != null) ? (optionInfo.argument + " ") : "") + optionInfo.comment + "\n"; } return result; } CommandLineParser(String[][]... | @Test public void testGetUsageReturnsString() throws Exception { CommandLineParser parser = new CommandLineParser( new String[][] { { "t1", "Test Flag 1." }, { "t2", "Test Option 2.", "test" }, { "t3", "Test Option 3.", "test", "true" }, { "t4", "Test Option 4.", "test", null, "^test$" } }); final boolean condition = !... |
CommandLineParser { public Properties parseCommandLine(String[] args) throws IllegalArgumentException { Properties options = new Properties(); int free = 1; boolean expectingArgs = false; String optionExpectingArgs = null; boolean ignore = false; StringBuilder regexp = new StringBuilder("^("); int optionsAdded = 0; for... | @Test public void testParseCondensedFlagsOk() throws Exception { CommandLineParser parser = new CommandLineParser( new String[][] { { "t1", "Test Flag 1." }, { "t2", "Test Flag 2." }, { "t3", "Test Flag 3." } }); Properties testProps = parser.parseCommandLine(new String[] { "-t1t2t3" }); assertTrue("The t1 flag was not... |
StringUtil { public String randomAlphaNumericString(int maxLength) { char[] result = new char[maxLength]; for (int i = 0; i < maxLength; i++) { result[i] = (char) CHARACTERS[_random.nextInt(CHARACTERS.length)]; } return new String(result); } static String elideDataUrl(final String path); static String toHex(byte[] bin... | @Test public void testRandomAlphaNumericStringInt() { String password = _util.randomAlphaNumericString(10); assertEquals("Unexpected password string length", (long) 10, (long) password.length()); assertCharacters(password); } |
StringUtil { public String createUniqueJavaName(String managerName) { StringBuilder builder = new StringBuilder(); boolean initialChar = true; for (int i = 0; i < managerName.length(); i++) { char c = managerName.charAt(i); if ((initialChar && Character.isJavaIdentifierStart(c)) || (!initialChar && Character.isJavaIden... | @Test public void testCreateUniqueJavaName() { assertEquals("MyName_973de1b4e26b629d4817c8255090e58e", _util.createUniqueJavaName("MyName")); assertEquals("ContaisIllegalJavaCharacters_a68b2484f2eb790558d6527e56c595fa", _util.createUniqueJavaName("Contais+Illegal-Java*Characters")); assertEquals("StartsWithIllegalIniti... |
FileUtils { public static void copyRecursive(File source, File dst) throws FileNotFoundException, UnableToCopyException { if (!source.exists()) { throw new FileNotFoundException("Unable to copy '" + source.toString() + "' as it does not exist."); } if (dst.exists() && !dst.isDirectory()) { throw new IllegalArgumentExce... | @Test public void testCopyRecursive() { final String TEST_DATA = "FileUtilsTest-testDirectoryCopy-TestDataTestDataTestDataTestDataTestDataTestData"; String fileName = "FileUtilsTest-testCopy"; String TEST_DIR = "testDirectoryCopy"; File testDir = new File(TEST_DIR); File[] beforeCopyFileList = testDir.getAbsoluteFile()... |
FileUtils { public static boolean deleteFile(String filePath) { return delete(new File(filePath), false); } private FileUtils(); static byte[] readFileAsBytes(String filename); static String readFileAsString(String filename); static String readFileAsString(File file); @SuppressWarnings("resource") static InputStream o... | @Test public void testDeleteFile() { File test = new File("FileUtilsTest-testDelete"); String path = test.getAbsolutePath(); File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles(); int fileCountBefore = filesBefore.length; try { test.createNewFile(); test.deleteOnExit(); } catch ... |
FileUtils { public static boolean delete(File file, boolean recursive) { boolean success = true; if (file.isDirectory()) { if (recursive) { File[] files = file.listFiles(); if (files == null) { LOG.debug("Recursive delete failed as file was deleted outside JVM"); return false; } for (int i = 0; i < files.length; i++) {... | @Test public void testDeleteNonExistentFile() { File test = new File("FileUtilsTest-testDelete-" + System.currentTimeMillis()); final boolean condition1 = !test.exists(); assertTrue("File exists", condition1); assertFalse("File is a directory", test.isDirectory()); final boolean condition = !FileUtils.delete(test, true... |
FileUtils { @SuppressWarnings("resource") public static InputStream openFileOrDefaultResource(String filename, String defaultResource, ClassLoader cl) { InputStream is = null; if (filename != null) { try { is = new BufferedInputStream(new FileInputStream(new File(filename))); } catch (FileNotFoundException e) { is = nu... | @Test public void testOpenFileOrDefaultResourceOpensFileOnFileSystem() throws Exception { final File testFile = createTestFileInTmpDir("src=tmpfile"); final String filenameOnFilesystem = testFile.getCanonicalPath(); final String defaultResource = "org/apache/qpid/util/default.properties"; final InputStream is = FileUti... |
FileUtils { public static boolean deleteDirectory(String directoryPath) { File directory = new File(directoryPath); if (directory.isDirectory()) { if (directory.listFiles().length == 0) { return delete(directory, true); } } return false; } private FileUtils(); static byte[] readFileAsBytes(String filename); static Str... | @Test public void testEmptyDirectoryDelete() { String directoryName = "FileUtilsTest-testRecursiveDelete"; File test = new File(directoryName); String path = test.getAbsolutePath(); File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles(); int fileCountBefore = filesBefore.length; ... |
CachingUUIDFactory { public UUID createUuidFromBits(final long mostSigBits, final long leastSigBits) { UUID candidate = new UUID(mostSigBits, leastSigBits); return cacheIfNecessary(candidate); } UUID createUuidFromString(final String name); UUID createUuidFromBits(final long mostSigBits, final long leastSigBits); } | @Test public void testUuidFromBits() { UUID first = _factory.createUuidFromBits(0L,0L); UUID second = _factory.createUuidFromBits(0L,0L); assertSame("UUIDFactory should return the same object", first, second); } |
ByteBufferInputStream extends InputStream { @Override public int read() throws IOException { if (_buffer.hasRemaining()) { return _buffer.get() & 0xFF; } return -1; } ByteBufferInputStream(ByteBuffer buffer); @Override int read(); @Override int read(byte[] b, int off, int len); @Override void mark(int readlimit); @Over... | @Test public void testRead() throws IOException { for (int i = 0; i < _data.length; i++) { assertEquals("Unexpected byte at position " + i, (long) _data[i], (long) _inputStream.read()); } assertEquals("EOF not reached", (long) -1, (long) _inputStream.read()); }
@Test public void testReadByteArray() throws IOException {... |
RollingPolicyDecorator implements RollingPolicy { @Override public String getActiveFileName() { return _decorated.getActiveFileName(); } RollingPolicyDecorator(RollingPolicyBase decorated, RolloverListener listener, ScheduledExecutorService executorService); @Override void rollover(); @Override String getActiveFileName... | @Test public void testGetActiveFileName() { _policy.getActiveFileName(); verify(_delegate).getActiveFileName(); } |
ByteBufferInputStream extends InputStream { @Override public long skip(long n) throws IOException { _buffer.position(_buffer.position()+(int)n); return n; } ByteBufferInputStream(ByteBuffer buffer); @Override int read(); @Override int read(byte[] b, int off, int len); @Override void mark(int readlimit); @Override void ... | @Test public void testSkip() throws IOException { _inputStream.skip(3); byte[] readBytes = new byte[_data.length - 3]; int length = _inputStream.read(readBytes); byte[] expected = new byte[_data.length - 3]; System.arraycopy(_data, 3, expected, 0, _data.length - 3); assertTrue("Unexpected data", Arrays.equals(expected,... |
ByteBufferInputStream extends InputStream { @Override public int available() throws IOException { return _buffer.remaining(); } ByteBufferInputStream(ByteBuffer buffer); @Override int read(); @Override int read(byte[] b, int off, int len); @Override void mark(int readlimit); @Override void reset(); @Override boolean ma... | @Test public void testAvailable() throws IOException { int available = _inputStream.available(); assertEquals("Unexpected number of available bytes", (long) _data.length, (long) available); byte[] readBytes = new byte[_data.length]; _inputStream.read(readBytes); available = _inputStream.available(); assertEquals("Unexp... |
ByteBufferInputStream extends InputStream { @Override public boolean markSupported() { return true; } ByteBufferInputStream(ByteBuffer buffer); @Override int read(); @Override int read(byte[] b, int off, int len); @Override void mark(int readlimit); @Override void reset(); @Override boolean markSupported(); @Override l... | @Test public void testMarkSupported() throws IOException { assertTrue("Unexpected mark supported", _inputStream.markSupported()); } |
AMQPProtocolVersionWrapper { public AMQPProtocolVersionWrapper(Protocol amqpProtocol) { if (!amqpProtocol.isAMQP()) { throw new IllegalArgumentException("Protocol must be of type " + Protocol.ProtocolType.AMQP); } final String[] parts = amqpProtocol.name().split(DELIMITER); for (int i = 0; i < parts.length; i++) { swit... | @Test public void testAMQPProtocolVersionWrapper() throws Exception { final AMQPProtocolVersionWrapper wrapper0_8 = new AMQPProtocolVersionWrapper(Protocol.AMQP_0_8); assertEquals((long) 0, (long) wrapper0_8.getMajor()); assertEquals((long) 8, (long) wrapper0_8.getMinor()); assertEquals((long) 0, (long) wrapper0_8.getP... |
AMQPProtocolVersionWrapper { public Protocol getProtocol() { return Protocol.valueOf(this.toString()); } AMQPProtocolVersionWrapper(Protocol amqpProtocol); int getMajor(); int getMinor(); int getPatch(); Protocol getProtocol(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); ... | @Test public void testAMQPProtocolVersionWrapperGetProtocol() throws Exception { for (final Protocol protocol : Protocol.values()) { if (protocol.isAMQP()) { assertEquals(protocol, new AMQPProtocolVersionWrapper(protocol).getProtocol()); } } } |
ProtocolEngineCreatorComparator implements Comparator<ProtocolEngineCreator> { @Override public int compare(ProtocolEngineCreator pec1, ProtocolEngineCreator pec2) { final AMQPProtocolVersionWrapper v1 = new AMQPProtocolVersionWrapper(pec1.getVersion()); final AMQPProtocolVersionWrapper v2 = new AMQPProtocolVersionWrap... | @Test public void testProtocolEngineCreatorComparator() throws Exception { final ProtocolEngineCreatorComparator comparator = new ProtocolEngineCreatorComparator(); final ProtocolEngineCreator amqp_0_8 = createAMQPProtocolEngineCreatorMock(Protocol.AMQP_0_8); final ProtocolEngineCreator amqp_0_9 = createAMQPProtocolEng... |
StandardQueueEntryList extends OrderedQueueEntryList { @Override public QueueEntry getLeastSignificantOldestEntry() { return getOldestEntry(); } StandardQueueEntryList(final StandardQueue<?> queue, QueueStatistics queueStatistics); @Override QueueEntry getLeastSignificantOldestEntry(); } | @Test public void testGetLesserOldestEntry() { StandardQueueEntryList queueEntryList = new StandardQueueEntryList(_testQueue, _testQueue.getQueueStatistics()); QueueEntry entry1 = queueEntryList.add(createServerMessage(1), null); assertEquals("Unexpected last message", entry1, queueEntryList.getLeastSignificantOldestEn... |
SortedQueueEntryList extends AbstractQueueEntryList { @Override public QueueEntryIterator iterator() { return new QueueEntryIteratorImpl(_head); } SortedQueueEntryList(final SortedQueueImpl queue, final QueueStatistics queueStatistics); @Override SortedQueueImpl getQueue(); @Override SortedQueueEntry add(final ServerMe... | @Override @Test public void testIterator() throws Exception { super.testIterator(); final QueueEntryIterator iter = getTestList().iterator(); int count = 0; while(iter.advance()) { final Object expected = keysSorted[count++]; assertEquals("Sorted queue entry value does not match sorted key array", expected, getSortedKe... |
SortedQueueEntryList extends AbstractQueueEntryList { @Override public QueueEntry getLeastSignificantOldestEntry() { return getOldestEntry(); } SortedQueueEntryList(final SortedQueueImpl queue, final QueueStatistics queueStatistics); @Override SortedQueueImpl getQueue(); @Override SortedQueueEntry add(final ServerMessa... | @Test public void testGetLeastSignificantOldestEntry() { SortedQueueEntryList list = new SortedQueueEntryList(_testQueue, _testQueue.getQueueStatistics()); SortedQueueEntry entry1 = list.add(generateTestMessage(1, "B"), null); assertEquals("Unexpected last entry", entry1, list.getLeastSignificantOldestEntry()); list.ad... |
RollingPolicyDecorator implements RollingPolicy { @Override public CompressionMode getCompressionMode() { return _decorated.getCompressionMode(); } RollingPolicyDecorator(RollingPolicyBase decorated, RolloverListener listener, ScheduledExecutorService executorService); @Override void rollover(); @Override String getAct... | @Test public void testGetCompressionMode() { _policy.getCompressionMode(); verify(_delegate).getCompressionMode(); } |
ProducerFlowControlOverflowPolicyHandler implements OverflowPolicyHandler { @Override public void checkOverflow(final QueueEntry newlyEnqueued) { _handler.checkOverflow(newlyEnqueued); } ProducerFlowControlOverflowPolicyHandler(Queue<?> queue, EventLogger eventLogger); @Override void checkOverflow(final QueueEntry newl... | @Test public void testCheckOverflowBlocksSessionWhenOverfullBytes() throws Exception { AMQPSession<?, ?> session = mock(AMQPSession.class); when(_queue.getQueueDepthBytes()).thenReturn(11L); when(_queue.getMaximumQueueDepthBytes()).thenReturn(10L); checkOverflow(session); verify(session, times(1)).block(_queue); LogMes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.