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(); @Override Object[] getArgumentArray(); @Override String getFormattedMessage(); @Override String getLoggerName(); @Override LoggerContextVO getLoggerContextVO(); @Override IThrowableProxy getThrowableProxy(); @Override StackTraceElement[] getCallerData(); @Override boolean hasCallerData(); @Override Marker getMarker(); @Override Map<String, String> getMDCPropertyMap(); @Deprecated @Override Map<String, String> getMdc(); @Override long getTimeStamp(); @Override void prepareForDeferredProcessing(); }
@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(); @Override byte[] readBin128(); @Override byte[] readBytes(int howManyBytes); @Override double readDouble(); @Override float readFloat(); @Override short readInt16(); @Override int readInt32(); @Override byte readInt8(); @Override byte[] readRemainingBytes(); @Override long readInt64(); }
@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(); Cache<Binary, String> cache = CacheBuilder.newBuilder().maximumSize(2).build(); try { BBDecoder.setStringCache(cache); String decodedString1 = decoder.readStr8(); String decodedString2 = decoder.readStr8(); assertThat(testString, is(equalTo(decodedString1))); assertThat(testString, is(equalTo(decodedString2))); assertSame(decodedString1, decodedString2); } finally { cache.cleanUp(); BBDecoder.setStringCache(original); } }
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 UnsignedInteger deliveryId); @Override UnsettledDelivery getDelivery(final UnsignedInteger deliveryId); @Override void removeDeliveriesForLinkEndpoint(final LinkEndpoint<?, ?> linkEndpoint); @Override UnsignedInteger getDeliveryId(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); @Override int size(); }
@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.ZERO), is(equalTo(expected))); }
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(); ByteBuffer buffer(); @Override int position(); ByteBuffer underlyingBuffer(); @Override void writeUint8(short b); @Override void writeUint16(int s); @Override void writeUint32(long i); @Override void writeUint64(long l); @Override int beginSize8(); @Override void endSize8(int pos); @Override int beginSize16(); @Override void endSize16(int pos); @Override int beginSize32(); @Override void endSize32(int pos); @Override void writeDouble(double aDouble); @Override void writeInt16(short aShort); @Override void writeInt32(int anInt); @Override void writeInt64(long aLong); @Override void writeInt8(byte aByte); @Override void writeBin128(byte[] byteArray); void writeBin128(UUID id); @Override void writeFloat(float aFloat); }
@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) buf.getInt(4)); }
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 for default exchange"); return; } Exchange<?> exchange = getExchange(session, method.getExchange(), false); if(exchange == null) { exception(session, method, ExecutionErrorCode.NOT_FOUND, "No such exchange '" + method.getExchange() + "'"); } else { if (method.getIfUnused() && exchange.hasBindings()) { exception(session, method, ExecutionErrorCode.PRECONDITION_FAILED, "Exchange has bindings"); } else { try { exchange.delete(); } catch (MessageDestinationIsAlternateException e) { exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Exchange in use as an alternate binding destination"); } catch (RequiredExchangeException e) { exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Exchange '"+method.getExchange()+"' cannot be deleted"); } catch (AccessControlException e) { exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); } } } } ServerSessionDelegate(); @Override void command(ServerSession session, Method method); @Override void messageAccept(ServerSession session, MessageAccept method); @Override void messageReject(ServerSession session, MessageReject method); @Override void messageRelease(ServerSession session, MessageRelease method); @Override void messageAcquire(ServerSession session, MessageAcquire method); @Override void messageResume(ServerSession session, MessageResume method); @Override void messageSubscribe(ServerSession session, MessageSubscribe method); @Override void messageTransfer(ServerSession ssn, final MessageTransfer xfr); @Override void messageCancel(ServerSession session, MessageCancel method); @Override void messageFlush(ServerSession session, MessageFlush method); @Override void txSelect(ServerSession session, TxSelect method); @Override void txCommit(ServerSession session, TxCommit method); @Override void txRollback(ServerSession session, TxRollback method); @Override void dtxSelect(ServerSession session, DtxSelect method); @Override void dtxStart(ServerSession session, DtxStart method); @Override void dtxEnd(ServerSession session, DtxEnd method); @Override void dtxCommit(ServerSession session, DtxCommit method); @Override void dtxForget(ServerSession session, DtxForget method); @Override void dtxGetTimeout(ServerSession session, DtxGetTimeout method); @Override void dtxPrepare(ServerSession session, DtxPrepare method); @Override void dtxRecover(ServerSession session, DtxRecover method); @Override void dtxRollback(ServerSession session, DtxRollback method); @Override void dtxSetTimeout(ServerSession session, DtxSetTimeout method); @Override void executionSync(final ServerSession ssn, final ExecutionSync sync); @Override void exchangeDeclare(ServerSession session, ExchangeDeclare method); @Override void exchangeDelete(ServerSession session, ExchangeDelete method); @Override void exchangeQuery(ServerSession session, ExchangeQuery method); @Override void exchangeBind(ServerSession session, ExchangeBind method); @Override void exchangeUnbind(ServerSession session, ExchangeUnbind method); @Override void exchangeBound(ServerSession session, ExchangeBound method); @Override void queueDeclare(ServerSession session, final QueueDeclare method); @Override void queueDelete(ServerSession session, QueueDelete method); @Override void queuePurge(ServerSession session, QueuePurge method); @Override void queueQuery(ServerSession session, QueueQuery method); @Override void messageSetFlowMode(ServerSession session, MessageSetFlowMode sfm); @Override void messageStop(ServerSession session, MessageStop stop); @Override void messageFlow(ServerSession session, MessageFlow flow); void closed(ServerSession session); void detached(ServerSession session); @Override void init(ServerSession ssn, ProtocolHeader hdr); @Override void control(ServerSession ssn, Method method); void command(ServerSession ssn, Method method, boolean processed); @Override void error(ServerSession ssn, ProtocolError error); @Override void handle(ServerSession ssn, Method method); @Override void sessionRequestTimeout(ServerSession ssn, SessionRequestTimeout t); @Override void sessionAttached(ServerSession ssn, SessionAttached atc); @Override void sessionTimeout(ServerSession ssn, SessionTimeout t); @Override void sessionCompleted(ServerSession ssn, SessionCompleted cmp); @Override void sessionKnownCompleted(ServerSession ssn, SessionKnownCompleted kcmp); @Override void sessionFlush(ServerSession ssn, SessionFlush flush); @Override void sessionCommandPoint(ServerSession ssn, SessionCommandPoint scp); @Override void executionResult(ServerSession ssn, ExecutionResult result); @Override void executionException(ServerSession ssn, ExecutionException exc); }
@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 ExchangeDelete(getTestName(), Option.IF_UNUSED); _delegate.exchangeDelete(_session, method); verify(_session).invoke(argThat((ArgumentMatcher<ExecutionException>) exception -> exception.getErrorCode() == ExecutionErrorCode.PRECONDITION_FAILED && "Exchange has bindings".equals( exception.getDescription()))); } @Test public void testExchangeDeleteWhenIfUsedIsSetAndExchangeHasNoBinding() throws Exception { Exchange<?> exchange = mock(Exchange.class); when(exchange.hasBindings()).thenReturn(false); doReturn(exchange).when(_host).getAttainedMessageDestination(eq(getTestName()), anyBoolean()); final ExchangeDelete method = new ExchangeDelete(getTestName(), Option.IF_UNUSED); _delegate.exchangeDelete(_session, method); verify(exchange).delete(); }
MessageTransferMessageMutator implements ServerMessageMutator<MessageTransferMessage> { @Override public void setPriority(final byte priority) { if (_deliveryProperties == null) { _deliveryProperties = new DeliveryProperties(); } _deliveryProperties.setPriority(MessageDeliveryPriority.get(priority)); } MessageTransferMessageMutator(final MessageTransferMessage message, final MessageStore messageStore); @Override void setPriority(final byte priority); @Override byte getPriority(); @Override MessageTransferMessage create(); }
@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.getValue(); } MessageTransferMessageMutator(final MessageTransferMessage message, final MessageStore messageStore); @Override void setPriority(final byte priority); @Override byte getPriority(); @Override MessageTransferMessage create(); }
@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(), _message.getArrivalTime()); final QpidByteBuffer content = _message.getContent(); final MessageHandle<MessageMetaData_0_10> addedMessage = _messageStore.addMessage(messageMetaData); if (content != null) { addedMessage.addContent(content); } return new MessageTransferMessage(addedMessage.allContentAdded(), _message.getConnectionReference()); } MessageTransferMessageMutator(final MessageTransferMessage message, final MessageStore messageStore); @Override void setPriority(final byte priority); @Override byte getPriority(); @Override MessageTransferMessage create(); }
@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_CONTENT_TYPE))); assertThat(newMessage.getMessageHeader().getHeader(TEST_HEADER_NAME), is(equalTo(TEST_HEADER_VALUE))); QpidByteBuffer content = newMessage.getContent(); final byte[] bytes = new byte[content.remaining()]; content.copyTo(bytes); assertThat(new String(bytes, UTF_8), is(equalTo(TEST_CONTENT))); }
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 = fileBasedSettings.getStorePath(); if (storePath != null) { LOGGER.debug("Deleting store : {}", storePath); File configFile = new File(storePath); if (!FileUtils.delete(configFile, true)) { LOGGER.info("Failed to delete the store at location : {}", storePath); } } } @Override Connection getConnection(); @Override void onDelete(ConfiguredObject parent); @Override String getStoreLocation(); @Override File getStoreLocationAsFile(); }
@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(DerbyVirtualHost.class); when(mockVH.getStorePath()).thenReturn(_storeLocation); getStore().onDelete(mockVH); assertFalse("Store exists at " + _storeLocation, location.exists()); }
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) { config.setUsername(username); config.setPassword(password); } Map<String, String> attributes = new HashMap<>(providerAttributes); attributes.putIfAbsent(MIN_CONNECTIONS_PER_PARTITION, String.valueOf(DEFAULT_MIN_CONNECTIONS_PER_PARTITION)); attributes.putIfAbsent(MAX_CONNECTIONS_PER_PARTITION, String.valueOf(DEFAULT_MAX_CONNECTIONS_PER_PARTITION)); attributes.putIfAbsent(PARTITION_COUNT, String.valueOf(DEFAULT_PARTITION_COUNT)); Map<String, String> propertiesMap = attributes.entrySet() .stream() .collect(Collectors.toMap(p -> p.getKey().substring(JDBCSTORE_PREFIX.length()), Map.Entry::getValue)); Properties properties = new Properties(); properties.putAll(propertiesMap); try { config.setProperties(properties); } catch (Exception e) { throw new IllegalConfigurationException("Unexpected exception on applying BoneCP configuration", e); } return config; } BoneCPConnectionProvider(String connectionUrl, String username, String password, Map<String, String> providerAttributes); @Override Connection getConnection(); @Override void close(); static final int DEFAULT_MIN_CONNECTIONS_PER_PARTITION; static final int DEFAULT_MAX_CONNECTIONS_PER_PARTITION; static final int DEFAULT_PARTITION_COUNT; }
@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"); attributes.put("qpid.jdbcstore.bonecp.logStatementsEnabled", "true"); attributes.put("qpid.jdbcstore.bonecp.partitionCount", "12"); String connectionUrl = "jdbc:mariadb: String username = "usr"; String password = "pwd"; BoneCPConfig config = BoneCPConnectionProvider.createBoneCPConfig(connectionUrl, username, password, attributes); assertEquals(connectionUrl, config.getJdbcUrl()); assertEquals(username, config.getUsername()); assertEquals(password, config.getPassword()); assertEquals("Unexpected idleMaxAgeInMinutes", 123, config.getIdleMaxAgeInMinutes()); assertEquals("Unexpected connectionTimeout", 1234, config.getConnectionTimeoutInMs()); assertEquals("Unexpected connectionTestStatement", "select 1", config.getConnectionTestStatement()); assertEquals("Unexpected logStatementsEnabled", true, config.isLogStatementsEnabled()); assertEquals("Unexpected maxConnectionsPerPartition", DEFAULT_MAX_CONNECTIONS_PER_PARTITION, config.getMaxConnectionsPerPartition()); assertEquals("Unexpected minConnectionsPerPartition", DEFAULT_MIN_CONNECTIONS_PER_PARTITION, config.getMinConnectionsPerPartition()); assertEquals("Unexpected partitionCount", 12, config.getPartitionCount()); }
BoneCPConnectionProviderFactory implements JDBCConnectionProviderFactory { @Override public Set<String> getProviderAttributeNames() { return _supportedAttributes; } BoneCPConnectionProviderFactory(); @Override String getType(); @Override ConnectionProvider getConnectionProvider(String connectionUrl, String username, String password, Map<String, String> providerAttributes); @Override Set<String> getProviderAttributeNames(); }
@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.contains(PARTITION_COUNT)); assertTrue("maxConnectionsPerPartition is not found", supported.contains(MAX_CONNECTIONS_PER_PARTITION)); assertTrue("minConnectionsPerPartition is not found",supported.contains(MIN_CONNECTIONS_PER_PARTITION)); }
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("testGroupProvider"); when(groupProvider.getModel()).thenReturn(BrokerModel.getInstance()); Group group = mock(Group.class); when(group.getCategoryClass()).thenReturn(Group.class); when(group.getParent()).thenReturn(groupProvider); when(group.getAttribute(Group.NAME)).thenReturn("test"); when(group.getName()).thenReturn("test"); assertCreateAuthorization(group, LegacyOperation.CREATE, ObjectType.GROUP, new ObjectProperties("test")); } @Test public void testAuthoriseCreateGroupMember() { Group group = mock(Group.class); when(group.getCategoryClass()).thenReturn(Group.class); when(group.getAttribute(Group.NAME)).thenReturn("testGroup"); when(group.getName()).thenReturn("testGroup"); when(group.getModel()).thenReturn(BrokerModel.getInstance()); GroupMember groupMember = mock(GroupMember.class); when(groupMember.getCategoryClass()).thenReturn(GroupMember.class); when(groupMember.getParent()).thenReturn(group); when(groupMember.getAttribute(Group.NAME)).thenReturn("test"); when(groupMember.getName()).thenReturn("test"); assertCreateAuthorization(groupMember, LegacyOperation.UPDATE, ObjectType.GROUP, new ObjectProperties("test")); } @Test public void testAuthoriseCreateUser() { AuthenticationProvider authenticationProvider = mock(AuthenticationProvider.class); when(authenticationProvider.getCategoryClass()).thenReturn(AuthenticationProvider.class); when(authenticationProvider.getAttribute(AuthenticationProvider.NAME)).thenReturn("testAuthenticationProvider"); when(authenticationProvider.getModel()).thenReturn(BrokerModel.getInstance()); User user = mock(User.class); when(user.getCategoryClass()).thenReturn(User.class); when(user.getAttribute(User.NAME)).thenReturn("test"); when(user.getName()).thenReturn("test"); when(user.getParent()).thenReturn(authenticationProvider); when(user.getModel()).thenReturn(BrokerModel.getInstance()); assertCreateAuthorization(user, LegacyOperation.CREATE, ObjectType.USER, new ObjectProperties("test")); } @Test public void testAuthoriseBrokerLogInclusionRuleOperations() { BrokerLogger bl = mock(BrokerLogger.class); when(bl.getName()).thenReturn("LOGGER"); when(bl.getCategoryClass()).thenReturn(BrokerLogger.class); when(bl.getParent()).thenReturn(_broker); when(bl.getAttribute(ConfiguredObject.CREATED_BY)).thenReturn(TEST_USER); BrokerLogInclusionRule mock = mock(BrokerLogInclusionRule.class); when(mock.getName()).thenReturn("TEST"); when(mock.getCategoryClass()).thenReturn(BrokerLogInclusionRule.class); when(mock.getParent()).thenReturn(bl); when(mock.getModel()).thenReturn(BrokerModel.getInstance()); when(mock.getAttribute(ConfiguredObject.CREATED_BY)).thenReturn(TEST_USER); assertBrokerChildCreateAuthorization(mock); when(mock.getName()).thenReturn("test"); assertBrokerChildUpdateAuthorization(mock); assertBrokerChildDeleteAuthorization(mock); }
DeliveryRegistryImpl implements DeliveryRegistry { @Override public void removeDeliveriesForLinkEndpoint(final LinkEndpoint<?, ?> linkEndpoint) { Iterator<UnsettledDelivery> iterator = _deliveries.values().iterator(); while (iterator.hasNext()) { UnsettledDelivery unsettledDelivery = iterator.next(); if (unsettledDelivery.getLinkEndpoint() == linkEndpoint) { iterator.remove(); _deliveryIds.remove(unsettledDelivery); } } } @Override void addDelivery(final UnsignedInteger deliveryId, final UnsettledDelivery unsettledDelivery); @Override void removeDelivery(final UnsignedInteger deliveryId); @Override UnsettledDelivery getDelivery(final UnsignedInteger deliveryId); @Override void removeDeliveriesForLinkEndpoint(final LinkEndpoint<?, ?> linkEndpoint); @Override UnsignedInteger getDeliveryId(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); @Override int size(); }
@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(LinkEndpoint.class))); assertThat(_registry.size(), is(equalTo(3))); _registry.removeDeliveriesForLinkEndpoint(_unsettledDelivery.getLinkEndpoint()); assertThat(_registry.size(), is(equalTo(1))); }
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, getACLObjectTypeManagingConfiguredObjectOfCategory(categoryClass), createObjectPropertiesForMethod(configuredObject, methodName)); if (invokeResult == Result.ALLOWED) { return invokeResult; } String createdBy = configuredObject instanceof ConfiguredObject<?> ? (String) ((ConfiguredObject) configuredObject).getAttribute(ConfiguredObject.CREATED_BY) : null; final ObjectProperties properties = new ObjectProperties(); if (createdBy != null) { properties.put(ObjectProperties.Property.CREATED_BY, createdBy); } if(categoryClass == Queue.class) { Queue queue = (Queue) configuredObject; if("clearQueue".equals(methodName)) { setQueueProperties(queue, properties); return _accessControl.authorise(PURGE, QUEUE, properties); } else if(QUEUE_UPDATE_METHODS.contains(methodName)) { VirtualHost virtualHost = queue.getVirtualHost(); final String virtualHostName = virtualHost.getName(); properties.setName(methodName); properties.put(ObjectProperties.Property.COMPONENT, buildHierarchicalCategoryName(queue, virtualHost)); properties.put(ObjectProperties.Property.VIRTUALHOST_NAME, virtualHostName); return _accessControl.authorise(LegacyOperation.UPDATE, METHOD, properties); } } else if ((categoryClass == BrokerLogger.class || categoryClass == VirtualHostLogger.class) && LOG_ACCESS_METHOD_NAMES.contains(methodName)) { if (categoryClass != BrokerLogger.class) { properties.setName(((ConfiguredObject<?>) configuredObject).getParent().getName()); } return _accessControl.authorise(ACCESS_LOGS, categoryClass == BrokerLogger.class ? ObjectType.BROKER : ObjectType.VIRTUALHOST, properties); } else if(categoryClass == Broker.class && "initiateShutdown".equals(methodName)) { _accessControl.authorise(LegacyOperation.SHUTDOWN, ObjectType.BROKER, properties); } else if (categoryClass == Exchange.class) { final ObjectProperties props = createObjectPropertiesForExchangeBind(arguments, configuredObject); if (createdBy != null) { props.put(ObjectProperties.Property.CREATED_BY, createdBy); } if ("bind".equals(methodName)) { return _accessControl.authorise(BIND, EXCHANGE, props); } else if ("unbind".equals(methodName)) { return _accessControl.authorise(UNBIND, EXCHANGE, props); } } return invokeResult; } LegacyAccessControlAdapter(final LegacyAccessControl accessControl, final Model model); }
@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.ALLOWED); ObjectProperties properties = new ObjectProperties("deleteMessages"); properties.put(ObjectProperties.Property.COMPONENT, "VirtualHost.Queue"); properties.put(ObjectProperties.Property.VIRTUALHOST_NAME, TEST_VIRTUAL_HOST); Queue queue = mock(Queue.class); when(queue.getParent()).thenReturn(_virtualHost); when(queue.getVirtualHost()).thenReturn(_virtualHost); when(queue.getModel()).thenReturn(_model); when(queue.getAttribute(Queue.NAME)).thenReturn(TEST_QUEUE); when(queue.getCategoryClass()).thenReturn(Queue.class); Result result = _adapter.authoriseMethod(queue, "deleteMessages", Collections.emptyMap()); assertEquals("Unexpected authorise result", Result.ALLOWED, result); verify(_accessControl).authorise(eq(LegacyOperation.UPDATE), eq(ObjectType.METHOD), eq(properties)); }
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.getAuthenticatedPrincipalConnectionCount()).thenReturn(2); final ConnectionPrincipalLimitRule rule = new ConnectionPrincipalLimitRule(2); assertThat(rule.matches(_subject), is(true)); } @Test public void frequencyBelowLimit() { when(_connection.getAuthenticatedPrincipalConnectionCount()).thenReturn(1); final ConnectionPrincipalLimitRule rule = new ConnectionPrincipalLimitRule(2); assertThat(rule.matches(_subject), is(true)); }
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(_connection.getAuthenticatedPrincipalConnectionFrequency()).thenReturn(2); final ConnectionPrincipalFrequencyLimitRule rule = new ConnectionPrincipalFrequencyLimitRule(2); assertThat(rule.matches(_subject), is(true)); } @Test public void frequencyBelowLimit() { when(_connection.getAuthenticatedPrincipalConnectionFrequency()).thenReturn(1); final ConnectionPrincipalFrequencyLimitRule rule = new ConnectionPrincipalFrequencyLimitRule(2); assertThat(rule.matches(_subject), is(true)); }
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 UnsettledDelivery unsettledDelivery); @Override void removeDelivery(final UnsignedInteger deliveryId); @Override UnsettledDelivery getDelivery(final UnsignedInteger deliveryId); @Override void removeDeliveriesForLinkEndpoint(final LinkEndpoint<?, ?> linkEndpoint); @Override UnsignedInteger getDeliveryId(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); @Override int size(); }
@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(deliveryId, is(equalTo(DELIVERY_ID))); }
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.getPrincipals().size() == 0) { return Result.DEFER; } if(LOGGER.isDebugEnabled()) { LOGGER.debug("Checking " + operation + " " + objectType ); } try { return _ruleSet.check(subject, operation, objectType, properties); } catch(Exception e) { LOGGER.error("Unable to check " + operation + " " + objectType , e); return Result.DENIED; } } RuleBasedAccessControl(RuleSet rs, final Model model); @Override Result getDefault(); @Override CachingSecurityToken newToken(); @Override CachingSecurityToken newToken(final Subject subject); @Override Result authorise(LegacyOperation operation, ObjectType objectType, ObjectProperties properties); @Override Result authorise(final CachingSecurityToken token, final Operation operation, final PermissionedObject configuredObject); @Override Result authorise(final CachingSecurityToken token, final Operation operation, final PermissionedObject configuredObject, final Map<String, Object> arguments); }
@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(TestPrincipalUtils.createTestSubject("user1"), new PrivilegedAction<Object>() { @Override public Object run() { final Result result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); assertEquals(Result.ALLOWED, result); return null; } }); } @Test public void testCatchAllRuleDeniesUnrecognisedUsername() { setUpGroupAccessControl(); Subject.doAs(TestPrincipalUtils.createTestSubject("unknown", "unkgroup1", "unkgroup2"), new PrivilegedAction<Object>() { @Override public Object run() { assertEquals("Expecting zero messages before test", (long) 0, (long) _messageLogger.getLogMessages().size()); final Result result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); assertEquals(Result.DENIED, result); assertEquals("Expecting one message before test", (long) 1, (long) _messageLogger.getLogMessages().size()); assertTrue("Logged message does not contain expected string", _messageLogger.messageContains(0, "ACL-1002")); return null; } }); } @Test public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnAllComponents() { final RuleSetCreator rs = new RuleSetCreator(); rs.addRule(1, "user4", RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.METHOD, new ObjectProperties(ObjectProperties.WILD_CARD)); configureAccessControl(rs.createRuleSet(mock(EventLoggerProvider.class))); Subject.doAs(TestPrincipalUtils.createTestSubject("user4"), new PrivilegedAction<Object>() { @Override public Object run() { ObjectProperties actionProperties = new ObjectProperties("getName"); actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); final Result result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, actionProperties); assertEquals(Result.ALLOWED, result); return null; } }); } @Test public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnSpecifiedComponent() { final RuleSetCreator rs = new RuleSetCreator(); ObjectProperties ruleProperties = new ObjectProperties(ObjectProperties.WILD_CARD); ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); rs.addRule(1, "user5", RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.METHOD, ruleProperties); configureAccessControl(rs.createRuleSet(mock(EventLoggerProvider.class))); Subject.doAs(TestPrincipalUtils.createTestSubject("user5"), new PrivilegedAction<Object>() { @Override public Object run() { ObjectProperties actionProperties = new ObjectProperties("getName"); actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); Result result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, actionProperties); assertEquals(Result.ALLOWED, result); actionProperties.put(ObjectProperties.Property.COMPONENT, "Test2"); result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, actionProperties); assertEquals(Result.DEFER, result); return null; } }); } @Test public void testAccess() throws Exception { final Subject subject = TestPrincipalUtils.createTestSubject("user1"); final String testVirtualHost = getTestName(); final InetAddress inetAddress = InetAddress.getLocalHost(); final InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 1); AMQPConnection connectionModel = mock(AMQPConnection.class); when(connectionModel.getRemoteSocketAddress()).thenReturn(inetSocketAddress); subject.getPrincipals().add(new ConnectionPrincipal(connectionModel)); Subject.doAs(subject, new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { RuleSet mockRuleSet = mock(RuleSet.class); RuleBasedAccessControl accessControl = new RuleBasedAccessControl(mockRuleSet, BrokerModel.getInstance()); ObjectProperties properties = new ObjectProperties(testVirtualHost); accessControl.authorise(LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, properties); verify(mockRuleSet).check(subject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, properties); return null; } }); } @Test public void testAccessIsDeniedIfRuleThrowsException() throws Exception { final Subject subject = TestPrincipalUtils.createTestSubject("user1"); final InetAddress inetAddress = InetAddress.getLocalHost(); final InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 1); AMQPConnection connectionModel = mock(AMQPConnection.class); when(connectionModel.getRemoteSocketAddress()).thenReturn(inetSocketAddress); subject.getPrincipals().add(new ConnectionPrincipal(connectionModel)); Subject.doAs(subject, new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { RuleSet mockRuleSet = mock(RuleSet.class); when(mockRuleSet.check( subject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)).thenThrow(new RuntimeException()); RuleBasedAccessControl accessControl = new RuleBasedAccessControl(mockRuleSet, BrokerModel.getInstance()); Result result = accessControl.authorise(LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); assertEquals(Result.DENIED, result); return null; } }); } @Test public void testAuthoriseAccessMethodWhenSpecifiedAccessOperationsAllowedOnSpecifiedComponent() { final RuleSetCreator rs = new RuleSetCreator(); ObjectProperties ruleProperties = new ObjectProperties("getAttribute"); ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); rs.addRule(1, "user6", RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.METHOD, ruleProperties); configureAccessControl(rs.createRuleSet(mock(EventLoggerProvider.class))); Subject.doAs(TestPrincipalUtils.createTestSubject("user6"), new PrivilegedAction<Object>() { @Override public Object run() { ObjectProperties properties = new ObjectProperties("getAttribute"); properties.put(ObjectProperties.Property.COMPONENT, "Test"); Result result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.ALLOWED, result); properties.put(ObjectProperties.Property.COMPONENT, "Test2"); result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.DEFER, result); properties = new ObjectProperties("getAttribute2"); properties.put(ObjectProperties.Property.COMPONENT, "Test"); result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.DEFER, result); return null; } }); } @Test public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnSpecifiedMethodForAllComponents() { final RuleSetCreator rs = new RuleSetCreator(); rs.addRule(1, "user8", RuleOutcome.ALLOW, LegacyOperation.ALL, ObjectType.METHOD, new ObjectProperties("queryNames")); configureAccessControl(rs.createRuleSet(mock(EventLoggerProvider.class))); Subject.doAs(TestPrincipalUtils.createTestSubject("user8"), new PrivilegedAction<Object>() { @Override public Object run() { ObjectProperties properties = new ObjectProperties(); properties.put(ObjectProperties.Property.COMPONENT, "Test"); properties.put(ObjectProperties.Property.NAME, "queryNames"); Result result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.ALLOWED, result); result = _plugin.authorise(LegacyOperation.UPDATE, ObjectType.METHOD, properties); assertEquals(Result.ALLOWED, result); properties = new ObjectProperties("getAttribute"); properties.put(ObjectProperties.Property.COMPONENT, "Test"); result = _plugin.authorise(LegacyOperation.UPDATE, ObjectType.METHOD, properties); assertEquals(Result.DEFER, result); result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.DEFER, result); return null; } }); } @Test public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnAllMethodsInAllComponents() { final RuleSetCreator rs = new RuleSetCreator(); rs.addRule(1, "user9", RuleOutcome.ALLOW, LegacyOperation.ALL, ObjectType.METHOD, new ObjectProperties()); configureAccessControl(rs.createRuleSet(mock(EventLoggerProvider.class))); Subject.doAs(TestPrincipalUtils.createTestSubject("user9"), new PrivilegedAction<Object>() { @Override public Object run() { ObjectProperties properties = new ObjectProperties("queryNames"); properties.put(ObjectProperties.Property.COMPONENT, "Test"); Result result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.ALLOWED, result); result = _plugin.authorise(LegacyOperation.UPDATE, ObjectType.METHOD, properties); assertEquals(Result.ALLOWED, result); properties = new ObjectProperties("getAttribute"); properties.put(ObjectProperties.Property.COMPONENT, "Test"); result = _plugin.authorise(LegacyOperation.UPDATE, ObjectType.METHOD, properties); assertEquals(Result.ALLOWED, result); result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.ALLOWED, result); return null; } }); } @Test public void testAuthoriseAccessMethodWhenMatchingAccessOperationsAllowedOnSpecifiedComponent() { final RuleSetCreator rs = new RuleSetCreator(); ObjectProperties ruleProperties = new ObjectProperties(); ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); ruleProperties.put(ObjectProperties.Property.NAME, "getAttribute*"); rs.addRule(1, "user9", RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.METHOD, ruleProperties); configureAccessControl(rs.createRuleSet(mock(EventLoggerProvider.class))); Subject.doAs(TestPrincipalUtils.createTestSubject("user9"), new PrivilegedAction<Object>() { @Override public Object run() { ObjectProperties properties = new ObjectProperties("getAttributes"); properties.put(ObjectProperties.Property.COMPONENT, "Test"); Result result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.ALLOWED, result); properties = new ObjectProperties("getAttribute"); properties.put(ObjectProperties.Property.COMPONENT, "Test"); result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.ALLOWED, result); properties = new ObjectProperties("getAttribut"); properties.put(ObjectProperties.Property.COMPONENT, "Test"); result = _plugin.authorise(LegacyOperation.ACCESS, ObjectType.METHOD, properties); assertEquals(Result.DEFER, result); return null; } }); }
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(final UnsignedInteger deliveryId); @Override void removeDeliveriesForLinkEndpoint(final LinkEndpoint<?, ?> linkEndpoint); @Override UnsignedInteger getDeliveryId(final Binary deliveryTag, final LinkEndpoint<?, ?> linkEndpoint); @Override int size(); }
@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 properties); DynamicRule getDynamicRule(); Action getAction(); boolean isAllowed(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); Map<ObjectProperties.Property, String> getAttributes(); }
@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(ObjectProperties.Property.ATTRIBUTES.name(), TEST_ATTRIBUTES); predicates.parse(ObjectProperties.Property.NAME.name(), getTestName()); final AclAction aclAction = new AclAction(operation, objectType, predicates); final Map<ObjectProperties.Property, String> attributes = aclAction.getAttributes(); assertThat(attributes, allOf(aMapWithSize(3), hasEntry(ObjectProperties.Property.FROM_HOSTNAME, TEST_HOSTNAME), hasEntry(ObjectProperties.Property.ATTRIBUTES, TEST_ATTRIBUTES), hasEntry(ObjectProperties.Property.NAME, getTestName()))); }
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 properties); boolean matches(AclAction ruleAction, final Subject subject); LegacyOperation getOperation(); ObjectType getObjectType(); ObjectProperties getProperties(); @Override String toString(); }
@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 public void testMatches_returnsFalseWhenActionsDontMatch() { FirewallRule firewallRule = mock(FirewallRule.class); when(firewallRule.matches(_subject)).thenReturn(true); when(_ruleAction.getDynamicRule()).thenReturn(firewallRule); when(_action.matches(any(Action.class))).thenReturn(false); when(_ruleAction.getDynamicRule()).thenReturn(firewallRule); when(_ruleAction.getAction()).thenReturn(mock(Action.class)); assertFalse(_clientAction.matches(_ruleAction, _subject)); } @Test public void testMatches_returnsTrueWhenActionsAndFirewallRuleMatch() { FirewallRule firewallRule = mock(FirewallRule.class); when(firewallRule.matches(_subject)).thenReturn(true); when(_ruleAction.getDynamicRule()).thenReturn(firewallRule); when(_action.matches(any(Action.class))).thenReturn(true); when(_ruleAction.getDynamicRule()).thenReturn(firewallRule); when(_ruleAction.getAction()).thenReturn(mock(Action.class)); assertTrue(_clientAction.matches(_ruleAction, _subject)); } @Test public void testMatches_ignoresFirewallRuleIfClientAddressIsNull() { FirewallRule firewallRule = new FirewallRule() { @Override protected boolean matches(final InetAddress addressOfClient) { return false; } }; when(_action.matches(any(Action.class))).thenReturn(true); when(_ruleAction.getDynamicRule()).thenReturn(firewallRule); when(_ruleAction.getAction()).thenReturn(mock(Action.class)); assertTrue(_clientAction.matches(_ruleAction, _subject)); } @Test public void testMatchesWhenConnectionLimitBreached() { final ObjectProperties properties = new ObjectProperties("foo"); final AclRulePredicates predicates = new AclRulePredicates(); predicates.parse(ObjectProperties.Property.CONNECTION_LIMIT.name(), "1"); final AclAction ruleAction = new AclAction(LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, predicates); final ClientAction clientAction = new ClientAction(LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, properties); when(_connection.getAuthenticatedPrincipalConnectionCount()).thenReturn(2); boolean matches = clientAction.matches(ruleAction, _subject); assertFalse(matches); }
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, operation, objectType); if (rules == null) { LOGGER.debug("No rules found, returning default result"); return getDefault(); } final boolean ownerRules = rules.stream() .anyMatch(rule -> rule.getIdentity().equalsIgnoreCase(Rule.OWNER)); if (ownerRules) { rules = new LinkedList<>(rules); if (operation == LegacyOperation.CREATE) { rules.removeIf(rule -> rule.getIdentity().equalsIgnoreCase(Rule.OWNER)); } else { final String objectCreator = properties.get(ObjectProperties.Property.CREATED_BY); final Principal principal = AuthenticatedPrincipal.getOptionalAuthenticatedPrincipalFromSubject(subject); if (principal == null || !principal.getName().equalsIgnoreCase(objectCreator)) { rules.removeIf(rule -> rule.getIdentity().equalsIgnoreCase(Rule.OWNER)); } } } for (Rule rule : rules) { LOGGER.debug("Checking against rule: {}", rule); if (action.matches(rule.getAclAction(), subject)) { RuleOutcome ruleOutcome = rule.getRuleOutcome(); LOGGER.debug("Action matches. Result: {}", ruleOutcome); boolean allowed = ruleOutcome.isAllowed(); if(ruleOutcome.isLogged()) { if(allowed) { getEventLogger().message(AccessControlMessages.ALLOWED( action.getOperation().toString(), action.getObjectType().toString(), action.getProperties().toString())); } else { getEventLogger().message(AccessControlMessages.DENIED( action.getOperation().toString(), action.getObjectType().toString(), action.getProperties().toString())); } } return allowed ? Result.ALLOWED : Result.DENIED; } } LOGGER.debug("Deferring result of ACL check"); return Result.DEFER; } RuleSet(final EventLoggerProvider eventLogger, final Collection<Rule> rules, final Result defaultResult); Result check(Subject subject, LegacyOperation operation, ObjectType objectType, ObjectProperties properties); Result getDefault(); List<Rule> getAllRules(); @Override EventLogger getEventLogger(); }
@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(_testSubject, LegacyOperation.CREATE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY)); assertEquals(Result.DENIED, ruleSet.check(_testSubject, LegacyOperation.DELETE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY)); } @Test public void testVirtualHostAccessAllowPermissionWithVirtualHostName() throws Exception { _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH)); RuleSet ruleSet = createRuleSet(); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); assertEquals(Result.DEFER, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); } @Test public void testVirtualHostAccessAllowPermissionWithNameSetToWildCard() throws Exception { _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ObjectProperties.WILD_CARD)); RuleSet ruleSet = createRuleSet(); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); } @Test public void testVirtualHostAccessAllowPermissionWithNoName() throws Exception { _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); RuleSet ruleSet = createRuleSet(); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); } @Test public void testVirtualHostAccessDenyPermissionWithNoName() throws Exception { _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.DENY, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); RuleSet ruleSet = createRuleSet(); assertEquals(Result.DENIED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); assertEquals(Result.DENIED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); } @Test public void testVirtualHostAccessDenyPermissionWithNameSetToWildCard() throws Exception { _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.DENY, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ObjectProperties.WILD_CARD)); RuleSet ruleSet = createRuleSet(); assertEquals(Result.DENIED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); assertEquals(Result.DENIED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); } @Test public void testVirtualHostAccessAllowDenyPermissions() throws Exception { _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.DENY, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH)); _ruleSetCreator.addRule(1, TEST_USER, RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH)); RuleSet ruleSet = createRuleSet(); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); assertEquals(Result.DENIED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); } @Test public void testVirtualHostAccessAllowPermissionWithVirtualHostNameOtherPredicate() throws Exception { ObjectProperties properties = new ObjectProperties(); properties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, properties); RuleSet ruleSet = createRuleSet(); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, properties)); assertEquals(Result.DEFER, ruleSet.check(_testSubject, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); } @Test public void testQueueCreateNamedVirtualHost() throws Exception { _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.ALLOW, LegacyOperation.CREATE, ObjectType.QUEUE, new ObjectProperties(Property.VIRTUALHOST_NAME, ALLOWED_VH)); RuleSet ruleSet = createRuleSet(); ObjectProperties allowedQueueObjectProperties = new ObjectProperties(_queueName); allowedQueueObjectProperties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.CREATE, ObjectType.QUEUE, new ObjectProperties(allowedQueueObjectProperties))); ObjectProperties deniedQueueObjectProperties = new ObjectProperties(_queueName); deniedQueueObjectProperties.put(Property.VIRTUALHOST_NAME, DENIED_VH); assertEquals(Result.DEFER, ruleSet.check(_testSubject, LegacyOperation.CREATE, ObjectType.QUEUE, deniedQueueObjectProperties)); } @Test public void testExchangeCreateNamedVirtualHost() { _ruleSetCreator.addRule(0, TEST_USER, RuleOutcome.ALLOW, LegacyOperation.CREATE, ObjectType.EXCHANGE, new ObjectProperties(Property.VIRTUALHOST_NAME, ALLOWED_VH)); RuleSet ruleSet = createRuleSet(); ObjectProperties allowedExchangeProperties = new ObjectProperties(_exchangeName); allowedExchangeProperties.put(Property.TYPE, _exchangeType); allowedExchangeProperties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.CREATE, ObjectType.EXCHANGE, allowedExchangeProperties)); ObjectProperties deniedExchangeProperties = new ObjectProperties(_exchangeName); deniedExchangeProperties.put(Property.TYPE, _exchangeType); deniedExchangeProperties.put(Property.VIRTUALHOST_NAME, DENIED_VH); assertEquals(Result.DEFER, ruleSet.check(_testSubject, LegacyOperation.CREATE, ObjectType.EXCHANGE, deniedExchangeProperties)); } @Test public void testUserInMultipleGroups() { String allowedGroup = "group1"; String deniedGroup = "group2"; _ruleSetCreator.addRule(1, allowedGroup, RuleOutcome.ALLOW, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); _ruleSetCreator.addRule(2, deniedGroup, RuleOutcome.DENY, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); RuleSet ruleSet = createRuleSet(); Subject subjectInBothGroups = TestPrincipalUtils.createTestSubject("user", allowedGroup, deniedGroup); Subject subjectInDeniedGroupAndOneOther = TestPrincipalUtils.createTestSubject("user", deniedGroup, "some other group"); Subject subjectInAllowedGroupAndOneOther = TestPrincipalUtils.createTestSubject("user", allowedGroup, "some other group"); assertEquals(Result.ALLOWED, ruleSet.check(subjectInBothGroups, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); assertEquals(Result.DENIED, ruleSet.check(subjectInDeniedGroupAndOneOther, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); assertEquals(Result.ALLOWED, ruleSet.check(subjectInAllowedGroupAndOneOther, LegacyOperation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); } @Test public void testUpdatedAllowedAttribute() { final ObjectProperties ruleProperties = new ObjectProperties(); ruleProperties.setAttributeNames(Collections.singleton("attribute1")); _ruleSetCreator.addRule(1, TEST_USER, RuleOutcome.ALLOW, LegacyOperation.UPDATE, ObjectType.VIRTUALHOST, ruleProperties); _ruleSetCreator.addRule(2, TEST_USER, RuleOutcome.DENY, LegacyOperation.UPDATE, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); RuleSet ruleSet = createRuleSet(); final ObjectProperties updateProperties = new ObjectProperties(); assertEquals(Result.DENIED, ruleSet.check(_testSubject, LegacyOperation.UPDATE, ObjectType.VIRTUALHOST, updateProperties)); updateProperties.setAttributeNames(Collections.singleton("attribute2")); assertEquals(Result.DENIED, ruleSet.check(_testSubject, LegacyOperation.UPDATE, ObjectType.VIRTUALHOST, updateProperties)); updateProperties.setAttributeNames(Collections.singleton("attribute1")); assertEquals(Result.ALLOWED, ruleSet.check(_testSubject, LegacyOperation.UPDATE, ObjectType.VIRTUALHOST, updateProperties)); }
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 void setPriority(final byte priority); @Override byte getPriority(); @Override Message_1_0 create(); }
@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(LegacyOperation operation, ObjectType object, String name); Action(LegacyOperation operation, ObjectType object); Action(LegacyOperation operation, ObjectType object, ObjectProperties properties); LegacyOperation getOperation(); ObjectType getObjectType(); ObjectProperties getProperties(); boolean matches(Action a); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }
@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 void setPriority(final byte priority); @Override byte getPriority(); @Override Message_1_0 create(); }
@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 = pattern.matcher(hostname).matches(); if (hostnameMatches) { if(LOGGER.isDebugEnabled()) { LOGGER.debug("Hostname " + hostname + " matches rule " + pattern.toString()); } return true; } } LOGGER.debug("Hostname {} matches no configured hostname patterns", hostname); return false; } HostnameFirewallRule(String... hostnames); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testSingleHostname() throws Exception { String hostnameInRule = "hostnameInRule"; InetAddress addressWithMatchingHostname = mock(InetAddress.class); when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn(hostnameInRule); _HostnameFirewallRule = new HostnameFirewallRule(hostnameInRule); assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); } @Test public void testSingleHostnameWildcard() throws Exception { String hostnameInRule = ".*FOO.*"; InetAddress addressWithMatchingHostname = mock(InetAddress.class); when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn("xxFOOxx"); _HostnameFirewallRule = new HostnameFirewallRule(hostnameInRule); assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); } @Test public void testMultipleHostnames() throws Exception { String[] hostnamesInRule = new String[] {"hostnameInRule1", "hostnameInRule2"}; _HostnameFirewallRule = new HostnameFirewallRule(hostnamesInRule); assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); for (String hostnameInRule : hostnamesInRule) { InetAddress addressWithMatchingHostname = mock(InetAddress.class); when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn(hostnameInRule); assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); } }
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 configured networks", ip); return false; } NetworkFirewallRule(String... networks); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }
@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 testNetMask() throws Exception { String ipAddressInRule = "192.168.23.0/24"; _networkFirewallRule = new NetworkFirewallRule(ipAddressInRule); assertFalse(_networkFirewallRule.matches(InetAddress.getByName("192.168.24.1"))); assertTrue(_networkFirewallRule.matches(InetAddress.getByName("192.168.23.0"))); assertTrue(_networkFirewallRule.matches(InetAddress.getByName("192.168.23.255"))); } @Test public void testWildcard() throws Exception { assertFalse(new NetworkFirewallRule("192.168.*") .matches(InetAddress.getByName("192.169.1.0"))); assertTrue(new NetworkFirewallRule("192.168.*") .matches(InetAddress.getByName("192.168.1.0"))); assertTrue(new NetworkFirewallRule("192.168.*") .matches(InetAddress.getByName("192.168.255.255"))); assertFalse(new NetworkFirewallRule("192.168.1.*") .matches(InetAddress.getByName("192.169.2.0"))); assertTrue(new NetworkFirewallRule("192.168.1.*") .matches(InetAddress.getByName("192.168.1.0"))); assertTrue(new NetworkFirewallRule("192.168.1.*") .matches(InetAddress.getByName("192.168.1.255"))); } @Test public void testMultipleNetworks() throws Exception { String[] ipAddressesInRule = new String[] {OTHER_IP_1, OTHER_IP_2}; _networkFirewallRule = new NetworkFirewallRule(ipAddressesInRule); assertFalse(_networkFirewallRule.matches(_addressNotInRule)); for (String ipAddressInRule : ipAddressesInRule) { assertTrue(_networkFirewallRule.matches(InetAddress.getByName(ipAddressInRule))); } }
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_0> getInputClass(); @Override Class<MessageTransferMessage> getOutputClass(); @Override MessageTransferMessage convert(Message_1_0 serverMsg, NamedAddressSpace addressSpace); @Override void dispose(final MessageTransferMessage message); @Override String getType(); }
@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 MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testAmqpValueWithNullWithMessageAnnotation() throws Exception { final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testAmqpValueWithNullWithObjectMessageAnnotation() throws Exception { final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(OBJECT_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertEquals("Unexpected mime type", "application/java-object-stream", convertedMessage.getMessageHeader().getMimeType()); assertArrayEquals("Unexpected content size", getObjectBytes(null), getBytes(content)); } @Test public void testAmqpValueWithNullWithMapMessageAnnotation() throws Exception { final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(MAP_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType()); assertArrayEquals("Unexpected content size", new MapToJmsMapMessage().toMimeContent(Collections.emptyMap()), getBytes(content)); } @Test public void testAmqpValueWithNullWithBytesMessageAnnotation() throws Exception { final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(BYTE_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/octet-stream", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testAmqpValueWithNullWithStreamMessageAnnotation() throws Exception { final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(STREAM_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testAmqpValueWithNullWithUnknownMessageAnnotation() throws Exception { final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"), (byte) 11)), amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testAmqpValueWithNullWithContentTypeApplicationOctetStream() throws Exception { Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("application/octet-stream")); final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(properties, amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/octet-stream", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testAmqpValueWithNullWithObjectMessageContentType() throws Exception { final Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("application/x-java-serialized-object")); final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(properties, amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/java-object-stream", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) getObjectBytes(null).length, convertedMessage.getSize()); } @Test public void testAmqpValueWithNullWithJmsMapContentType() throws Exception { final Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("jms/map-message")); final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(properties, amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType()); assertArrayEquals("Unexpected content size", new MapToJmsMapMessage().toMimeContent(Collections.emptyMap()), getBytes(content)); } @Test public void testAmqpValueWithNull() throws Exception { final Object expected = null; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testAmqpValueWithString() throws Exception { final String expected = "testContent"; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8)); } @Test public void testAmqpValueWithStringWithTextMessageAnnotation() throws Exception { final String expected = "testContent"; final AmqpValue amqpValue = new AmqpValue(expected); Message_1_0 sourceMessage = createTestMessage(TEXT_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8)); } @Test public void testAmqpValueWithMap() throws Exception { final Map<String, Object> originalMap = new LinkedHashMap<>(); originalMap.put("binaryEntry", new Binary(new byte[]{0x00, (byte) 0xFF})); originalMap.put("intEntry", 42); originalMap.put("nullEntry", null); final AmqpValue amqpValue = new AmqpValue(originalMap); Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); Map<String, Object> convertedMap = new JmsMapMessageToMap().toObject(getBytes(content)); assertEquals("Unexpected size", (long) originalMap.size(), (long) convertedMap.size()); assertArrayEquals("Unexpected binary entry", ((Binary) originalMap.get("binaryEntry")).getArray(), (byte[]) convertedMap.get("binaryEntry")); assertEquals("Unexpected int entry", originalMap.get("intEntry"), convertedMap.get("intEntry")); assertEquals("Unexpected null entry", originalMap.get("nullEntry"), convertedMap.get("nullEntry")); } @Test public void testAmqpValueWithMapContainingMap() throws Exception { final Map<String, Object> originalMap = Collections.singletonMap("testMap", Collections.singletonMap("innerKey", "testValue")); final AmqpValue amqpValue = new AmqpValue(originalMap); Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "amqp/map", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); Map<String, Object> convertedMap = new AmqpMapToMapConverter().toObject(getBytes(content)); assertEquals("Unexpected size", (long) originalMap.size(), (long) convertedMap.size()); assertEquals("Unexpected binary entry", new HashMap((Map<String, Object>) originalMap.get("testMap")), new HashMap((Map<String, Object>) convertedMap.get("testMap"))); } @Test public void testAmqpValueWithMapContainingNonFieldTableCompliantEntries() throws Exception { final AmqpValue amqpValue = new AmqpValue(Collections.<Object, Object>singletonMap(13, 42)); Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection()); try { _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); fail("expected exception not thrown."); } catch (MessageConversionException e) { } } @Test public void testAmqpValueWithList() throws Exception { final List<Object> originalList = new ArrayList<>(); originalList.add(new Binary(new byte[]{0x00, (byte) 0xFF})); originalList.add(42); originalList.add(null); final AmqpValue amqpValue = new AmqpValue(originalList); Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); List<Object> convertedList = new JmsStreamMessageToList().toObject(getBytes(content)); assertEquals("Unexpected size", (long) originalList.size(), (long) convertedList.size()); assertArrayEquals("Unexpected binary item", ((Binary) originalList.get(0)).getArray(), (byte[]) convertedList.get(0)); assertEquals("Unexpected int item", originalList.get(1), convertedList.get(1)); assertEquals("Unexpected null item", originalList.get(2), convertedList.get(2)); } @Test public void testAmqpValueWithListContainingMap() throws Exception { final List<Object> originalList = Collections.singletonList(Collections.singletonMap("testKey", "testValue")); final AmqpValue amqpValue = new AmqpValue(originalList); Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); List<Object> convertedList = new AmqpListToListConverter().toObject(getBytes(content)); assertEquals("Unexpected size", (long) originalList.size(), (long) convertedList.size()); assertEquals("Unexpected map item", new HashMap<String, Object>((Map) originalList.get(0)), new HashMap<String, Object>((Map) convertedList.get(0))); } @Test public void testAmqpValueWithListContainingUnsupportedType() throws Exception { final List<Object> originalList = Collections.singletonList(new Source()); final AmqpValue amqpValue = new AmqpValue(originalList); Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection()); try { _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); fail("expected exception not thrown."); } catch (MessageConversionException e) { } } @Test public void testAmqpValueWithUnsupportedType() throws Exception { final Integer originalValue = 42; final AmqpValue amqpValue = new AmqpValue(originalValue); Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection()); try { _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); fail("expected exception not thrown."); } catch (MessageConversionException e) { } } @Test public void testAmqpSequenceWithSimpleTypes() throws Exception { final List<Integer> expected = new ArrayList<>(); expected.add(37); expected.add(42); final AmqpSequence amqpSequence = new AmqpSequence(expected); Message_1_0 sourceMessage = createTestMessage(amqpSequence.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertEquals("Unexpected content", expected, new JmsStreamMessageToList().toObject(getBytes(content))); } @Test public void testAmqpSequenceWithMap() throws Exception { final List<Object> originalList = Collections.singletonList(Collections.singletonMap("testKey", "testValue")); final AmqpSequence amqpSequence = new AmqpSequence(originalList); Message_1_0 sourceMessage = createTestMessage(amqpSequence.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); List<Object> convertedList = new AmqpListToListConverter().toObject(getBytes(content)); assertEquals("Unexpected size", (long) originalList.size(), (long) convertedList.size()); assertEquals("Unexpected map item", new HashMap<String, Object>((Map) originalList.get(0)), new HashMap<String, Object>((Map) convertedList.get(0))); } @Test public void testAmqpSequenceWithUnsupportedType() throws Exception { final List<Object> originalList = Collections.singletonList(new Source()); final AmqpSequence amqpSequence = new AmqpSequence(originalList); Message_1_0 sourceMessage = createTestMessage(amqpSequence.createEncodingRetainingSection()); try { _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); fail("expected exception not thrown."); } catch (MessageConversionException e) { } } @Test public void testDataWithMapMessageAnnotationAndContentTypeJmsMapMessage() throws Exception { Map<String, Object> originalMap = Collections.singletonMap("testKey", "testValue"); byte[] data = new MapToJmsMapMessage().toMimeContent(originalMap); String expectedMimeType = "jms/map-message"; final Data value = new Data(new Binary(data)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf(expectedMimeType)); Message_1_0 sourceMessage = createTestMessage(properties, MAP_MESSAGE_MESSAGE_ANNOTATION, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", expectedMimeType, convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", data, getBytes(content)); } @Test public void testDataWithMapMessageAnnotationAndContentTypeAmqpMap() throws Exception { Map<String, Object> originalMap = Collections.singletonMap("testKey", "testValue"); byte[] data = new MapToAmqpMapConverter().toMimeContent(originalMap); String expectedMimeType = "amqp/map"; final Data value = new Data(new Binary(data)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf(expectedMimeType)); Message_1_0 sourceMessage = createTestMessage(properties, MAP_MESSAGE_MESSAGE_ANNOTATION, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", expectedMimeType, convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", data, getBytes(content)); } @Test public void testDataWithStreamMessageAnnotationAndContentTypeJmsStreamMessage() throws Exception { List<Object> originalList = Collections.singletonList("testValue"); byte[] data = new ListToJmsStreamMessage().toMimeContent(originalList); String expectedMimeType = "jms/stream-message"; final Data value = new Data(new Binary(data)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf(expectedMimeType)); Message_1_0 sourceMessage = createTestMessage(properties, STREAM_MESSAGE_MESSAGE_ANNOTATION, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", expectedMimeType, convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", data, getBytes(content)); } @Test public void testDataWithStreamMessageAnnotationAndContentTypeAmqpList() throws Exception { List<Object> originalList = Collections.singletonList("testValue"); byte[] data = new ListToAmqpListConverter().toMimeContent(originalList); String expectedMimeType = "amqp/list"; final Data value = new Data(new Binary(data)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf(expectedMimeType)); Message_1_0 sourceMessage = createTestMessage(properties, STREAM_MESSAGE_MESSAGE_ANNOTATION, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", expectedMimeType, convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", data, getBytes(content)); } @Test public void testDataWithContentTypeAmqpMap() throws Exception { Map<String, Object> originalMap = Collections.singletonMap("testKey", "testValue"); byte[] bytes = new MapToAmqpMapConverter().toMimeContent(originalMap); final Data value = new Data(new Binary(bytes)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("amqp/map")); Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "amqp/map", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", bytes, getBytes(content)); } @Test public void testDataWithContentTypeJmsMapMessage() throws Exception { Map<String, Object> originalMap = Collections.singletonMap("testKey", "testValue"); byte[] bytes = new MapToJmsMapMessage().toMimeContent(originalMap); final Data value = new Data(new Binary(bytes)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("jms/map-message")); Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", bytes, getBytes(content)); } @Test public void testDataWithContentTypeAmqpList() throws Exception { List<Object> originalMap = Collections.singletonList("testValue"); byte[] bytes = new ListToAmqpListConverter().toMimeContent(originalMap); final Data value = new Data(new Binary(bytes)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("amqp/list")); Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", bytes, getBytes(content)); } @Test public void testDataWithContentTypeJmsStreamMessage() throws Exception { List<Object> originalMap = Collections.singletonList("testValue"); byte[] bytes = new ListToJmsStreamMessage().toMimeContent(originalMap); final Data value = new Data(new Binary(bytes)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("jms/stream-message")); Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", bytes, getBytes(content)); } @Test public void testDataWithContentTypeJavaSerializedObject() throws Exception { final byte[] expected = getObjectBytes("helloworld".getBytes(UTF_8)); final Data value = new Data(new Binary(expected)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("application/x-java-serialized-object")); Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/java-object-stream", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", expected, getBytes(content)); } @Test public void testDataWithContentTypeJavaObjectStream() throws Exception { final byte[] expected = getObjectBytes("helloworld".getBytes(UTF_8)); final Data value = new Data(new Binary(expected)); Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("application/java-object-stream")); Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/java-object-stream", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", expected, getBytes(content)); } @Test public void testDataWithContentTypeOther() throws Exception { final byte[] expected = "helloworld".getBytes(UTF_8); final Data value = new Data(new Binary(expected)); final Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("application/bin")); Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/octet-stream", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", expected, getBytes(content)); } @Test public void testData() throws Exception { final byte[] expected = getObjectBytes("helloworld".getBytes(UTF_8)); final Data value = new Data(new Binary(expected)); final Message_1_0 sourceMessage = createTestMessage(value.createEncodingRetainingSection()); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/octet-stream", convertedMessage.getMessageHeader().getMimeType()); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertArrayEquals("Unexpected content", expected, getBytes(content)); } @Test public void testNoBodyWithMessageAnnotation() throws Exception { Message_1_0 sourceMessage = createTestMessage(MESSAGE_MESSAGE_ANNOTATION, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testNoBodyWithObjectMessageAnnotation() throws Exception { Message_1_0 sourceMessage = createTestMessage(OBJECT_MESSAGE_MESSAGE_ANNOTATION, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertEquals("Unexpected mime type", "application/java-object-stream", convertedMessage.getMessageHeader().getMimeType()); assertArrayEquals("Unexpected content size", getObjectBytes(null), getBytes(content)); } @Test public void testNoBodyWithMapMessageAnnotation() throws Exception { Message_1_0 sourceMessage = createTestMessage(MAP_MESSAGE_MESSAGE_ANNOTATION, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType()); assertArrayEquals("Unexpected content size", new MapToJmsMapMessage().toMimeContent(Collections.emptyMap()), getBytes(content)); } @Test public void testNoBodyWithBytesMessageAnnotation() throws Exception { Message_1_0 sourceMessage = createTestMessage(BYTE_MESSAGE_MESSAGE_ANNOTATION, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/octet-stream", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testNoBodyWithStreamMessageAnnotation() throws Exception { Message_1_0 sourceMessage = createTestMessage(STREAM_MESSAGE_MESSAGE_ANNOTATION, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testNoBodyWithTextMessageAnnotation() throws Exception { Message_1_0 sourceMessage = createTestMessage(TEXT_MESSAGE_MESSAGE_ANNOTATION, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testNoBodyWithUnknownMessageAnnotation() throws Exception { Message_1_0 sourceMessage = createTestMessage(new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"), (byte) 11)), null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testNoBody() throws Exception { final Message_1_0 sourceMessage = createTestMessage(null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testNoBodyWithContentTypeApplicationOctetStream() throws Exception { Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("application/octet-stream")); final Message_1_0 sourceMessage = createTestMessage(properties, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/octet-stream", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize()); } @Test public void testNoBodyWithObjectMessageContentType() throws Exception { final Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("application/x-java-serialized-object")); final Message_1_0 sourceMessage = createTestMessage(properties, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/java-object-stream", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) getObjectBytes(null).length, convertedMessage.getSize()); } @Test public void testNoBodyWithJmsMapContentType() throws Exception { final Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("jms/map-message")); final Message_1_0 sourceMessage = createTestMessage(properties, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize()); assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType()); assertArrayEquals("Unexpected content size", new MapToJmsMapMessage().toMimeContent(Collections.emptyMap()), getBytes(content)); } @Test public void testMessageAnnotationTakesPrecedenceOverContentType() throws Exception { final Properties properties = new Properties(); properties.setContentType(Symbol.valueOf("application/octet-stream")); final Message_1_0 sourceMessage = createTestMessage(OBJECT_MESSAGE_MESSAGE_ANNOTATION, null); final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class)); assertEquals("Unexpected mime type", "application/java-object-stream", convertedMessage.getMessageHeader().getMimeType()); assertEquals("Unexpected content size", (long) getObjectBytes(null).length, convertedMessage.getSize()); }
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 deliveryAnnotationsSection = null; if (_deliveryAnnotations != null) { deliveryAnnotationsSection = new DeliveryAnnotations(_deliveryAnnotations).createEncodingRetainingSection(); } MessageAnnotationsSection messageAnnotationsSection = null; if (_messageAnnotations != null) { messageAnnotationsSection = new MessageAnnotations(_messageAnnotations).createEncodingRetainingSection(); } PropertiesSection propertiesSection = null; if (_properties != null) { propertiesSection = _properties.createEncodingRetainingSection(); } ApplicationPropertiesSection applicationPropertiesSection = null; if (_applicationProperties != null) { applicationPropertiesSection = new ApplicationProperties(_applicationProperties).createEncodingRetainingSection(); } FooterSection footerSection = null; if (_footer != null) { footerSection = new Footer(_footer).createEncodingRetainingSection(); } final QpidByteBuffer content = _message.getContent(); final MessageMetaData_1_0 mmd = new MessageMetaData_1_0(headerSection, deliveryAnnotationsSection, messageAnnotationsSection, propertiesSection, applicationPropertiesSection, footerSection, _message.getArrivalTime(), contentSize); final MessageHandle<MessageMetaData_1_0> handle = _messageStore.addMessage(mmd); if (content != null) { handle.addContent(content); } return new Message_1_0(handle.allContentAdded(), _message.getConnectionReference()); } Message_1_0_Mutator(final Message_1_0 message, final MessageStore messageStore); @Override void setPriority(final byte priority); @Override byte getPriority(); @Override Message_1_0 create(); }
@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(equalTo(TEST_CONTENT_TYPE))); assertThat(newMessage.getMessageHeader().getHeader(TEST_HEADER_NAME), is(equalTo(TEST_HEADER_VALUE))); final QpidByteBuffer content = newMessage.getContent(); final SectionDecoderImpl sectionDecoder = new SectionDecoderImpl(MessageConverter_v1_0_to_Internal.TYPE_REGISTRY.getSectionDecoderRegistry()); final List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(content); assertThat(sections.size(), is(equalTo(1))); final Object value = sections.get(0).getValue(); assertThat(value, is(equalTo(TEST_CONTENT))); }
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> converter; if(serverMessage instanceof Message_1_0) { converter = null; message = (Message_1_0) serverMessage; } else { if (!serverMessage.checkValid()) { throw new MessageConversionException(String.format("Cannot convert malformed message '%s'", serverMessage)); } converter = (MessageConverter<? super ServerMessage, Message_1_0>) MessageConverterRegistry.getConverter(serverMessage.getClass(), Message_1_0.class); if (converter == null) { throw new ServerScopedRuntimeException(String.format( "Could not find message converter from '%s' to '%s'." + " This is unexpected since we should not try to send if the converter is not present.", serverMessage.getClass(), Message_1_0.class)); } message = converter.convert(serverMessage, _linkEndpoint.getAddressSpace()); } Transfer transfer = new Transfer(); try { QpidByteBuffer bodyContent = message.getContent(); HeaderSection headerSection = message.getHeaderSection(); UnsignedInteger ttl = headerSection == null ? null : headerSection.getValue().getTtl(); if (entry.getDeliveryCount() != 0 || ttl != null) { Header header = new Header(); if (headerSection != null) { final Header oldHeader = headerSection.getValue(); header.setDurable(oldHeader.getDurable()); header.setPriority(oldHeader.getPriority()); if (ttl != null) { long timeSpentOnBroker = System.currentTimeMillis() - message.getArrivalTime(); final long adjustedTtl = Math.max(0L, ttl.longValue() - timeSpentOnBroker); header.setTtl(UnsignedInteger.valueOf(adjustedTtl)); } headerSection.dispose(); } if (entry.getDeliveryCount() != 0) { header.setDeliveryCount(UnsignedInteger.valueOf(entry.getDeliveryCount())); } headerSection = header.createEncodingRetainingSection(); } List<QpidByteBuffer> payload = new ArrayList<>(); if(headerSection != null) { payload.add(headerSection.getEncodedForm()); headerSection.dispose(); } EncodingRetainingSection<?> section; if((section = message.getDeliveryAnnotationsSection()) != null) { payload.add(section.getEncodedForm()); section.dispose(); } if((section = message.getMessageAnnotationsSection()) != null) { payload.add(section.getEncodedForm()); section.dispose(); } if((section = message.getPropertiesSection()) != null) { payload.add(section.getEncodedForm()); section.dispose(); } if((section = message.getApplicationPropertiesSection()) != null) { payload.add(section.getEncodedForm()); section.dispose(); } payload.add(bodyContent); if((section = message.getFooterSection()) != null) { payload.add(section.getEncodedForm()); section.dispose(); } try (QpidByteBuffer combined = QpidByteBuffer.concatenate(payload)) { transfer.setPayload(combined); } payload.forEach(QpidByteBuffer::dispose); byte[] data = new byte[8]; ByteBuffer.wrap(data).putLong(_deliveryTag++); final Binary tag = new Binary(data); transfer.setDeliveryTag(tag); if (_linkEndpoint.isAttached()) { boolean sendPreSettled = SenderSettleMode.SETTLED.equals(getEndpoint().getSendingSettlementMode()); if (sendPreSettled) { transfer.setSettled(true); if (_acquires && _transactionId == null) { transfer.setState(new Accepted()); } } else { final UnsettledAction action; if (_acquires) { action = new DispositionAction(tag, entry, consumer); addUnacknowledgedMessage(entry); } else { action = new DoNothingAction(); } _linkEndpoint.addUnsettled(tag, action, entry); } if (_transactionId != null) { TransactionalState state = new TransactionalState(); state.setTxnId(_transactionId); transfer.setState(state); } if (_acquires && _transactionId != null) { try { ServerTransaction txn = _linkEndpoint.getTransaction(_transactionId); txn.addPostTransactionAction(new ServerTransaction.Action() { @Override public void postCommit() { } @Override public void onRollback() { entry.release(consumer); _linkEndpoint.updateDisposition(tag, null, true); } }); final TransactionLogResource owningResource = entry.getOwningResource(); if (owningResource instanceof TransactionMonitor) { ((TransactionMonitor) owningResource).registerTransaction(txn); } } catch (UnknownTransactionException e) { entry.release(consumer); getEndpoint().close(new Error(TransactionError.UNKNOWN_ID, e.getMessage())); return; } } getSession().getAMQPConnection().registerMessageDelivered(message.getSize()); getEndpoint().transfer(transfer, false); if (sendPreSettled && _acquires && _transactionId == null) { handleAcquiredEntrySentPareSettledNonTransactional(entry, consumer); } } else { entry.release(consumer); } } finally { transfer.dispose(); if(converter != null) { converter.dispose(message); } } } ConsumerTarget_1_0(final SendingLinkEndpoint linkEndpoint, boolean acquires); @Override void updateNotifyWorkDesired(); @Override void doSend(final MessageInstanceConsumer consumer, final MessageInstance entry, boolean batch); @Override void flushBatched(); @Override void queueDeleted(final Queue queue, final MessageInstanceConsumer sub); @Override boolean allocateCredit(final ServerMessage msg); @Override void restoreCredit(final ServerMessage message); @Override void noMessagesAvailable(); void flowStateChanged(); @Override Session_1_0 getSession(); @Override String getTargetAddress(); @Override String toString(); }
@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 = createTestMessage(header, arrivalTime); final MessageInstance messageInstance = mock(MessageInstance.class); when(messageInstance.getMessage()).thenReturn(message); AtomicReference<QpidByteBuffer> payloadRef = new AtomicReference<>(); doAnswer(invocation -> { final Object[] args = invocation.getArguments(); Transfer transfer = (Transfer) args[0]; QpidByteBuffer transferPayload = transfer.getPayload(); QpidByteBuffer payloadCopy = transferPayload.duplicate(); payloadRef.set(payloadCopy); return null; }).when(_sendingLinkEndpoint).transfer(any(Transfer.class), anyBoolean()); _consumerTarget.doSend(comsumer, messageInstance, false); verify(_sendingLinkEndpoint, times(1)).transfer(any(Transfer.class), anyBoolean()); final List<EncodingRetainingSection<?>> sections; try (QpidByteBuffer payload = payloadRef.get()) { sections = new SectionDecoderImpl(_describedTypeRegistry.getSectionDecoderRegistry()).parseAll(payload); } Header sentHeader = null; for (EncodingRetainingSection<?> section : sections) { if (section instanceof HeaderSection) { sentHeader = ((HeaderSection) section).getValue(); } } assertNotNull("Header is not found", sentHeader); assertNotNull("Ttl is not set", sentHeader.getTtl()); assertTrue("Unexpected ttl", sentHeader.getTtl().longValue() <= 1000); }
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 (_inputHandleToEndpoint.containsKey(inputHandle)) { String errorMessage = String.format("Input Handle '%d' already in use", inputHandle.intValue()); getConnection().close(new Error(SessionError.HANDLE_IN_USE, errorMessage)); throw new ConnectionScopedRuntimeException(errorMessage); } else { final Link_1_0<? extends BaseSource, ? extends BaseTarget> link; if (attach.getRole() == Role.RECEIVER) { link = getAddressSpace().getSendingLink(getConnection().getRemoteContainerId(), attach.getName()); } else { link = getAddressSpace().getReceivingLink(getConnection().getRemoteContainerId(), attach.getName()); } final ListenableFuture<? extends LinkEndpoint<?,?>> future = link.attach(this, attach); addFutureCallback(future, new EndpointCreationCallback(attach), MoreExecutors.directExecutor()); } } } Session_1_0(final AMQPConnection_1_0 connection, Begin begin, int sendingChannelId, int receivingChannelId, long incomingWindow); void sendDetach(final Detach detach); void receiveAttach(final Attach attach); boolean hasCreditToSend(); void end(); boolean isActive(); void receiveEnd(final End end); UnsignedInteger getNextOutgoingId(); void sendFlowConditional(); UnsignedInteger getOutgoingWindow(); void receiveFlow(final Flow flow); void receiveDisposition(final Disposition disposition); SessionState getSessionState(); void sendFlow(); void sendFlow(final Flow flow); void receiveDetach(final Detach detach); void sendAttach(final Attach attach); boolean isSyntheticError(final Error error); void end(final End end); void receiveTransfer(final Transfer transfer); ReceivingDestination getReceivingDestination(final Link_1_0<?, ?> link, final Target target); boolean updateSourceForSubscription(final SendingLinkEndpoint linkEndpoint, final Source newSource, final SendingDestination newDestination); SendingDestination getSendingDestination(final Link_1_0<?, ?> link, final Source source); @Override void close(); void close(ErrorCondition condition, String message); @Override void transportStateChanged(); @Override void block(final Queue<?> queue); @Override void unblock(final Queue<?> queue); @Override void block(); @Override void unblock(); @Override boolean getBlocking(); @Override Object getConnectionReference(); @Override int getUnacknowledgedMessageCount(); @Override String toLogString(); AMQPConnection_1_0<?> getConnection(); @Override void addDeleteTask(final Action<? super Session_1_0> task); Subject getSubject(); SecurityToken getSecurityToken(); @Override long getTransactionStartTimeLong(); @Override long getTransactionUpdateTimeLong(); @Override boolean isClosing(); @Override String toString(); void dissociateEndpoint(LinkEndpoint<? extends BaseSource, ? extends BaseTarget> linkEndpoint); static final Symbol LIFETIME_POLICY; }
@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); assertQueues(TOPIC_NAME, LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS); } @Test public void testReceiveAttachTopicNonDurableWithContainer() throws Exception { final String linkName = "testLink"; final String address = "amq.direct/" + TOPIC_NAME; Attach attach = createTopicAttach(false, linkName, address, false); _session.receiveAttach(attach); assertAttachSent(_connection, _session, attach); assertQueues(TOPIC_NAME, LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS); } @Test public void testReceiveAttachTopicDurableNoContainer() throws Exception { final String linkName = "testLink"; final String address = "amq.direct/" + TOPIC_NAME; Attach attach = createTopicAttach(true, linkName, address, true); _session.receiveAttach(attach); assertAttachSent(_connection, _session, attach); assertQueues(TOPIC_NAME, LifetimePolicy.PERMANENT); } @Test public void testReceiveAttachTopicDurableWithContainer() throws Exception { final String linkName = "testLink"; final String address = "amq.direct/" + TOPIC_NAME; Attach attach = createTopicAttach(true, linkName+ "|1", address, false); _session.receiveAttach(attach); assertAttachSent(_connection, _session, attach); assertQueues(TOPIC_NAME, LifetimePolicy.PERMANENT); AMQPConnection_1_0 secondConnection = createAmqpConnection_1_0("testContainerId2"); Session_1_0 secondSession = createSession_1_0(secondConnection, 0); Attach attach2 = createTopicAttach(true, linkName + "|2", address, false); secondSession.receiveAttach(attach2); assertAttachSent(secondConnection, secondSession, attach2); Collection<Queue> queues = _virtualHost.getChildren(Queue.class); assertEquals( "Unexpected number of queues after second subscription with the same subscription name but different " + "container id ", (long) 2, (long) queues.size()); } @Test public void testReceiveAttachSharedTopicNonDurableNoContainer() throws Exception { final String linkName = "testLink"; final String address = "amq.direct/" + TOPIC_NAME; Attach attach = createSharedTopicAttach(false, linkName, address, true); Attach attach2 = createSharedTopicAttach(false, linkName, address, true); _session.receiveAttach(attach); assertAttachSent(_connection, _session, attach); assertQueues(TOPIC_NAME, LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS); AMQPConnection_1_0 secondConnection = createAmqpConnection_1_0(); Session_1_0 secondSession = createSession_1_0(secondConnection, 0); secondSession.receiveAttach(attach2); assertAttachSent(secondConnection, secondSession, attach2); assertQueues(TOPIC_NAME, LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS); final Collection<Queue> queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after attach", (long) 1, (long) queues.size()); Queue<?> queue = queues.iterator().next(); Collection<QueueConsumer<?,?>> consumers = queue.getConsumers(); assertEquals("Unexpected number of consumers", (long) 2, (long) consumers.size()); } @Test public void testReceiveAttachSharedTopicNonDurableWithContainer() throws Exception { final String linkName = "testLink"; final String address = "amq.direct/" + TOPIC_NAME; Attach attach = createSharedTopicAttach(false, linkName, address, false); Attach attach2 = createSharedTopicAttach(false, linkName, address, false); _session.receiveAttach(attach); assertAttachSent(_connection, _session, attach); assertQueues(TOPIC_NAME, LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS); AMQPConnection_1_0 secondConnection = createAmqpConnection_1_0("testContainerId2"); Session_1_0 secondSession = createSession_1_0(secondConnection, 0); secondSession.receiveAttach(attach2); assertAttachSent(secondConnection, secondSession, attach2); final Collection<Queue> queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after attach", (long) 2, (long) queues.size()); for (Queue<?> queue : queues) { Collection<QueueConsumer<?,?>> consumers = queue.getConsumers(); assertEquals("Unexpected number of consumers on queue " + queue.getName(), (long) 1, (long) consumers.size()); } } @Test public void testSeparateSubscriptionNameSpaces() throws Exception { AMQPConnection_1_0 secondConnection = createAmqpConnection_1_0(); Session_1_0 secondSession = createSession_1_0(secondConnection, 0); final String linkName = "testLink"; final String address = "amq.direct/" + TOPIC_NAME; Attach durableSharedWithContainerId = createSharedTopicAttach(true, linkName + "|1", address, false); _session.receiveAttach(durableSharedWithContainerId); assertAttachSent(_connection, _session, durableSharedWithContainerId, 0); Collection<Queue> queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after durable non shared with containerId", (long) 1, (long) queues.size()); Attach durableNonSharedWithContainerId = createTopicAttach(true, linkName, address, false); _session.receiveAttach(durableNonSharedWithContainerId); assertAttachFailed(_connection, _session, durableNonSharedWithContainerId, 1); queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after durable non shared with containerId", (long) 1, (long) queues.size()); Attach nonDurableSharedWithContainerId = createSharedTopicAttach(false, linkName + "|3", address, false); _session.receiveAttach(nonDurableSharedWithContainerId); assertAttachSent(_connection, _session, nonDurableSharedWithContainerId, 3); queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after durable non shared with containerId", (long) 2, (long) queues.size()); Attach durableSharedWithoutContainerId = createSharedTopicAttach(true, linkName + "|4", address, true); secondSession.receiveAttach(durableSharedWithoutContainerId); assertAttachSent(secondConnection, secondSession, durableSharedWithoutContainerId, 0); queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after durable non shared with containerId", (long) 3, (long) queues.size()); Attach nonDurableSharedWithoutContainerId = createSharedTopicAttach(false, linkName + "|5", address, true); secondSession.receiveAttach(nonDurableSharedWithoutContainerId); assertAttachSent(secondConnection, secondSession, nonDurableSharedWithoutContainerId, 1); queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after durable non shared with containerId", (long) 4, (long) queues.size()); Attach nonDurableNonSharedWithoutContainerId = createTopicAttach(false, linkName + "|6", address, true); secondSession.receiveAttach(nonDurableNonSharedWithoutContainerId); assertAttachSent(secondConnection, secondSession, nonDurableNonSharedWithoutContainerId, 2); queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after durable non shared with containerId", (long) 5, (long) queues.size()); Attach nonDurableNonSharedWithContainerId = createTopicAttach(false, linkName + "|6", address, false); _session.receiveAttach(nonDurableNonSharedWithContainerId); assertAttachSent(_connection, _session, nonDurableNonSharedWithContainerId, 4); queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after durable non shared with containerId", (long) 6, (long) queues.size()); } @Test public void testReceiveAttachForInvalidUnsubscribe() throws Exception { final String linkName = "testLink"; final String address = "amq.direct/" + TOPIC_NAME; Attach unsubscribeAttach = createTopicAttach(true, linkName, address, false); unsubscribeAttach.setSource(null); _session.receiveAttach(unsubscribeAttach); assertAttachFailed(_connection, _session, unsubscribeAttach); Collection<Queue> queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after unsubscribe", (long) 0, (long) queues.size()); } @Test public void testReceiveAttachToExistingQueue() throws Exception { final String linkName = "testLink"; Attach attach = createQueueAttach(false, linkName, QUEUE_NAME); Queue<?> queue = _virtualHost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, QUEUE_NAME)); Exchange<?> exchange = _virtualHost.getChildByName(Exchange.class, "amq.direct"); exchange.bind(QUEUE_NAME, QUEUE_NAME, Collections.emptyMap(), false); _session.receiveAttach(attach); assertAttachActions(queue, attach); } @Test public void testReceiveAttachToNonExistingQueue() throws Exception { final String linkName = "testLink"; Attach attach = createQueueAttach(false, linkName, QUEUE_NAME); _session.receiveAttach(attach); assertAttachFailed(_connection, _session, attach); } @Test public void testReceiveAttachTopicNonDurableNoContainerWithInvalidSelector() throws Exception { final String linkName = "testLink"; final String address = "amq.direct/" + TOPIC_NAME; Attach attach = createTopicAttach(false, linkName, address, true); setSelector(attach, "invalid selector"); _session.receiveAttach(attach); assertAttachFailed(_connection, _session, attach); final Collection<Queue> queues = _virtualHost.getChildren(Queue.class); assertEquals("Unexpected number of queues after attach", (long) 0, (long) queues.size()); } @Test public void testLinkStealing() { _virtualHost.createChild(Queue.class, Collections.singletonMap(Queue.NAME, QUEUE_NAME)); Attach attach = createQueueAttach(true, getTestName(), QUEUE_NAME); AMQPConnection_1_0 connection1 = _connection; Session_1_0 session1 = _session; session1.receiveAttach(attach); Link_1_0<?,?> link = _virtualHost.getSendingLink(connection1.getRemoteContainerId(), attach.getName()); assertNotNull("Link is not created", link); assertAttachSent(connection1, session1, attach); AMQPConnection_1_0 connection2 = createAmqpConnection_1_0(connection1.getRemoteContainerId()); Session_1_0 session2 = createSession_1_0(connection2, 0); session2.receiveAttach(attach); assertDetachSent(connection1, session1, LinkError.STOLEN, 1); assertAttachSent(connection2, session2, attach); }
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, JmsMessageTypeAnnotation.STREAM_MESSAGE.getType()); } @Test public void testConvertJmsStreamMessageEmptyBody() throws Exception { final List<Object> expected = Collections.emptyList(); doTestStreamMessage(null, "jms/stream-message", expected, JmsMessageTypeAnnotation.STREAM_MESSAGE.getType()); } @Test public void testConvertAmqpListMessageBody() throws Exception { final List<Object> expected = Lists.newArrayList("apple", 43, 31.42D); final byte[] messageBytes = new ListToAmqpListConverter().toMimeContent(expected); final String mimeType = "amqp/list"; doTestStreamMessage(messageBytes, mimeType, expected, JmsMessageTypeAnnotation.STREAM_MESSAGE.getType()); } @Test public void testConvertJmsMapMessageBody() throws Exception { final Map<String, Object> expected = Collections.singletonMap("key", "value"); final byte[] messageBytes = getJmsMapMessageBytes(expected); doTestMapMessage(messageBytes, "jms/map-message", expected, JmsMessageTypeAnnotation.MAP_MESSAGE.getType()); } @Test public void testConvertAmqpMapMessageBody() throws Exception { final Map<String, Object> expected = Collections.singletonMap("key", "value"); final byte[] messageBytes = new MapToAmqpMapConverter().toMimeContent(expected); doTestMapMessage(messageBytes, "amqp/map", expected, JmsMessageTypeAnnotation.MAP_MESSAGE.getType()); } @Test public void testConvertJmsMapMessageEmptyBody() throws Exception { final Map<String, Object> expected = Collections.emptyMap(); doTestMapMessage(null, "jms/map-message", expected, JmsMessageTypeAnnotation.MAP_MESSAGE.getType()); } @Test public void testConvertEmptyMessageWithoutContentType() throws Exception { doTest(null, null, AmqpValueSection.class, null, null, JmsMessageTypeAnnotation.MESSAGE.getType()); }
JDBCSettingsDrivenConnectionSource extends ConnectionSourceBase { @Override public void start() { _connectionProvider.getAndUpdate(provider -> provider == null ? create() : provider); discoverConnectionProperties(); if (!supportsGetGeneratedKeys() && getSQLDialectCode() == SQLDialectCode.UNKNOWN_DIALECT) { addWarn("Connection does not support GetGeneratedKey method and could not discover the dialect."); } super.start(); } JDBCSettingsDrivenConnectionSource(final ConfiguredObject<?> object, final JDBCSettings jdbcSettings); @Override Connection getConnection(); @Override void start(); @Override void stop(); @Override String toString(); }
@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 connection provider", e); } } } JDBCSettingsDrivenConnectionSource(final ConfiguredObject<?> object, final JDBCSettings jdbcSettings); @Override Connection getConnection(); @Override void start(); @Override void stop(); @Override String toString(); }
@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"); } return connectionProvider.getConnection(); } JDBCSettingsDrivenConnectionSource(final ConfiguredObject<?> object, final JDBCSettings jdbcSettings); @Override Connection getConnection(); @Override void start(); @Override void stop(); @Override String toString(); }
@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> attributes, VirtualHost<?> virtualHost); @Override String getConnectionUrl(); @Override String getConnectionPoolType(); @Override String getUsername(); @Override String getPassword(); @Override String getTableNamePrefix(); }
@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); @Override String getConnectionUrl(); @Override String getConnectionPoolType(); @Override String getUsername(); @Override String getPassword(); @Override String getTableNamePrefix(); }
@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 + tableName.toString(); return name.toLowerCase(); } JDBCSettingsDBNameResolver(final JDBCSettings settings); @Override String getTableName(final N tableName); @Override String getColumnName(final N columnName); }
@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(final N columnName); }
@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(context, logger, settings); final DBAppender appender = new DBAppender(); appender.setDbNameResolver(dbNameResolver); appender.setConnectionSource(connectionSource); appender.setContext(context); appender.start(); return appender; } catch (Exception e) { LOGGER.error("Failed to create appender", e); throw new IllegalConfigurationException("Cannot create appender"); } } }
@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(context, appender.getContext()); assertTrue(((DBAppender) appender).getConnectionSource() instanceof JDBCSettingsDrivenConnectionSource); }
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(connectionSource).stop(); verify(connectionSource).start(); verifyNoMoreInteractions(connectionSource); }
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( "Cannot create connection source from given URL, credentials and connection pool type"); } } }
@Test public void validateConnectionSourceSettings() { _jdbcLoggerHelper.validateConnectionSourceSettings(_broker, _jdbcSettings); } @Test public void validateConnectionSourceSettingsForInvalidURL() { when(_jdbcSettings.getConnectionUrl()).thenReturn(INVALID_JDBC_URL); try { _jdbcLoggerHelper.validateConnectionSourceSettings(_broker, _jdbcSettings); fail("Exception is expected"); } catch (IllegalConfigurationException e) { } }
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); } } StoreConfigurationChangeListener(DurableConfigurationStore store); @Override void stateChanged(ConfiguredObject object, State oldState, State newState); @Override void childAdded(ConfiguredObject<?> object, ConfiguredObject<?> child); @Override void bulkChangeStart(final ConfiguredObject<?> object); @Override void bulkChangeEnd(final ConfiguredObject<?> object); @Override void childRemoved(ConfiguredObject object, ConfiguredObject child); @Override void attributeSet(ConfiguredObject object, String attributeName, Object oldAttributeValue, Object newAttributeValue); @Override String toString(); }
@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()).thenReturn(record); _listener.stateChanged(object, State.ACTIVE, State.DELETED); verify(_store).remove(record); }
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> parentType = model.getParentType(child.getCategoryClass()); if(parentType.equals(object.getCategoryClass())) { child.addChangeListener(this); _store.update(true, child.asObjectRecord()); Class<? extends ConfiguredObject> categoryClass = child.getCategoryClass(); Collection<Class<? extends ConfiguredObject>> childTypes = model.getChildTypes(categoryClass); for (Class<? extends ConfiguredObject> childClass : childTypes) { for (ConfiguredObject<?> grandchild : child.getChildren(childClass)) { childAdded(child, grandchild); } } } } } } StoreConfigurationChangeListener(DurableConfigurationStore store); @Override void stateChanged(ConfiguredObject object, State oldState, State newState); @Override void childAdded(ConfiguredObject<?> object, ConfiguredObject<?> child); @Override void bulkChangeStart(final ConfiguredObject<?> object); @Override void bulkChangeEnd(final ConfiguredObject<?> object); @Override void childRemoved(ConfiguredObject object, ConfiguredObject child); @Override void attributeSet(ConfiguredObject object, String attributeName, Object oldAttributeValue, Object newAttributeValue); @Override String toString(); }
@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 = mock(Model.class); when(model.getChildTypes(any(Class.class))).thenReturn(Collections.<Class<? extends ConfiguredObject>>emptyList()); when(model.getParentType(eq(VirtualHost.class))).thenReturn((Class)Broker.class); when(child.getModel()).thenReturn(model); when(child.isDurable()).thenReturn(true); final ConfiguredObjectRecord childRecord = mock(ConfiguredObjectRecord.class); when(child.asObjectRecord()).thenReturn(childRecord); _listener.childAdded(broker, child); verify(_store).update(eq(true), eq(childRecord)); } @Test public void testChildAddedWhereParentManagesChildStorage() { notifyBrokerStarted(); VirtualHostNode<?> object = mock(VirtualHostNode.class); when(object.managesChildStorage()).thenReturn(true); VirtualHost<?> virtualHost = mock(VirtualHost.class); _listener.childAdded(object, virtualHost); verifyNoMoreInteractions(_store); }
StoreConfigurationChangeListener implements ConfigurationChangeListener { @Override public void attributeSet(ConfiguredObject object, String attributeName, Object oldAttributeValue, Object newAttributeValue) { if (object.isDurable() && !_bulkChanges) { _store.update(false, object.asObjectRecord()); } } StoreConfigurationChangeListener(DurableConfigurationStore store); @Override void stateChanged(ConfiguredObject object, State oldState, State newState); @Override void childAdded(ConfiguredObject<?> object, ConfiguredObject<?> child); @Override void bulkChangeStart(final ConfiguredObject<?> object); @Override void bulkChangeEnd(final ConfiguredObject<?> object); @Override void childRemoved(ConfiguredObject object, ConfiguredObject child); @Override void attributeSet(ConfiguredObject object, String attributeName, Object oldAttributeValue, Object newAttributeValue); @Override String toString(); }
@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); _listener.attributeSet(broker, Broker.DESCRIPTION, null, "test description"); verify(_store).update(eq(false), eq(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, SystemConfig<?> systemConfig); @Override void init(final ConfiguredObject<?> parent); @Override void upgradeStoreStructure(); @Override boolean openConfigurationStore(final ConfiguredObjectRecordHandler recoveryHandler, final ConfiguredObjectRecord... initialRecords); @Override void reload(final ConfiguredObjectRecordHandler handle); @Override void create(final ConfiguredObjectRecord object); @Override void update(final boolean createIfNecessary, final ConfiguredObjectRecord... records); @Override void closeConfigurationStore(); @Override void onDelete(ConfiguredObject<?> parent); @Override synchronized UUID[] remove(final ConfiguredObjectRecord... records); void recoverRecords(final List<ConfiguredObjectRecord> records); }
@Test public void testGetRootEntryWithHttpPortOverriden() { _systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,9090); _handler = createManagementModeStoreHandler(); _handler.init(_systemConfig); Collection<ConfiguredObjectRecord> records = openAndGetRecords(); ConfiguredObjectRecord root = getRootEntry(records); assertEquals("Unexpected root id", _rootId, root.getId()); Collection<UUID> childrenIds = getChildrenIds(records, root); assertEquals("Unexpected children size", (long) 2, (long) childrenIds.size()); assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); } @Test public void testGetRootEntryWithManagementPortsOverriden() { _systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,1000); _handler = createManagementModeStoreHandler(); _handler.init(_systemConfig); Collection<ConfiguredObjectRecord> records = openAndGetRecords(); ConfiguredObjectRecord root = getRootEntry(records); assertEquals("Unexpected root id", _rootId, root.getId()); Collection<UUID> childrenIds = getChildrenIds(records, root); assertEquals("Unexpected children size", (long) 2, (long) childrenIds.size()); assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); } @Test public void testGetEntryByCLIHttpPortId() { _systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,9090); _handler = createManagementModeStoreHandler(); _handler.init(_systemConfig); Collection<ConfiguredObjectRecord> records = openAndGetRecords(); UUID optionsPort = getOptionsPortId(records); ConfiguredObjectRecord portEntry = getEntry(records, optionsPort); assertCLIPortEntry(records, portEntry, optionsPort, Protocol.HTTP); } @Test public void testHttpPortEntryIsQuiesced() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.PROTOCOLS, Collections.singleton(Protocol.HTTP)); when(_portEntry.getAttributes()).thenReturn(attributes); _systemConfigAttributes.put(SystemConfig.MANAGEMENT_MODE_HTTP_PORT_OVERRIDE,9090); _handler = createManagementModeStoreHandler(); _handler.init(_systemConfig); Collection<ConfiguredObjectRecord> records = openAndGetRecords(); ConfiguredObjectRecord portEntry = getEntry(records, _portEntryId); assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.DESIRED_STATE)); }
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[i].getId(); } for (UUID id : idsToRemove) { if (_cliEntries.containsKey(id)) { throw new IllegalConfigurationException("Cannot change configuration for command line entry:" + _cliEntries.get(id)); } } UUID[] result = _store.remove(records); for (UUID id : idsToRemove) { if (_quiescedEntriesOriginalState.containsKey(id)) { _quiescedEntriesOriginalState.remove(id); } } for(ConfiguredObjectRecord record : records) { _records.remove(record.getId()); } return result; } } ManagementModeStoreHandler(DurableConfigurationStore store, SystemConfig<?> systemConfig); @Override void init(final ConfiguredObject<?> parent); @Override void upgradeStoreStructure(); @Override boolean openConfigurationStore(final ConfiguredObjectRecordHandler recoveryHandler, final ConfiguredObjectRecord... initialRecords); @Override void reload(final ConfiguredObjectRecordHandler handle); @Override void create(final ConfiguredObjectRecord object); @Override void update(final boolean createIfNecessary, final ConfiguredObjectRecord... records); @Override void closeConfigurationStore(); @Override void onDelete(ConfiguredObject<?> parent); @Override synchronized UUID[] remove(final ConfiguredObjectRecord... records); void recoverRecords(final List<ConfiguredObjectRecord> 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() { @Override public UUID getId() { return _portEntryId; } @Override public String getType() { return Port.class.getSimpleName(); } @Override public Map<String, Object> getAttributes() { return Collections.emptyMap(); } @Override public Map<String, UUID> getParents() { return null; } }; _handler.remove(record); verify(_store).remove(record); }
LocalTransaction implements ServerTransaction { @Override public void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction) { sync(); _outstandingWork = true; initTransactionStartTimeIfNecessaryAndAdvanceUpdateTime(); _transactionObserver.onMessageEnqueue(this, message); if(queue.getMessageDurability().persist(message.isPersistent())) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Enqueue of message number " + message.getMessageNumber() + " to transaction log. Queue : " + queue.getName()); } beginTranIfNecessary(); final MessageEnqueueRecord record = _transaction.enqueueMessage(queue, message); if(postTransactionAction != null) { final EnqueueAction underlying = postTransactionAction; _postTransactionActions.add(new Action() { @Override public void postCommit() { underlying.postCommit(record); } @Override public void onRollback() { underlying.onRollback(); } }); } } catch(RuntimeException e) { if(postTransactionAction != null) { final EnqueueAction underlying = postTransactionAction; _postTransactionActions.add(new Action() { @Override public void postCommit() { } @Override public void onRollback() { underlying.onRollback(); } }); } tidyUpOnError(e); } } else { if(postTransactionAction != null) { final EnqueueAction underlying = postTransactionAction; _postTransactionActions.add(new Action() { @Override public void postCommit() { underlying.postCommit((MessageEnqueueRecord)null); } @Override public void onRollback() { underlying.onRollback(); } }); } } } LocalTransaction(MessageStore transactionLog); LocalTransaction(MessageStore transactionLog, TransactionObserver transactionObserver); LocalTransaction(MessageStore transactionLog, ActivityTimeAccessor activityTime, TransactionObserver transactionObserver, boolean resetable); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addPostTransactionAction(Action postTransactionAction); @Override void dequeue(MessageEnqueueRecord record, Action postTransactionAction); @Override void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction); @Override void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void enqueue(Collection<? extends BaseQueue> queues, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void commit(); @Override void commit(Runnable immediateAction); void commitAsync(final Runnable deferred); @Override void rollback(); void sync(); @Override boolean isTransactional(); boolean setRollbackOnly(); boolean isRollbackOnly(); boolean hasOutstandingWork(); boolean isDischarged(); void addTransactionListener(LocalTransactionListener listener); void removeTransactionListener(LocalTransactionListener listener); }
@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) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testEnqueueToDurableQueueOfPersistentMessage() throws Exception { _message = createTestMessage(true); _queue = createQueue(true); _transaction.enqueue(_queue, _message, _action1); assertEquals("Enqueue of persistent message to durable queue must cause message to be enqueued", (long) 1, (long) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testStoreEnqueueCausesException() throws Exception { _message = createTestMessage(true); _queue = createQueue(true); _storeTransaction = createTestStoreTransaction(true); _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); _transaction = new LocalTransaction(_transactionLog); try { _transaction.enqueue(_queue, _message, _action1); fail("Exception not thrown"); } catch (RuntimeException re) { } assertTrue("Rollback action must be fired", _action1.isRollbackActionFired()); assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired()); } @Test public void testEnqueueToManyNonDurableQueuesOfNonPersistentMessage() throws Exception { _message = createTestMessage(false); _queues = createTestBaseQueues(new boolean[] {false, false, false}); _transaction.enqueue(_queues, _message, _action1); assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", (long) 0, (long) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testEnqueueToManyNonDurableQueuesOfPersistentMessage() throws Exception { _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {false, false, false}); _transaction.enqueue(_queues, _message, _action1); assertEquals("Enqueue of persistent message to non-durable queues must not cause message to be enqueued", (long) 0, (long) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testEnqueueToDurableAndNonDurableQueuesOfPersistentMessage() throws Exception { _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {false, true, false, true}); _transaction.enqueue(_queues, _message, _action1); assertEquals( "Enqueue of persistent message to durable/non-durable queues must cause messages to be enqueued", (long) 2, (long) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testStoreEnqueuesCausesExceptions() throws Exception { _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {true, true}); _storeTransaction = createTestStoreTransaction(true); _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); _transaction = new LocalTransaction(_transactionLog); try { _transaction.enqueue(_queues, _message, _action1); fail("Exception not thrown"); } catch (RuntimeException re) { } assertTrue("Rollback action must be fired", _action1.isRollbackActionFired()); assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired()); } @Test public void testEnqueueInvokesTransactionObserver() throws Exception { final TransactionObserver transactionObserver = mock(TransactionObserver.class); _transaction = new LocalTransaction(_transactionLog, transactionObserver); _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {false, true, false, true}); _transaction.enqueue(_queues, _message, null); verify(transactionObserver).onMessageEnqueue(_transaction, _message); ServerMessage message2 = createTestMessage(true); _transaction.enqueue(createQueue(true), message2, null); verify(transactionObserver).onMessageEnqueue(_transaction, message2); verifyNoMoreInteractions(transactionObserver); }
LocalTransaction implements ServerTransaction { @Override public void dequeue(MessageEnqueueRecord record, Action postTransactionAction) { sync(); _outstandingWork = true; _postTransactionActions.add(postTransactionAction); initTransactionStartTimeIfNecessaryAndAdvanceUpdateTime(); if(record != null) { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Dequeue of message number " + record.getMessageNumber() + " from transaction log. Queue : " + record.getQueueId()); } beginTranIfNecessary(); _transaction.dequeueMessage(record); } catch(RuntimeException e) { tidyUpOnError(e); } } } LocalTransaction(MessageStore transactionLog); LocalTransaction(MessageStore transactionLog, TransactionObserver transactionObserver); LocalTransaction(MessageStore transactionLog, ActivityTimeAccessor activityTime, TransactionObserver transactionObserver, boolean resetable); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addPostTransactionAction(Action postTransactionAction); @Override void dequeue(MessageEnqueueRecord record, Action postTransactionAction); @Override void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction); @Override void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void enqueue(Collection<? extends BaseQueue> queues, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void commit(); @Override void commit(Runnable immediateAction); void commitAsync(final Runnable deferred); @Override void rollback(); void sync(); @Override boolean isTransactional(); boolean setRollbackOnly(); boolean isRollbackOnly(); boolean hasOutstandingWork(); boolean isDischarged(); void addTransactionListener(LocalTransactionListener listener); void removeTransactionListener(LocalTransactionListener listener); }
@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, (long) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testDequeueFromDurableQueueOfPersistentMessage() throws Exception { _message = createTestMessage(true); _queue = createQueue(true); _transaction.dequeue(mock(MessageEnqueueRecord.class), _action1); assertEquals("Dequeue of non-persistent message must cause message to be dequeued", (long) 1, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testStoreDequeueCausesException() throws Exception { _message = createTestMessage(true); _queue = createQueue(true); _storeTransaction = createTestStoreTransaction(true); _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); _transaction = new LocalTransaction(_transactionLog); try { _transaction.dequeue(mock(MessageEnqueueRecord.class), _action1); fail("Exception not thrown"); } catch (RuntimeException re) { } assertTrue("Rollback action must be fired", _action1.isRollbackActionFired()); assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired()); } @Test public void testDequeueFromManyNonDurableQueuesOfNonPersistentMessage() throws Exception { _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {false, false, false}); _transaction.dequeue(_queueEntries, _action1); assertEquals("Dequeue of non-persistent messages must not cause message to be dequeued", (long) 0, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testDequeueFromManyNonDurableQueuesOfPersistentMessage() throws Exception { _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {true, true, true}); _transaction.dequeue(_queueEntries, _action1); assertEquals( "Dequeue of persistent message from non-durable queues must not cause message to be enqueued", (long) 0, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testDequeueFromDurableAndNonDurableQueuesOfPersistentMessage() throws Exception { _queueEntries = createTestQueueEntries(new boolean[] {true, false, true, true}, new boolean[] {true, true, true, false}); _transaction.dequeue(_queueEntries, _action1); assertEquals( "Dequeue of persistent messages from durable/non-durable queues must cause messages to be dequeued", (long) 2, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected transaction state", TransactionState.STARTED, _storeTransaction.getState()); assertNotFired(_action1); } @Test public void testStoreDequeuesCauseExceptions() throws Exception { _queueEntries = createTestQueueEntries(new boolean[] {true}, new boolean[] {true}); _storeTransaction = createTestStoreTransaction(true); _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); _transaction = new LocalTransaction(_transactionLog); try { _transaction.dequeue(_queueEntries, _action1); fail("Exception not thrown"); } catch (RuntimeException re) { } assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); assertTrue("Rollback action must be fired", _action1.isRollbackActionFired()); assertFalse("Post commit action must not be fired", _action1.isPostCommitActionFired()); }
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()); Map<Symbol, Object> properties = flow.getProperties(); if (properties != null) { final Binary transactionId = (Binary) properties.get(Symbol.valueOf("txn-id")); if (transactionId != null) { try { getSession().getTransaction(transactionId); } catch (UnknownTransactionException e) { close(new Error(TransactionError.UNKNOWN_ID, e.getMessage())); return; } } _transactionId = transactionId; } if(receiverDeliveryCount == null) { setLinkCredit(receiverLinkCredit); } else { SequenceNumber limit = new SequenceNumber(receiverDeliveryCount.intValue()).add(receiverLinkCredit.intValue()); if (limit.compareTo(getDeliveryCount()) <= 0) { setLinkCredit(UnsignedInteger.valueOf(0)); } else { setLinkCredit(limit.subtract(getDeliveryCount().intValue()).unsignedIntegerValue()); } } boolean sendFlow = Boolean.TRUE.equals(flow.getEcho()) || ( Boolean.TRUE.equals(flow.getDrain()) && getLinkCredit().equals(UnsignedInteger.ZERO)); flowStateChanged(); if (sendFlow) { sendFlow(); } } SendingLinkEndpoint(final Session_1_0 session, final LinkImpl<Source, Target> link); @Override void start(); @Override Role getRole(); @Override void receiveFlow(final Flow flow); @Override void flowStateChanged(); ServerTransaction getTransaction(Binary transactionId); boolean hasCreditToSend(); Binary getTransactionId(); @Override void attachReceived(final Attach attach); SendingDestination getDestination(); void setDestination(final SendingDestination destination); @Override void receiveComplete(); @Override void recordFuture(final ListenableFuture<Void> future, final ServerTransaction.Action action); }
@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(flow); UnsignedInteger linkCredit = _sendingLinkEndpoint.getLinkCredit(); assertThat(linkCredit, is(equalTo(UnsignedInteger.ONE))); }
LocalTransaction implements ServerTransaction { @Override public void addPostTransactionAction(Action postTransactionAction) { sync(); _postTransactionActions.add(postTransactionAction); } LocalTransaction(MessageStore transactionLog); LocalTransaction(MessageStore transactionLog, TransactionObserver transactionObserver); LocalTransaction(MessageStore transactionLog, ActivityTimeAccessor activityTime, TransactionObserver transactionObserver, boolean resetable); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addPostTransactionAction(Action postTransactionAction); @Override void dequeue(MessageEnqueueRecord record, Action postTransactionAction); @Override void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction); @Override void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void enqueue(Collection<? extends BaseQueue> queues, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void commit(); @Override void commit(Runnable immediateAction); void commitAsync(final Runnable deferred); @Override void rollback(); void sync(); @Override boolean isTransactional(); boolean setRollbackOnly(); boolean isRollbackOnly(); boolean hasOutstandingWork(); boolean isDischarged(); void addTransactionListener(LocalTransactionListener listener); void removeTransactionListener(LocalTransactionListener listener); }
@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, ActivityTimeAccessor activityTime, TransactionObserver transactionObserver, boolean resetable); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addPostTransactionAction(Action postTransactionAction); @Override void dequeue(MessageEnqueueRecord record, Action postTransactionAction); @Override void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction); @Override void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void enqueue(Collection<? extends BaseQueue> queues, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void commit(); @Override void commit(Runnable immediateAction); void commitAsync(final Runnable deferred); @Override void rollback(); void sync(); @Override boolean isTransactional(); boolean setRollbackOnly(); boolean isRollbackOnly(); boolean hasOutstandingWork(); boolean isDischarged(); void addTransactionListener(LocalTransactionListener listener); void removeTransactionListener(LocalTransactionListener listener); }
@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()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); }
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.DISCHARGING) { throw new IllegalStateException(String.format("Cannot roll back transaction with state '%s'", _state.get())); } try { if(_transaction != null) { _transaction.abortTran(); } } finally { try { doRollbackActions(); } finally { resetDetails(); } } } LocalTransaction(MessageStore transactionLog); LocalTransaction(MessageStore transactionLog, TransactionObserver transactionObserver); LocalTransaction(MessageStore transactionLog, ActivityTimeAccessor activityTime, TransactionObserver transactionObserver, boolean resetable); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addPostTransactionAction(Action postTransactionAction); @Override void dequeue(MessageEnqueueRecord record, Action postTransactionAction); @Override void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction); @Override void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void enqueue(Collection<? extends BaseQueue> queues, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void commit(); @Override void commit(Runnable immediateAction); void commitAsync(final Runnable deferred); @Override void rollback(); void sync(); @Override boolean isTransactional(); boolean setRollbackOnly(); boolean isRollbackOnly(); boolean hasOutstandingWork(); boolean isDischarged(); void addTransactionListener(LocalTransactionListener listener); void removeTransactionListener(LocalTransactionListener listener); }
@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()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); }
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.debug("Enqueue of message number {} to transaction log. Queue : {}", message.getMessageNumber(), queue.getName()); txn = _messageStore.newTransaction(); record = txn.enqueueMessage(queue, message); txn.commitTran(); txn = null; } else { record = null; } if(postTransactionAction != null) { postTransactionAction.postCommit(record); } postTransactionAction = null; } finally { final EnqueueAction underlying = postTransactionAction; rollbackIfNecessary(new Action() { @Override public void postCommit() { } @Override public void onRollback() { if(underlying != null) { underlying.onRollback(); } } }, txn); } } AutoCommitTransaction(MessageStore transactionLog); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addPostTransactionAction(final Action immediateAction); @Override void dequeue(MessageEnqueueRecord record, Action postTransactionAction); @Override void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction); @Override void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void enqueue(Collection<? extends BaseQueue> queues, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void commit(final Runnable immediatePostTransactionAction); @Override void commit(); @Override void rollback(); @Override boolean isTransactional(); }
@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) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); } @Test public void testEnqueueToDurableQueueOfPersistentMessage() throws Exception { _message = createTestMessage(true); _queue = createTestAMQQueue(true); _transaction.enqueue(_queue, _message, _action); assertEquals("Enqueue of persistent message to durable queue must cause message to be enqueued", (long) 1, (long) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState()); assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); } @Test public void testStoreEnqueueCausesException() throws Exception { _message = createTestMessage(true); _queue = createTestAMQQueue(true); _storeTransaction = createTestStoreTransaction(true); _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); _transaction = new AutoCommitTransaction(_transactionLog); try { _transaction.enqueue(_queue, _message, _action); fail("Exception not thrown"); } catch (RuntimeException re) { } assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); assertTrue("Rollback action must be fired", _action.isRollbackActionFired()); assertFalse("Post commit action must be fired", _action.isPostCommitActionFired()); } @Test public void testEnqueueToManyNonDurableQueuesOfNonPersistentMessage() throws Exception { _message = createTestMessage(false); _queues = createTestBaseQueues(new boolean[] {false, false, false}); _transaction.enqueue(_queues, _message, _action); assertEquals("Enqueue of non-persistent message must not cause message to be enqueued", (long) 0, (long) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); } @Test public void testEnqueueToManyNonDurableQueuesOfPersistentMessage() throws Exception { _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {false, false, false}); _transaction.enqueue(_queues, _message, _action); assertEquals("Enqueue of persistent message to non-durable queues must not cause message to be enqueued", (long) 0, (long) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); } @Test public void testEnqueueToDurableAndNonDurableQueuesOfPersistentMessage() throws Exception { _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {false, true, false, true}); _transaction.enqueue(_queues, _message, _action); assertEquals( "Enqueue of persistent message to durable/non-durable queues must cause messages to be enqueued", (long) 2, (long) _storeTransaction.getNumberOfEnqueuedMessages()); assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState()); assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); } @Test public void testStoreEnqueuesCausesExceptions() throws Exception { _message = createTestMessage(true); _queues = createTestBaseQueues(new boolean[] {true, true}); _storeTransaction = createTestStoreTransaction(true); _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); _transaction = new AutoCommitTransaction(_transactionLog); try { _transaction.enqueue(_queues, _message, _action); fail("Exception not thrown"); } catch (RuntimeException re) { } assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); assertTrue("Rollback action must be fired", _action.isRollbackActionFired()); assertFalse("Post commit action must not be fired", _action.isPostCommitActionFired()); }
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()); txn = _messageStore.newTransaction(); txn.dequeueMessage(record); txn.commitTran(); txn = null; } postTransactionAction.postCommit(); postTransactionAction = null; } finally { rollbackIfNecessary(postTransactionAction, txn); } } AutoCommitTransaction(MessageStore transactionLog); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addPostTransactionAction(final Action immediateAction); @Override void dequeue(MessageEnqueueRecord record, Action postTransactionAction); @Override void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction); @Override void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void enqueue(Collection<? extends BaseQueue> queues, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void commit(final Runnable immediatePostTransactionAction); @Override void commit(); @Override void rollback(); @Override boolean isTransactional(); }
@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, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); } @Test public void testStoreDequeueCausesException() throws Exception { _message = createTestMessage(true); _queue = createTestAMQQueue(true); _storeTransaction = createTestStoreTransaction(true); _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); _transaction = new AutoCommitTransaction(_transactionLog); try { _transaction.dequeue(mock(MessageEnqueueRecord.class), _action); fail("Exception not thrown"); } catch (RuntimeException re) { } assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); assertTrue("Rollback action must be fired", _action.isRollbackActionFired()); assertFalse("Post commit action must not be fired", _action.isPostCommitActionFired()); } @Test public void testDequeueFromManyNonDurableQueuesOfNonPersistentMessage() throws Exception { _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {false, false, false}); _transaction.dequeue(_queueEntries, _action); assertEquals("Dequeue of non-persistent messages must not cause message to be dequeued", (long) 0, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertEquals("Rollback action must not be fired", false, _action.isRollbackActionFired()); assertEquals("Post commit action must be fired", true, _action.isPostCommitActionFired()); } @Test public void testDequeueFromManyNonDurableQueuesOfPersistentMessage() throws Exception { _queueEntries = createTestQueueEntries(new boolean[] {false, false, false}, new boolean[] {true, true, true}); _transaction.dequeue(_queueEntries, _action); assertEquals( "Dequeue of persistent message from non-durable queues must not cause message to be enqueued", (long) 0, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected transaction state", TransactionState.NOT_STARTED, _storeTransaction.getState()); assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); } @Test public void testDequeueFromDurableAndNonDurableQueuesOfPersistentMessage() throws Exception { _queueEntries = createTestQueueEntries(new boolean[] {true, false, true, true}, new boolean[] {true, true, true, false}); _transaction.dequeue(_queueEntries, _action); assertEquals( "Dequeue of persistent messages from durable/non-durable queues must cause messages to be dequeued", (long) 2, (long) _storeTransaction.getNumberOfDequeuedMessages()); assertEquals("Unexpected transaction state", TransactionState.COMMITTED, _storeTransaction.getState()); assertFalse("Rollback action must not be fired", _action.isRollbackActionFired()); assertTrue("Post commit action must be fired", _action.isPostCommitActionFired()); } @Test public void testStoreDequeuesCauseExceptions() throws Exception { _queueEntries = createTestQueueEntries(new boolean[] {true}, new boolean[] {true}); _storeTransaction = createTestStoreTransaction(true); _transactionLog = MockStoreTransaction.createTestTransactionLog(_storeTransaction); _transaction = new AutoCommitTransaction(_transactionLog); try { _transaction.dequeue(_queueEntries, _action); fail("Exception not thrown"); } catch (RuntimeException re) { } assertEquals("Unexpected transaction state", TransactionState.ABORTED, _storeTransaction.getState()); assertTrue("Rollback action must be fired", _action.isRollbackActionFired()); assertFalse("Post commit action must not be fired", _action.isPostCommitActionFired()); }
AutoCommitTransaction implements ServerTransaction { @Override public void addPostTransactionAction(final Action immediateAction) { immediateAction.postCommit(); } AutoCommitTransaction(MessageStore transactionLog); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addPostTransactionAction(final Action immediateAction); @Override void dequeue(MessageEnqueueRecord record, Action postTransactionAction); @Override void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction); @Override void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void enqueue(Collection<? extends BaseQueue> queues, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void commit(final Runnable immediatePostTransactionAction); @Override void commit(); @Override void rollback(); @Override boolean isTransactional(); }
@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().persist(message.isPersistent())) { LOGGER.debug("Enqueue of message number {} to transaction log. Queue : {}", message.getMessageNumber(), queue.getName()); txn = _messageStore.newTransaction(); enqueueRecord = txn.enqueueMessage(queue, message); future = txn.commitTranAsync(null); txn = null; } else { future = Futures.immediateFuture(null); enqueueRecord = null; } final EnqueueAction underlying = postTransactionAction; addEnqueueFuture(future, new Action() { @Override public void postCommit() { underlying.postCommit(enqueueRecord); } @Override public void onRollback() { underlying.onRollback(); } }, message.isPersistent()); postTransactionAction = null; } finally { final EnqueueAction underlying = postTransactionAction; rollbackIfNecessary(new Action() { @Override public void postCommit() { } @Override public void onRollback() { if(underlying != null) { underlying.onRollback(); } } }, txn); } } AsyncAutoCommitTransaction(MessageStore transactionLog, FutureRecorder recorder); @Override long getTransactionStartTime(); @Override long getTransactionUpdateTime(); @Override void addPostTransactionAction(final Action immediateAction); @Override void dequeue(MessageEnqueueRecord record, Action postTransactionAction); @Override void dequeue(Collection<MessageInstance> queueEntries, Action postTransactionAction); @Override void enqueue(TransactionLogResource queue, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void enqueue(Collection<? extends BaseQueue> queues, EnqueueableMessage message, EnqueueAction postTransactionAction); @Override void commit(final Runnable immediatePostTransactionAction); @Override void commit(); @Override void rollback(); @Override boolean isTransactional(); }
@Test public void testEnqueuePersistentMessagePostCommitNotCalledWhenFutureAlreadyComplete() throws Exception { setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "false"); when(_message.isPersistent()).thenReturn(true); when(_future.isDone()).thenReturn(true); AsyncAutoCommitTransaction asyncAutoCommitTransaction = new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); asyncAutoCommitTransaction.enqueue(_queue, _message, _postTransactionAction); verify(_storeTransaction).enqueueMessage(_queue, _message); verify(_futureRecorder).recordFuture(eq(_future), any(Action.class)); verifyNoInteractions(_postTransactionAction); } @Test public void testEnqueuePersistentMessageOnMultipleQueuesPostCommitNotCalled() throws Exception { setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "false"); when(_message.isPersistent()).thenReturn(true); when(_future.isDone()).thenReturn(true); AsyncAutoCommitTransaction asyncAutoCommitTransaction = new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); asyncAutoCommitTransaction.enqueue(Collections.singletonList(_queue), _message, _postTransactionAction); verify(_storeTransaction).enqueueMessage(_queue, _message); verify(_futureRecorder).recordFuture(eq(_future), any(Action.class)); verifyNoInteractions(_postTransactionAction); } @Test public void testEnqueuePersistentMessagePostCommitNotCalledWhenFutureNotYetComplete() throws Exception { setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "false"); when(_message.isPersistent()).thenReturn(true); when(_future.isDone()).thenReturn(false); AsyncAutoCommitTransaction asyncAutoCommitTransaction = new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); asyncAutoCommitTransaction.enqueue(_queue, _message, _postTransactionAction); verify(_storeTransaction).enqueueMessage(_queue, _message); verify(_futureRecorder).recordFuture(eq(_future), any(Action.class)); verifyNoInteractions(_postTransactionAction); } @Test public void testEnqueueTransientMessagePostCommitIsCalledWhenNotBehavingStrictly() throws Exception { setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "false"); when(_message.isPersistent()).thenReturn(false); AsyncAutoCommitTransaction asyncAutoCommitTransaction = new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); asyncAutoCommitTransaction.enqueue(_queue, _message, _postTransactionAction); verifyNoInteractions(_storeTransaction); verify(_postTransactionAction).postCommit((MessageEnqueueRecord)null); verifyNoInteractions(_futureRecorder); } @Test public void testEnqueueTransientMessagePostCommitIsCalledWhenBehavingStrictly() throws Exception { setTestSystemProperty(STRICT_ORDER_SYSTEM_PROPERTY, "true"); when(_message.isPersistent()).thenReturn(false); AsyncAutoCommitTransaction asyncAutoCommitTransaction = new AsyncAutoCommitTransaction(_messageStore, _futureRecorder); asyncAutoCommitTransaction.enqueue(_queue, _message, _postTransactionAction); verifyNoInteractions(_storeTransaction); verify(_futureRecorder).recordFuture(any(ListenableFuture.class), any(Action.class)); verifyNoInteractions(_postTransactionAction); }
FlowToDiskTransactionObserver implements TransactionObserver { @Override public void onMessageEnqueue(final ServerTransaction transaction, final EnqueueableMessage<? extends StorableMessageMetaData> message) { StoredMessage<? extends StorableMessageMetaData> handle = message.getStoredMessage(); long messageSize = handle.getContentSize() + handle.getMetadataSize(); long newUncommittedSize = _uncommittedMessageSize.addAndGet(messageSize); TransactionDetails details = _uncommittedMessages.computeIfAbsent(transaction, key -> new TransactionDetails()); details.messageEnqueued(handle); if (newUncommittedSize > _maxUncommittedInMemorySize) { try { details.flowToDisk(); } finally { if (!_reported) { _eventLogger.message(_logSubject, ConnectionMessages.LARGE_TRANSACTION_WARN(newUncommittedSize, _maxUncommittedInMemorySize)); _reported = true; } } } } FlowToDiskTransactionObserver(final long maxUncommittedInMemorySize, final LogSubject logSubject, final EventLogger eventLogger); @Override void onMessageEnqueue(final ServerTransaction transaction, final EnqueueableMessage<? extends StorableMessageMetaData> message); @Override void onDischarge(final ServerTransaction transaction); @Override void reset(); }
@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); StoredMessage handle1 = message1.getStoredMessage(); verify(handle1, never()).flowToDisk(); verify(_eventLogger, never()).message(same(_logSubject), any(LogMessage.class)); _flowToDiskMessageObserver.onMessageEnqueue(_transaction, message2); StoredMessage handle2 = message2.getStoredMessage(); verify(handle1).flowToDisk(); verify(handle2).flowToDisk(); verify(_eventLogger).message(same(_logSubject), any(LogMessage.class)); final ServerTransaction transaction2 = mock(ServerTransaction.class); _flowToDiskMessageObserver.onMessageEnqueue(transaction2, message3); StoredMessage handle3 = message2.getStoredMessage(); verify(handle1).flowToDisk(); verify(handle2).flowToDisk(); verify(handle3).flowToDisk(); verify(_eventLogger).message(same(_logSubject), any(LogMessage.class)); }
FlowToDiskTransactionObserver implements TransactionObserver { @Override public void onDischarge(final ServerTransaction transaction) { TransactionDetails transactionDetails = _uncommittedMessages.remove(transaction); if (transactionDetails != null) { _uncommittedMessageSize.addAndGet(-transactionDetails.getUncommittedMessageSize()); } if (_maxUncommittedInMemorySize > _uncommittedMessageSize.get()) { _reported = false; } } FlowToDiskTransactionObserver(final long maxUncommittedInMemorySize, final LogSubject logSubject, final EventLogger eventLogger); @Override void onMessageEnqueue(final ServerTransaction transaction, final EnqueueableMessage<? extends StorableMessageMetaData> message); @Override void onDischarge(final ServerTransaction transaction); @Override void reset(); }
@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 ServerTransaction transaction2 = mock(ServerTransaction.class); _flowToDiskMessageObserver.onMessageEnqueue(transaction2, message2); _flowToDiskMessageObserver.onDischarge(_transaction); _flowToDiskMessageObserver.onMessageEnqueue(transaction2, message3); StoredMessage handle1 = message1.getStoredMessage(); StoredMessage handle2 = message2.getStoredMessage(); StoredMessage handle3 = message2.getStoredMessage(); verify(handle1, never()).flowToDisk(); verify(handle2, never()).flowToDisk(); verify(handle3, never()).flowToDisk(); verify(_eventLogger, never()).message(same(_logSubject), any(LogMessage.class)); }
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.BindingIdentifier getBinding(); boolean matches(AMQMessageHeader headers); boolean matches(Filterable message); @Override boolean equals(final Object o); @Override int hashCode(); String getReplacementRoutingKey(); }
@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 void testDefault_2() throws Exception { bindHeaders.put("A", "Value of A"); matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertTrue(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testDefault_3() throws Exception { bindHeaders.put("A", "Value of A"); matchHeaders.setString("A", "Altered value of A"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertFalse(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testAll_1() throws Exception { bindHeaders.put("X-match", "all"); 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 void testAll_2() throws Exception { bindHeaders.put("X-match", "all"); bindHeaders.put("A", "Value of A"); bindHeaders.put("B", "Value of B"); matchHeaders.setString("A", "Value of A"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertFalse(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testAll_3() throws Exception { bindHeaders.put("X-match", "all"); bindHeaders.put("A", "Value of A"); bindHeaders.put("B", "Value of B"); matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertTrue(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testAll_4() throws Exception { bindHeaders.put("X-match", "all"); bindHeaders.put("A", "Value of A"); bindHeaders.put("B", "Value of B"); matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); matchHeaders.setString("C", "Value of C"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertTrue(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testAll_5() throws Exception { bindHeaders.put("X-match", "all"); bindHeaders.put("A", "Value of A"); bindHeaders.put("B", "Value of B"); matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Altered value of B"); matchHeaders.setString("C", "Value of C"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertFalse(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testAny_1() throws Exception { bindHeaders.put("X-match", "any"); 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 void testAny_2() throws Exception { bindHeaders.put("X-match", "any"); bindHeaders.put("A", "Value of A"); bindHeaders.put("B", "Value of B"); matchHeaders.setString("A", "Value of A"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertTrue(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testAny_3() throws Exception { bindHeaders.put("X-match", "any"); bindHeaders.put("A", "Value of A"); bindHeaders.put("B", "Value of B"); matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertTrue(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testAny_4() throws Exception { bindHeaders.put("X-match", "any"); bindHeaders.put("A", "Value of A"); bindHeaders.put("B", "Value of B"); matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Value of B"); matchHeaders.setString("C", "Value of C"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertTrue(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testAny_5() throws Exception { bindHeaders.put("X-match", "any"); bindHeaders.put("A", "Value of A"); bindHeaders.put("B", "Value of B"); matchHeaders.setString("A", "Value of A"); matchHeaders.setString("B", "Altered value of B"); matchHeaders.setString("C", "Value of C"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertTrue(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); } @Test public void testAny_6() throws Exception { bindHeaders.put("X-match", "any"); bindHeaders.put("A", "Value of A"); bindHeaders.put("B", "Value of B"); matchHeaders.setString("A", "Altered value of A"); matchHeaders.setString("B", "Altered value of B"); matchHeaders.setString("C", "Value of C"); AbstractExchange.BindingIdentifier b = new AbstractExchange.BindingIdentifier(getQueueName(), _queue); assertFalse(new HeadersBinding(b, bindHeaders).matches(matchHeaders)); }
ConnectionVersionValidator implements ConnectionValidator { @Override public boolean validateConnectionCreation(final AMQPConnection<?> connection, final QueueManagingVirtualHost<?> virtualHost) { String connectionVersion = connection.getClientVersion(); if (connectionVersion == null) { connectionVersion = ""; } boolean valid = true; if (!connectionMatches(virtualHost, VIRTUALHOST_ALLOWED_CONNECTION_VERSION, connectionVersion)) { if (connectionMatches(virtualHost, VIRTUALHOST_LOGGED_CONNECTION_VERSION, connectionVersion)) { virtualHost.getBroker().getEventLogger().message(ConnectionMessages.CLIENT_VERSION_LOG(connection.getClientVersion())); } else if (connectionMatches(virtualHost, VIRTUALHOST_REJECTED_CONNECTION_VERSION, connectionVersion)) { virtualHost.getBroker().getEventLogger().message(ConnectionMessages.CLIENT_VERSION_REJECT(connection.getClientVersion())); valid = false; } } return valid; } ConnectionVersionValidator(); @Override boolean validateConnectionCreation(final AMQPConnection<?> connection, final QueueManagingVirtualHost<?> virtualHost); @Override String getType(); static final String VIRTUALHOST_ALLOWED_CONNECTION_VERSION; static final String VIRTUALHOST_LOGGED_CONNECTION_VERSION; static final String VIRTUALHOST_REJECTED_CONNECTION_VERSION; }
@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(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_REJECT("foo")); } @Test public void testNullClientDefaultAllowed() { assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); } @Test public void testClientDefaultAllowed() { when(_connectionMock.getClientVersion()).thenReturn("foo"); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); } @Test public void testEmptyList() { Map<String, List<String>> contextValues = new HashMap<>(); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Collections.<String>emptyList()); setContextValues(contextValues); when(_connectionMock.getClientVersion()).thenReturn("foo"); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock, never()).message(any(LogMessage.class)); } @Test public void testEmptyString() { Map<String, List<String>> contextValues = new HashMap<>(); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList("")); setContextValues(contextValues); when(_connectionMock.getClientVersion()).thenReturn(""); assertFalse(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_REJECT("")); when(_connectionMock.getClientVersion()).thenReturn(null); assertFalse(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_REJECT("")); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_REJECT(null)); } @Test public void testClientRejected() { when(_connectionMock.getClientVersion()).thenReturn("foo"); Map<String, List<String>> contextValues = new HashMap<>(); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList("foo")); setContextValues(contextValues); assertFalse(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_REJECT("foo")); } @Test public void testClientLogged() { when(_connectionMock.getClientVersion()).thenReturn("foo"); Map<String, List<String>> contextValues = new HashMap<>(); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("foo")); setContextValues(contextValues); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_LOG("foo")); } @Test public void testAllowedTakesPrecedence() { when(_connectionMock.getClientVersion()).thenReturn("foo"); Map<String, List<String>> contextValues = new HashMap<>(); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_ALLOWED_CONNECTION_VERSION, Arrays.asList("foo")); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("foo")); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList("foo")); setContextValues(contextValues); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock, never()).message(any(LogMessage.class)); } @Test public void testLoggedTakesPrecedenceOverRejected() { when(_connectionMock.getClientVersion()).thenReturn("foo"); Map<String, List<String>> contextValues = new HashMap<>(); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("foo")); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_REJECTED_CONNECTION_VERSION, Arrays.asList("foo")); setContextValues(contextValues); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_LOG("foo")); } @Test public void testRegex() { Map<String, List<String>> contextValues = new HashMap<>(); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_ALLOWED_CONNECTION_VERSION, Arrays.asList("foo")); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("f.*")); setContextValues(contextValues); when(_connectionMock.getClientVersion()).thenReturn("foo"); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock, never()).message(any(LogMessage.class)); when(_connectionMock.getClientVersion()).thenReturn("foo2"); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_LOG("foo2")); when(_connectionMock.getClientVersion()).thenReturn("baz"); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock, never()).message(ConnectionMessages.CLIENT_VERSION_LOG("baz")); } @Test public void testRegexLists() { Map<String, List<String>> contextValues = new HashMap<>(); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_ALLOWED_CONNECTION_VERSION, Arrays.asList("foo")); contextValues.put(ConnectionVersionValidator.VIRTUALHOST_LOGGED_CONNECTION_VERSION, Arrays.asList("f.*", "baz")); setContextValues(contextValues); when(_connectionMock.getClientVersion()).thenReturn("foo"); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock, never()).message(any(LogMessage.class)); when(_connectionMock.getClientVersion()).thenReturn("foo2"); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_LOG("foo2")); when(_connectionMock.getClientVersion()).thenReturn("baz"); assertTrue(_connectionValidator.validateConnectionCreation(_connectionMock, _virtualHostMock)); verify(_eventLoggerMock).message(ConnectionMessages.CLIENT_VERSION_LOG("baz")); }
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<>(Arrays.asList(supportedEntries)); for (String allowListedRegEx : allowList) { Iterator<String> supportedIter = supportedList.iterator(); while (supportedIter.hasNext()) { String supportedEntry = supportedIter.next(); if (supportedEntry.matches(allowListedRegEx)) { filteredList.add(supportedEntry); supportedIter.remove(); } } } } else { filteredList = new ArrayList<>(Arrays.asList(enabledEntries)); } if (denyList != null && !denyList.isEmpty()) { for (String denyListedRegEx : denyList) { Iterator<String> entriesIter = filteredList.iterator(); while (entriesIter.hasNext()) { if (entriesIter.next().matches(denyListedRegEx)) { entriesIter.remove(); } } } } return filteredList.toArray(new String[filteredList.size()]); } private SSLUtil(); static CertificateFactory getCertificateFactory(); static void verifyHostname(SSLEngine engine,String hostnameExpected); static void verifyHostname(final String hostnameExpected, final X509Certificate cert); static boolean checkHostname(String hostname, X509Certificate cert); static String getIdFromSubjectDN(String dn); static String retrieveIdentity(SSLEngine engine); static KeyStore getInitializedKeyStore(String storePath, String storePassword, String keyStoreType); static KeyStore getInitializedKeyStore(URL storePath, String storePassword, String keyStoreType); static X509Certificate[] readCertificates(URL certFile); static X509Certificate[] readCertificates(InputStream input); static PrivateKey readPrivateKey(final URL url); static PrivateKey readPrivateKey(InputStream input); static PrivateKey readPrivateKey(final byte[] content, final String algorithm); static void updateEnabledTlsProtocols(final SSLEngine engine, final List<String> protocolAllowList, final List<String> protocolDenyList); static void updateEnabledTlsProtocols(final SSLSocket socket, final List<String> protocolAllowList, final List<String> protocolDenyList); static String[] filterEnabledProtocols(final String[] enabledProtocols, final String[] supportedProtocols, final List<String> protocolAllowList, final List<String> protocolDenyList); static String[] filterEnabledCipherSuites(final String[] enabledCipherSuites, final String[] supportedCipherSuites, final List<String> cipherSuiteAllowList, final List<String> cipherSuiteDenyList); static void updateEnabledCipherSuites(final SSLEngine engine, final List<String> cipherSuitesAllowList, final List<String> cipherSuitesDenyList); static void updateEnabledCipherSuites(final SSLSocket socket, final List<String> cipherSuitesAllowList, final List<String> cipherSuitesDenyList); static SSLContext tryGetSSLContext(); static SSLContext tryGetSSLContext(final String[] protocols); static boolean isSufficientToDetermineClientSNIHost(QpidByteBuffer buffer); final static String getServerNameFromTLSClientHello(QpidByteBuffer source); static SSLContext createSslContext(final org.apache.qpid.server.model.KeyStore keyStore, final Collection<TrustStore> trustStores, final String portName); static boolean canGenerateCerts(); static KeyCertPair generateSelfSignedCertificate(final String keyAlgorithm, final String signatureAlgorithm, final int keyLength, long startTime, long duration, String x500Name, Set<String> dnsNames, Set<InetAddress> addresses); static Collection<Certificate> getCertificates(final KeyStore ks); }
@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) result.length); } @Test public void testFilterEntries_allowListNotEmpty_denyListEmpty() { List<String> allowList = Arrays.asList("TLSv1\\.[0-9]+"); List<String> denyList = Collections.emptyList(); String[] enabled = {"TLS", "TLSv1.1", "TLSv1.2", "TLSv1.3"}; String[] expected = {"TLSv1.1", "TLSv1.2", "TLSv1.3"}; String[] supported = {"SSLv3", "TLS", "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"}; String[] result = SSLUtil.filterEntries(enabled, supported, allowList, denyList); assertTrue("unexpected filtered list: expected " + Arrays.toString(expected) + " actual " + Arrays.toString( result), Arrays.equals(expected, result)); } @Test public void testFilterEntries_allowListEmpty_denyListNotEmpty() { List<String> allowList = Arrays.asList(); List<String> denyList = Arrays.asList("TLSv1\\.[0-9]+"); String[] enabled = {"TLS", "TLSv1.1", "TLSv1.2", "TLSv1.3"}; String[] expected = {"TLS"}; String[] supported = {"SSLv3", "TLS", "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"}; String[] result = SSLUtil.filterEntries(enabled, supported, allowList, denyList); assertTrue("unexpected filtered list: expected " + Arrays.toString(expected) + " actual " + Arrays.toString( result), Arrays.equals(expected, result)); } @Test public void testFilterEntries_respectOrder() { List<String> allowList = Arrays.asList("b", "c", "a"); List<String> denyList = Collections.emptyList(); String[] enabled = {"x"}; String[] expected = {"b", "c", "a"}; String[] supported = {"x", "c", "a", "xx", "b", "xxx"}; String[] result = SSLUtil.filterEntries(enabled, supported, allowList, denyList); assertTrue("unexpected filtered list: expected " + Arrays.toString(expected) + " actual " + Arrays.toString( result), Arrays.equals(expected, result)); allowList = Arrays.asList("c", "b", "a"); expected = new String[]{"c", "b", "a"}; result = SSLUtil.filterEntries(enabled, supported, allowList, denyList); assertTrue("unexpected filtered list: expected " + Arrays.toString(expected) + " actual " + Arrays.toString( result), Arrays.equals(expected, result)); } @Test public void testFilterEntries_denyListAppliesToAllowList() { List<String> allowList = Arrays.asList("a", "b"); List<String> denyList = Arrays.asList("a"); String[] enabled = {"a", "b", "c"}; String[] expected = {"b"}; String[] supported = {"a", "b", "c", "x"}; String[] result = SSLUtil.filterEntries(enabled, supported, allowList, denyList); assertTrue("unexpected filtered list: expected " + Arrays.toString(expected) + " actual " + Arrays.toString( result), Arrays.equals(expected, result)); } @Test public void testFilterEntries_allowListIgnoresEnabled() { List<String> allowList = Arrays.asList("b"); List<String> denyList = Collections.emptyList(); String[] enabled = {"a"}; String[] expected = {"b"}; String[] supported = {"a", "b", "x"}; String[] result = SSLUtil.filterEntries(enabled, supported, allowList, denyList); assertTrue("unexpected filtered list: expected " + Arrays.toString(expected) + " actual " + Arrays.toString( result), Arrays.equals(expected, result)); }
RollingPolicyDecorator implements RollingPolicy { @Override public void rollover() throws RolloverFailure { ScanTask task = createScanTaskAndCancelInProgress(); _decorated.rollover(); _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; }
@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.rollover(); verify(_delegate).rollover(); ArgumentMatcher<String[]> matcher = getMatcher(new String[]{_testFile.getName()}); verify(_listener).onRollover(eq(_baseFolder.toPath()), argThat(matcher)); } @Test public void testRolloverRescanLimit() throws IOException { _policy.rollover(); verify(_delegate).rollover(); ArgumentMatcher<String[]> matcher = getMatcher(new String[]{_testFile.getName()}); verify(_listener).onRollover(eq(_baseFolder.toPath()), argThat(matcher)); _policy.rollover(); verify(_delegate, times(2)).rollover(); verify(_listener).onNoRolloverDetected(eq(_baseFolder.toPath()), argThat(matcher)); } @Test public void testSequentialRollover() throws IOException { _policy.rollover(); verify(_delegate).rollover(); ArgumentMatcher<String[]> matcher = getMatcher(new String[]{ _testFile.getName() }); verify(_listener).onRollover(eq(_baseFolder.toPath()), argThat(matcher)); File secondFile = createTestFile("test.2015-06-25.1.gz"); _policy.rollover(); verify(_delegate, times(2)).rollover(); ArgumentMatcher<String[]> matcher2 = getMatcher(new String[]{_testFile.getName(), secondFile.getName()}); verify(_listener).onRollover(eq(_baseFolder.toPath()), argThat(matcher2)); }
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(rdn.getType())) { if(dcStr == null) { dcStr = rdn.getValue().toString(); } else { dcStr = rdn.getValue().toString() + '.' + dcStr; } } } return cnStr == null || cnStr.length()==0 ? "" : dcStr == null ? cnStr : cnStr + '@' + dcStr; } catch (InvalidNameException e) { LOGGER.warn("Invalid name: '{}'", dn); return ""; } } } private SSLUtil(); static CertificateFactory getCertificateFactory(); static void verifyHostname(SSLEngine engine,String hostnameExpected); static void verifyHostname(final String hostnameExpected, final X509Certificate cert); static boolean checkHostname(String hostname, X509Certificate cert); static String getIdFromSubjectDN(String dn); static String retrieveIdentity(SSLEngine engine); static KeyStore getInitializedKeyStore(String storePath, String storePassword, String keyStoreType); static KeyStore getInitializedKeyStore(URL storePath, String storePassword, String keyStoreType); static X509Certificate[] readCertificates(URL certFile); static X509Certificate[] readCertificates(InputStream input); static PrivateKey readPrivateKey(final URL url); static PrivateKey readPrivateKey(InputStream input); static PrivateKey readPrivateKey(final byte[] content, final String algorithm); static void updateEnabledTlsProtocols(final SSLEngine engine, final List<String> protocolAllowList, final List<String> protocolDenyList); static void updateEnabledTlsProtocols(final SSLSocket socket, final List<String> protocolAllowList, final List<String> protocolDenyList); static String[] filterEnabledProtocols(final String[] enabledProtocols, final String[] supportedProtocols, final List<String> protocolAllowList, final List<String> protocolDenyList); static String[] filterEnabledCipherSuites(final String[] enabledCipherSuites, final String[] supportedCipherSuites, final List<String> cipherSuiteAllowList, final List<String> cipherSuiteDenyList); static void updateEnabledCipherSuites(final SSLEngine engine, final List<String> cipherSuitesAllowList, final List<String> cipherSuitesDenyList); static void updateEnabledCipherSuites(final SSLSocket socket, final List<String> cipherSuitesAllowList, final List<String> cipherSuitesDenyList); static SSLContext tryGetSSLContext(); static SSLContext tryGetSSLContext(final String[] protocols); static boolean isSufficientToDetermineClientSNIHost(QpidByteBuffer buffer); final static String getServerNameFromTLSClientHello(QpidByteBuffer source); static SSLContext createSslContext(final org.apache.qpid.server.model.KeyStore keyStore, final Collection<TrustStore> trustStores, final String portName); static boolean canGenerateCerts(); static KeyCertPair generateSelfSignedCertificate(final String keyAlgorithm, final String signatureAlgorithm, final int keyLength, long startTime, long duration, String x500Name, Set<String> dnsNames, Set<InetAddress> addresses); static Collection<Certificate> getCertificates(final KeyStore ks); }
@Test public void testGetIdFromSubjectDN() { assertEquals("[email protected]", SSLUtil.getIdFromSubjectDN("cn=user,dc=somewhere,dc=example,dc=org")); assertEquals("[email protected]", SSLUtil.getIdFromSubjectDN("DC=somewhere, dc=example,cn=\"user2\",dc=org")); assertEquals("[email protected]", SSLUtil.getIdFromSubjectDN("DC=somewhere, dc=example,cn=\"user\",dc=org, cn=user2")); assertEquals("", SSLUtil.getIdFromSubjectDN("DC=somewhere, dc=example,dc=org")); assertEquals("", SSLUtil.getIdFromSubjectDN("C=CZ,O=Scholz,OU=\"JAKUB CN=USER1\"")); assertEquals("someone", SSLUtil.getIdFromSubjectDN("ou=someou, CN=\"someone\"")); assertEquals("", SSLUtil.getIdFromSubjectDN(null)); assertEquals("", SSLUtil.getIdFromSubjectDN("ou=someou, =")); assertEquals("[email protected]", SSLUtil.getIdFromSubjectDN("CN=me,DC=example, DC=com, O=My Company Ltd, L=Newbury, ST=Berkshire, C=GB")); assertEquals("", SSLUtil.getIdFromSubjectDN("CN=,DC=somewhere, dc=example,dc=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,String hostnameExpected); static void verifyHostname(final String hostnameExpected, final X509Certificate cert); static boolean checkHostname(String hostname, X509Certificate cert); static String getIdFromSubjectDN(String dn); static String retrieveIdentity(SSLEngine engine); static KeyStore getInitializedKeyStore(String storePath, String storePassword, String keyStoreType); static KeyStore getInitializedKeyStore(URL storePath, String storePassword, String keyStoreType); static X509Certificate[] readCertificates(URL certFile); static X509Certificate[] readCertificates(InputStream input); static PrivateKey readPrivateKey(final URL url); static PrivateKey readPrivateKey(InputStream input); static PrivateKey readPrivateKey(final byte[] content, final String algorithm); static void updateEnabledTlsProtocols(final SSLEngine engine, final List<String> protocolAllowList, final List<String> protocolDenyList); static void updateEnabledTlsProtocols(final SSLSocket socket, final List<String> protocolAllowList, final List<String> protocolDenyList); static String[] filterEnabledProtocols(final String[] enabledProtocols, final String[] supportedProtocols, final List<String> protocolAllowList, final List<String> protocolDenyList); static String[] filterEnabledCipherSuites(final String[] enabledCipherSuites, final String[] supportedCipherSuites, final List<String> cipherSuiteAllowList, final List<String> cipherSuiteDenyList); static void updateEnabledCipherSuites(final SSLEngine engine, final List<String> cipherSuitesAllowList, final List<String> cipherSuitesDenyList); static void updateEnabledCipherSuites(final SSLSocket socket, final List<String> cipherSuitesAllowList, final List<String> cipherSuitesDenyList); static SSLContext tryGetSSLContext(); static SSLContext tryGetSSLContext(final String[] protocols); static boolean isSufficientToDetermineClientSNIHost(QpidByteBuffer buffer); final static String getServerNameFromTLSClientHello(QpidByteBuffer source); static SSLContext createSslContext(final org.apache.qpid.server.model.KeyStore keyStore, final Collection<TrustStore> trustStores, final String portName); static boolean canGenerateCerts(); static KeyCertPair generateSelfSignedCertificate(final String keyAlgorithm, final String signatureAlgorithm, final int keyLength, long startTime, long duration, String x500Name, Set<String> dnsNames, Set<InetAddress> addresses); static Collection<Certificate> getCertificates(final KeyStore ks); }
@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.readCertificates(certificateURL); assertEquals("Unexpected number of certificates", 1, certificates.length); assertEquals("Unexpected certificate", certificate, certificates[0]); }
TransactionTimeoutTicker implements Ticker, SchedulingDelayNotificationListener { @Override public void notifySchedulingDelay(final long schedulingDelay) { if (schedulingDelay > 0) { long accumulatedSchedulingDelay; do { accumulatedSchedulingDelay = _accumulatedSchedulingDelay.get(); } while (!_accumulatedSchedulingDelay.compareAndSet(accumulatedSchedulingDelay, accumulatedSchedulingDelay + schedulingDelay)); } } TransactionTimeoutTicker(long timeoutValue, long notificationRepeatPeriod, Supplier<Long> timeStampSupplier, Action<Long> notification); @Override int getTimeToNextTick(final long currentTime); @Override int tick(final long currentTime); @Override void notifySchedulingDelay(final long schedulingDelay); }
@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, _dateSupplier, _notificationAction); _ticker.notifySchedulingDelay(10); final int expected = 20; assertTickTime("Unexpected ticker value when transaction is in-progress", expected, timeNow, _ticker); verify(_notificationAction, never()).performAction(anyLong()); } @Test public void testTicksDuringManyTransactionsWithSchedulingDelay() throws Exception { long timeNow = System.currentTimeMillis(); final long firstTransactionTime = timeNow - 10; when(_dateSupplier.get()).thenReturn(firstTransactionTime); _ticker = new TransactionTimeoutTicker(_timeoutValue, _notificationRepeatPeriod, _dateSupplier, _notificationAction); _ticker.notifySchedulingDelay(5); final int expectedTickForFirstTransaction = 95; assertTickTime("Unexpected ticker value for first transaction", expectedTickForFirstTransaction, timeNow, _ticker); timeNow += 100; final long secondTransactionTime = timeNow - 5; when(_dateSupplier.get()).thenReturn(secondTransactionTime); final int expectedTickForSecondTransaction = 95; assertTickTime("Unexpected ticker value for second transaction", expectedTickForSecondTransaction, timeNow, _ticker); verify(_notificationAction, never()).performAction(anyLong()); }
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>() { @Override public Object run() throws Exception { _listener.beforeStartup(); try { startupImpl(systemConfigAttributes); } catch (RuntimeException e) { systemOutMessageLogger.message(new SystemStartupMessage(e)); LOGGER.error("Exception during startup", e); _listener.errorOnStartup(e); closeSystemConfigAndCleanUp(); } finally { _listener.afterStartup(); } return null; } }); } SystemLauncher(SystemLauncherListener listener); SystemLauncher(SystemLauncherListener... listeners); SystemLauncher(); static void populateSystemPropertiesFromDefaults(final String initialProperties); Principal getSystemPrincipal(); void shutdown(); void shutdown(int exitStatusCode); void startup(final Map<String,Object> systemConfigAttributes); }
@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, _initialConfiguration.getAbsolutePath()); attributes.put(SystemConfig.TYPE, JsonSystemConfigImpl.SYSTEM_CONFIG_TYPE); attributes.put(SystemConfig.STARTUP_LOGGED_TO_SYSTEM_OUT, Boolean.TRUE); _systemLauncher = new SystemLauncher(); _systemLauncher.startup(attributes); assertEquals("Unexpected JVM system property", INITIAL_SYSTEM_PROPERTY_VALUE, System.getProperty(INITIAL_SYSTEM_PROPERTY)); assertEquals("Unexpected QPID_WORK system property", _brokerWork.getAbsolutePath(), System.getProperty("QPID_WORK")); }
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); static byte[] uncompressBufferToArray(ByteBuffer contentBuffer); static byte[] uncompressStreamToArray(InputStream stream); static final String GZIP_CONTENT_ENCODING; }
@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 { assertNull("Null buffer should return null", GZIPUtils.uncompressBufferToArray(null)); }
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)) != -1) { inflatedContent.write(buf, 0, read); } return inflatedContent.toByteArray(); } catch (IOException e) { LOGGER.warn("Unexpected IOException when attempting to uncompress with gzip", e); } } return null; } static byte[] compressBufferToArray(ByteBuffer input); static byte[] uncompressBufferToArray(ByteBuffer contentBuffer); static byte[] uncompressStreamToArray(InputStream stream); static final String GZIP_CONTENT_ENCODING; }
@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 testUncompressNullStreamReturnsNull() throws Exception { assertNull("Null Stream should return null", GZIPUtils.uncompressStreamToArray(null)); }
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(), input.arrayOffset() + input.position(), input.remaining()); } else { byte[] data = new byte[input.remaining()]; input.duplicate().get(data); gzipOutputStream.write(data); } } return compressedBuffer.toByteArray(); } catch (IOException e) { LOGGER.warn("Unexpected IOException when attempting to compress with gzip", e); } } return null; } static byte[] compressBufferToArray(ByteBuffer input); static byte[] uncompressBufferToArray(ByteBuffer contentBuffer); static byte[] uncompressStreamToArray(InputStream stream); static final String GZIP_CONTENT_ENCODING; }
@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, BaseAction<File, IOException> write); Path createNewFile(File newFile, String posixFileAttributes); Path createNewFile(Path newFile, String posixFileAttributes); Path createNewFile(Path newFile, Set<PosixFilePermission> permissions); boolean isPosixFileSystem(Path path); Path atomicFileMoveOrReplace(Path sourceFile, Path targetFile); boolean isWritableDirectory(String path); }
@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) != null) { assertPermissions(path); } } @Test public void testCreateNewFileUsingRelativePath() throws Exception { _testFile = new File("./tmp-" + System.currentTimeMillis()); 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) != null) { assertPermissions(path); } }
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 targetFile, BaseAction<File, IOException> operation); void writeFileSafely(Path targetFile, Path backupFile, Path tmpFile, BaseAction<File, IOException> write); Path createNewFile(File newFile, String posixFileAttributes); Path createNewFile(Path newFile, String posixFileAttributes); Path createNewFile(Path newFile, Set<PosixFilePermission> permissions); boolean isPosixFileSystem(Path path); Path atomicFileMoveOrReplace(Path sourceFile, Path targetFile); boolean isWritableDirectory(String path); }
@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")); assertEquals("Unexpected name", _testFile.getAbsolutePath() + ".tmp", file.getPath()); } }); assertTrue("File was not created", path.toFile().exists()); if (Files.getFileAttributeView(path, PosixFileAttributeView.class) != null) { assertPermissions(path); } String content = new String(Files.readAllBytes(path), "UTF-8"); assertEquals("Unexpected file content", "test", content); }
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())) { return targetFile; } else { throw new RuntimeException("Atomic move is unsupported and rename from : '" + sourceFile + "' to: '" + targetFile + "' failed."); } } } void writeFileSafely(Path targetFile, BaseAction<File, IOException> operation); void writeFileSafely(Path targetFile, Path backupFile, Path tmpFile, BaseAction<File, IOException> write); Path createNewFile(File newFile, String posixFileAttributes); Path createNewFile(Path newFile, String posixFileAttributes); Path createNewFile(Path newFile, Set<PosixFilePermission> permissions); boolean isPosixFileSystem(Path path); Path atomicFileMoveOrReplace(Path sourceFile, Path targetFile); boolean isWritableDirectory(String path); }
@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 was not moved", path.toFile().exists()); assertTrue("Target file does not exist", _testFile.exists()); if (Files.getFileAttributeView(_testFile.toPath(), PosixFileAttributeView.class) != null) { assertPermissions(_testFile.toPath()); } }
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()); } return storePath.canWrite(); } void writeFileSafely(Path targetFile, BaseAction<File, IOException> operation); void writeFileSafely(Path targetFile, Path backupFile, Path tmpFile, BaseAction<File, IOException> write); Path createNewFile(File newFile, String posixFileAttributes); Path createNewFile(Path newFile, String posixFileAttributes); Path createNewFile(Path newFile, Set<PosixFilePermission> permissions); boolean isPosixFileSystem(Path path); Path atomicFileMoveOrReplace(Path sourceFile, Path targetFile); boolean isWritableDirectory(String path); }
@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.setWritable(false, false)) { assertFalse("Should return false for non writable folder", _fileHelper.isWritableDirectory(new File(file, "test").getAbsolutePath())); } } } finally { FileUtils.delete(workDir, true); } }
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)); } builder.append(String.format(" %02x", buf.get(p))); count++; } builder.append(String.format("%n")); builder.append(String.format("%07x%n", count)); return builder.toString(); } private Strings(); static final byte[] toUTF8(String str); static final String fromUTF8(byte[] bytes); static Resolver chain(Resolver... resolvers); static byte[] decodePrivateBase64(String base64String, String description); static byte[] decodeBase64(String base64String); static final String expand(String input); static final String expand(String input, Resolver resolver); static final String expand(String input, boolean failOnUnresolved, Resolver... resolvers); static final String join(String sep, Iterable items); static final String join(String sep, Object[] items); static final List<String> split(String listAsString); static String printMap(Map<String,Object> map); static Resolver createSubstitutionResolver(String prefix, LinkedHashMap<String,String> substitutions); static String hexDump(ByteBuffer buf); static final Resolver ENV_VARS_RESOLVER; static final Resolver JAVA_SYS_PROPS_RESOLVER; static final Resolver SYSTEM_RESOLVER; }
@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 32 33 34 35 36 37 38%n" + "0000010 39%n" + "0000011%n"); String actual = Strings.hexDump(ByteBuffer.wrap("12345678123456789".getBytes())); assertThat(actual, is(equalTo(expected))); }
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()) .append('\n'); } return result.toString(); } CommandLineParser(String[][] config); String getErrors(); String getOptionsInForce(); String getUsage(); void setErrorsOnUnknowns(boolean errors); Properties parseCommandLine(String[] args); void addCommandLineToProperties(Properties properties); void reset(); static Properties processCommandLine(String[] args, CommandLineParser commandLine, Properties properties); }
@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$" } }); assertTrue("The options in force method did not return an empty string.", "".equals(parser.getOptionsInForce())); }
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[][] config); String getErrors(); String getOptionsInForce(); String getUsage(); void setErrorsOnUnknowns(boolean errors); Properties parseCommandLine(String[] args); void addCommandLineToProperties(Properties properties); void reset(); static Properties processCommandLine(String[] args, CommandLineParser commandLine, Properties properties); }
@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 = !((parser.getUsage() == null) || "".equals(parser.getUsage())); assertTrue("The usage method did not return a non empty string.", 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 (Iterator<String> i = optionMap.keySet().iterator(); i.hasNext();) { String nextOption = i.next(); boolean notFree = false; try { Integer.parseInt(nextOption); } catch (NumberFormatException e) { notFree = true; } if (notFree) { regexp.append(nextOption) .append(i.hasNext() ? "|" : ""); optionsAdded++; } } regexp.append(')') .append(((optionsAdded > 0) ? "?" : "")) .append("(.*)"); Pattern pattern = Pattern.compile(regexp.toString()); for (int i = 0; i < args.length; i++) { if (args[i].startsWith("-")) { String arg = args[i].substring(1); optionMatcher = pattern.matcher(arg); optionMatcher.matches(); String matchedOption = optionMatcher.group(1); String matchedArg = optionMatcher.group(2); if ((matchedOption != null) && !"".equals(matchedOption)) { CommandLineOption optionInfo = optionMap.get(matchedOption); if (optionInfo.expectsArgs) { expectingArgs = true; optionExpectingArgs = matchedOption; } if ("".equals(matchedArg) && !optionInfo.expectsArgs) { options.put(matchedOption, "true"); } else if (!"".equals(matchedArg)) { if (!optionInfo.expectsArgs) { options.put(matchedOption, "true"); do { optionMatcher = pattern.matcher(matchedArg); optionMatcher.matches(); matchedOption = optionMatcher.group(1); matchedArg = optionMatcher.group(2); if (matchedOption != null) { optionInfo = optionMap.get(matchedOption); if (optionInfo.expectsArgs == true) { parsingErrors.add("Option " + matchedOption + " cannot be combined with flags.\n"); } options.put(matchedOption, "true"); } else { parsingErrors.add("Illegal argument to a flag in the option " + arg + "\n"); break; } } while (!"".equals(matchedArg)); } else { checkArgumentFormat(optionInfo, matchedArg); options.put(matchedOption, matchedArg); expectingArgs = false; } } } else { if (errorsOnUnknowns) { parsingErrors.add("Option " + matchedOption + " is not a recognized option.\n"); } } } else { if (expectingArgs) { CommandLineOption optionInfo = optionMap.get(optionExpectingArgs); checkArgumentFormat(optionInfo, args[i]); options.put(optionExpectingArgs, args[i]); expectingArgs = false; optionExpectingArgs = null; } else { CommandLineOption optionInfo = optionMap.get(Integer.toString(free)); if (optionInfo != null) { checkArgumentFormat(optionInfo, args[i]); } options.put(Integer.toString(free), args[i]); free++; } } } for (CommandLineOption optionInfo : optionMap.values()) { if (!optionInfo.expectsArgs) { if (!options.containsKey(optionInfo.option)) { options.put(optionInfo.option, "false"); } } else if (optionInfo.mandatory && !options.containsKey(optionInfo.option)) { parsingErrors.add("Option -" + optionInfo.option + " is mandatory but not was not specified.\n"); } } if (!parsingErrors.isEmpty()) { throw new IllegalArgumentException(); } options = takeFreeArgsAsProperties(options, 1); parsedProperties = options; return options; } CommandLineParser(String[][] config); String getErrors(); String getOptionsInForce(); String getUsage(); void setErrorsOnUnknowns(boolean errors); Properties parseCommandLine(String[] args); void addCommandLineToProperties(Properties properties); void reset(); static Properties processCommandLine(String[] args, CommandLineParser commandLine, Properties properties); }
@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 \"true\", it was: " + testProps.get("t1"), "true".equals(testProps.get("t1"))); assertTrue("The t2 flag was not \"true\", it was: " + testProps.get("t2"), "true".equals(testProps.get("t2"))); assertTrue("The t3 flag was not \"true\", it was: " + testProps.get("t3"), "true".equals(testProps.get("t3"))); } @Test public void testParseFlagCondensedWithOptionFails() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "t1", "Test Flag 1." }, { "t2", "Test Option 2.", "test" } }); boolean testPassed = false; try { Properties testProps = parser.parseCommandLine(new String[] { "-t1t2" }); } catch (IllegalArgumentException e) { testPassed = true; } assertTrue("IllegalArgumentException not thrown when a flag and option are condensed together.", testPassed); } @Test public void testParseFormattedFreeArgumentFailsBadArgument() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "1", "Test Free Argument.", "test", null, "^test$" } }); boolean testPassed = false; try { Properties testProps = parser.parseCommandLine(new String[] { "fail" }); } catch (IllegalArgumentException e) { testPassed = true; } assertTrue("IllegalArgumentException not thrown when a badly formatted argument was set.", testPassed); } @Test public void testParseFormattedFreeArgumentOk() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "1", "Test Free Argument.", "test", null, "^test$" } }); Properties testProps = parser.parseCommandLine(new String[] { "test" }); assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"), "test".equals(testProps.get("1"))); } @Test public void testParseFormattedOptionArgumentFailsBadArgument() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "t", "Test Option.", "test", null, "^test$" } }); boolean testPassed = false; try { Properties testProps = parser.parseCommandLine(new String[] { "-t", "fail" }); } catch (IllegalArgumentException e) { testPassed = true; } assertTrue("IllegalArgumentException not thrown when a badly formatted argument was set.", testPassed); } @Test public void testParseFormattedOptionArgumentOk() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "t", "Test Option.", "test", null, "^test$" } }); Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" }); assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"), "test".equals(testProps.get("t"))); } @Test public void testParseFreeArgumentOk() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "1", "Test Free Argument.", "test" } }); Properties testProps = parser.parseCommandLine(new String[] { "test" }); assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"), "test".equals(testProps.get("1"))); } @Test public void testParseMandatoryOptionOk() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "t", "Test Option.", "test", "true" } }); Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" }); assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"), "test".equals(testProps.get("t"))); } @Test public void testParseMandatoryFreeArgumentOk() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "1", "Test Option.", "test", "true" } }); Properties testProps = parser.parseCommandLine(new String[] { "test" }); assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"), "test".equals(testProps.get("1"))); } @Test public void testParseManadatoryFreeArgumentFailsNoArgument() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "1", "Test Option.", "test", "true" } }); boolean testPassed = false; try { Properties testProps = parser.parseCommandLine(new String[] {}); } catch (IllegalArgumentException e) { testPassed = true; } assertTrue("IllegalArgumentException not thrown for a missing mandatory option.", testPassed); } @Test public void testParseMandatoryFailsNoOption() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "t", "Test Option.", "test", "true" } }); boolean testPassed = false; try { Properties testProps = parser.parseCommandLine(new String[] {}); } catch (IllegalArgumentException e) { testPassed = true; } assertTrue("IllegalArgumentException not thrown for a missing mandatory option.", testPassed); } @Test public void testParseOptionWithNoSpaceOk() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "t", "Test Option.", "test" } }); Properties testProps = parser.parseCommandLine(new String[] { "-ttest" }); assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"), "test".equals(testProps.get("t"))); } @Test public void testParseOptionWithSpaceOk() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] { { "t", "Test Option.", "test" } }); Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" }); assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"), "test".equals(testProps.get("t"))); } @Test public void testParseUnknownOptionOk() throws Exception { CommandLineParser parser = new CommandLineParser(new String[][] {}); try { parser.parseCommandLine(new String[] { "-t" }); } catch (IllegalArgumentException e) { fail("The parser threw an IllegalArgumentException on an unknown flag when errors on unkowns is off."); } }
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); String randomAlphaNumericString(int maxLength); String createUniqueJavaName(String managerName); }
@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.isJavaIdentifierPart(c))) { builder.append(c); initialChar = false; } } if (builder.length() > 0) { builder.append("_"); } try { byte[] digest = MessageDigest.getInstance("MD5").digest(managerName.getBytes(StandardCharsets.UTF_8)); builder.append(toHex(digest).toLowerCase()); } catch (NoSuchAlgorithmException e) { throw new ServerScopedRuntimeException(e); } return builder.toString(); } static String elideDataUrl(final String path); static String toHex(byte[] bin); String randomAlphaNumericString(int maxLength); String createUniqueJavaName(String managerName); }
@Test public void testCreateUniqueJavaName() { assertEquals("MyName_973de1b4e26b629d4817c8255090e58e", _util.createUniqueJavaName("MyName")); assertEquals("ContaisIllegalJavaCharacters_a68b2484f2eb790558d6527e56c595fa", _util.createUniqueJavaName("Contais+Illegal-Java*Characters")); assertEquals("StartsWithIllegalInitial_93031eec569608c60c6a98ac9e84a0a7", _util.createUniqueJavaName("9StartsWithIllegalInitial")); assertEquals("97b247ba19ff869340d3797cc73ca065", _util.createUniqueJavaName("1++++----")); assertEquals("d41d8cd98f00b204e9800998ecf8427e", _util.createUniqueJavaName("")); }
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 IllegalArgumentException("Unable to copy '" + source.toString() + "' to '" + dst + "' a file with same name exists."); } if (source.isFile()) { copy(source, dst); } if (!dst.isDirectory() && !dst.mkdirs()) { throw new UnableToCopyException("Unable to create destination directory"); } for (File file : source.listFiles()) { if (file.isFile()) { copy(file, new File(dst.toString() + File.separator + file.getName())); } else { copyRecursive(file, new File(dst + File.separator + file.getName())); } } } private FileUtils(); static byte[] readFileAsBytes(String filename); static String readFileAsString(String filename); static String readFileAsString(File file); @SuppressWarnings("resource") static InputStream openFileOrDefaultResource(String filename, String defaultResource, ClassLoader cl); static void copy(File src, File dst); static void copyCheckedEx(File src, File dst); static void copy(InputStream in, File dst); static boolean deleteFile(String filePath); static boolean deleteDirectory(String directoryPath); static boolean delete(File file, boolean recursive); static void copyRecursive(File source, File dst); static List<String> searchFile(File file, String search); }
@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().getParentFile().listFiles(); try { final boolean condition = !testDir.exists(); assertTrue("Test directory already exists cannot test.", condition); if (!testDir.mkdir()) { fail("Unable to make test Directory"); } File testSubDir = new File(TEST_DIR + File.separator + TEST_DIR + SUB); if (!testSubDir.mkdir()) { fail("Unable to make test sub Directory"); } createTestFile(testDir.toString() + File.separator + fileName, TEST_DATA); createTestFile(testSubDir.toString() + File.separator + fileName + SUB, TEST_DATA); testSubDir.deleteOnExit(); testDir.deleteOnExit(); File copyDir = new File(testDir.toString() + COPY); try { FileUtils.copyRecursive(testDir, copyDir); } catch (FileNotFoundException e) { fail(e.getMessage()); } catch (FileUtils.UnableToCopyException e) { fail(e.getMessage()); } assertEquals("Copied directory should only have one file and one directory in it.", (long) 2, (long) copyDir.listFiles().length); String copiedFileContent = FileUtils.readFileAsString(copyDir.toString() + File.separator + fileName); assertEquals(TEST_DATA, copiedFileContent); assertTrue("Expected subdirectory is not a directory", new File(copyDir.toString() + File.separator + TEST_DIR + SUB).isDirectory()); assertEquals("Copied sub directory should only have one directory in it.", (long) 1, (long) new File(copyDir.toString() + File.separator + TEST_DIR + SUB).listFiles().length); copiedFileContent = FileUtils.readFileAsString(copyDir.toString() + File.separator + TEST_DIR + SUB + File.separator + fileName + SUB); assertEquals(TEST_DATA, copiedFileContent); } finally { assertTrue("Unable to cleanup", FileUtils.delete(testDir, true)); assertTrue("Unable to cleanup", FileUtils.delete(new File(TEST_DIR + COPY), true)); File[] afterCleanup = testDir.getAbsoluteFile().getParentFile().listFiles(); checkFileLists(beforeCopyFileList, afterCleanup); } }
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 openFileOrDefaultResource(String filename, String defaultResource, ClassLoader cl); static void copy(File src, File dst); static void copyCheckedEx(File src, File dst); static void copy(InputStream in, File dst); static boolean deleteFile(String filePath); static boolean deleteDirectory(String directoryPath); static boolean delete(File file, boolean recursive); static void copyRecursive(File source, File dst); static List<String> searchFile(File file, String search); }
@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 (IOException e) { fail(e.getMessage()); } assertTrue("File does not exists", test.exists()); assertTrue("File is not a file", test.isFile()); int fileCountCreated = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles().length; assertEquals("File creation was no registered", (long) (fileCountBefore + 1), (long) fileCountCreated); assertTrue("Unable to cleanup", FileUtils.deleteFile("FileUtilsTest-testDelete")); final boolean condition = !test.exists(); assertTrue("File exists after delete", condition); File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles(); int fileCountAfter = filesAfter.length; assertEquals("File creation was no registered", (long) fileCountBefore, (long) fileCountAfter); checkFileLists(filesBefore, filesAfter); }
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++) { success = delete(files[i], true) && success; } final boolean directoryDeleteSuccess = file.delete(); if(!directoryDeleteSuccess) { LOG.debug("Failed to delete " + file.getPath()); } return success && directoryDeleteSuccess; } return false; } success = file.delete(); if(!success) { LOG.debug("Failed to delete " + file.getPath()); } return success; } private FileUtils(); static byte[] readFileAsBytes(String filename); static String readFileAsString(String filename); static String readFileAsString(File file); @SuppressWarnings("resource") static InputStream openFileOrDefaultResource(String filename, String defaultResource, ClassLoader cl); static void copy(File src, File dst); static void copyCheckedEx(File src, File dst); static void copy(InputStream in, File dst); static boolean deleteFile(String filePath); static boolean deleteDirectory(String directoryPath); static boolean delete(File file, boolean recursive); static void copyRecursive(File source, File dst); static List<String> searchFile(File file, String search); }
@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); assertTrue("Delete Succeeded ", condition); } @Test public void testDeleteNull() { try { FileUtils.delete(null, true); fail("Delete with null value should throw NPE."); } catch (NullPointerException npe) { } } @Test public void testNonEmptyDirectoryDelete() { String directoryName = "FileUtilsTest-testRecursiveDelete"; File test = new File(directoryName); final boolean condition = !test.exists(); assertTrue("Directory exists", condition); String path = test.getAbsolutePath(); File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles(); int fileCountBefore = filesBefore.length; test.mkdir(); String fileName = test.getAbsolutePath() + File.separatorChar + "testFile"; File subFile = new File(fileName); try { subFile.createNewFile(); subFile.deleteOnExit(); } catch (IOException e) { fail(e.getMessage()); } test.deleteOnExit(); assertFalse("Non Empty Directory was successfully deleted.", FileUtils.delete(test, false)); assertTrue("Directory was deleted.", test.exists()); assertTrue("Unable to cleanup", FileUtils.delete(test, true)); File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles(); int fileCountAfter = filesAfter.length; assertEquals("File creation was no registered", (long) fileCountBefore, (long) fileCountAfter); checkFileLists(filesBefore, filesAfter); } @Test public void testRecursiveDelete() { String directoryName = "FileUtilsTest-testRecursiveDelete"; File test = new File(directoryName); final boolean condition1 = !test.exists(); assertTrue("Directory exists", condition1); String path = test.getAbsolutePath(); File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles(); int fileCountBefore = filesBefore.length; test.mkdir(); createSubDir(directoryName, 2, 4); test.deleteOnExit(); assertFalse("Non recursive delete was able to directory", FileUtils.delete(test, false)); assertTrue("File does not exist after non recursive delete", test.exists()); assertTrue("Unable to cleanup", FileUtils.delete(test, true)); final boolean condition = !test.exists(); assertTrue("File exist after recursive delete", condition); File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles(); int fileCountAfter = filesAfter.length; assertEquals("File creation was no registered", (long) fileCountBefore, (long) fileCountAfter); checkFileLists(filesBefore, filesAfter); }
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 = null; } if (is == null) { is = cl.getResourceAsStream(filename); } } if (is == null) { is = cl.getResourceAsStream(defaultResource); } return is; } private FileUtils(); static byte[] readFileAsBytes(String filename); static String readFileAsString(String filename); static String readFileAsString(File file); @SuppressWarnings("resource") static InputStream openFileOrDefaultResource(String filename, String defaultResource, ClassLoader cl); static void copy(File src, File dst); static void copyCheckedEx(File src, File dst); static void copy(InputStream in, File dst); static boolean deleteFile(String filePath); static boolean deleteDirectory(String directoryPath); static boolean delete(File file, boolean recursive); static void copyRecursive(File source, File dst); static List<String> searchFile(File file, String search); }
@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 = FileUtils.openFileOrDefaultResource(filenameOnFilesystem, defaultResource, this.getClass().getClassLoader()); assertNotNull("Stream must not be null", is); final Properties p = new Properties(); p.load(is); assertEquals("tmpfile", p.getProperty("src")); } @Test public void testOpenFileOrDefaultResourceOpensFileOnClasspath() throws Exception { final String mydefaultsResource = "org/apache/qpid/server/util/mydefaults.properties"; final String defaultResource = "org/apache/qpid/server/util/default.properties"; final InputStream is = FileUtils.openFileOrDefaultResource(mydefaultsResource, defaultResource, this.getClass().getClassLoader()); assertNotNull("Stream must not be null", is); final Properties p = new Properties(); p.load(is); assertEquals("mydefaults", p.getProperty("src")); } @Test public void testOpenFileOrDefaultResourceOpensDefaultResource() throws Exception { final File fileThatDoesNotExist = new File("/does/not/exist.properties"); assertFalse("Test must not exist", fileThatDoesNotExist.exists()); final String defaultResource = "org/apache/qpid/server/util/default.properties"; final InputStream is = FileUtils.openFileOrDefaultResource(fileThatDoesNotExist.getCanonicalPath(), defaultResource, this.getClass().getClassLoader()); assertNotNull("Stream must not be null", is); Properties p = new Properties(); p.load(is); assertEquals("default.properties", p.getProperty("src")); } @Test public void testOpenFileOrDefaultResourceReturnsNullWhenNeitherCanBeFound() throws Exception { final String mydefaultsResource = "org/apache/qpid/server/util/doesnotexisteiether.properties"; final String defaultResource = "org/apache/qpid/server/util/doesnotexisteiether.properties"; final InputStream is = FileUtils.openFileOrDefaultResource(mydefaultsResource, defaultResource, this.getClass().getClassLoader()); assertNull("Stream must be null", is); }
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 String readFileAsString(String filename); static String readFileAsString(File file); @SuppressWarnings("resource") static InputStream openFileOrDefaultResource(String filename, String defaultResource, ClassLoader cl); static void copy(File src, File dst); static void copyCheckedEx(File src, File dst); static void copy(InputStream in, File dst); static boolean deleteFile(String filePath); static boolean deleteDirectory(String directoryPath); static boolean delete(File file, boolean recursive); static void copyRecursive(File source, File dst); static List<String> searchFile(File file, String search); }
@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; final boolean condition1 = !test.exists(); assertTrue("Directory exists", condition1); test.mkdir(); test.deleteOnExit(); assertTrue("Non Empty Directory was successfully deleted.", FileUtils.deleteDirectory(directoryName)); final boolean condition = !test.exists(); assertTrue("Directory was deleted.", condition); File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles(); int fileCountAfter = filesAfter.length; assertEquals("File creation was no registered", (long) fileCountBefore, (long) fileCountAfter); checkFileLists(filesBefore, filesAfter); }
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); @Override void reset(); @Override boolean markSupported(); @Override long skip(long n); @Override int available(); @Override void close(); }
@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 { byte[] readBytes = new byte[_data.length]; int length = _inputStream.read(readBytes, 0, 2); byte[] expected = new byte[_data.length]; System.arraycopy(_data, 0, expected, 0, 2); assertTrue("Unexpected data", Arrays.equals(expected, readBytes)); assertEquals("Unexpected length", (long) 2, (long) length); length = _inputStream.read(readBytes, 2, 3); assertTrue("Unexpected data", Arrays.equals(_data, readBytes)); assertEquals("Unexpected length", (long) 3, (long) length); length = _inputStream.read(readBytes); assertEquals("EOF not reached", (long) -1, (long) length); }
RollingPolicyDecorator implements RollingPolicy { @Override public String getActiveFileName() { return _decorated.getActiveFileName(); } 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; }
@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 reset(); @Override boolean markSupported(); @Override long skip(long n); @Override int available(); @Override void close(); }
@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, readBytes)); assertEquals("Unexpected length", (long) (_data.length - 3), (long) length); }
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 markSupported(); @Override long skip(long n); @Override int available(); @Override void close(); }
@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("Unexpected number of available bytes", (long) 0, (long) available); }
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 long skip(long n); @Override int available(); @Override void close(); }
@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++) { switch (i) { case 1: this._major = Integer.parseInt(parts[i]); break; case 2: this._minor = Integer.parseInt(parts[i]); break; case 3: this._patch = Integer.parseInt(parts[i]); break; } } } 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 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.getPatch()); final AMQPProtocolVersionWrapper wrapper0_9 = new AMQPProtocolVersionWrapper(Protocol.AMQP_0_9); assertEquals((long) 0, (long) wrapper0_9.getMajor()); assertEquals((long) 9, (long) wrapper0_9.getMinor()); assertEquals((long) 0, (long) wrapper0_9.getPatch()); final AMQPProtocolVersionWrapper wrapper0_9_1 = new AMQPProtocolVersionWrapper(Protocol.AMQP_0_9_1); assertEquals((long) 0, (long) wrapper0_9_1.getMajor()); assertEquals((long) 9, (long) wrapper0_9_1.getMinor()); assertEquals((long) 1, (long) wrapper0_9_1.getPatch()); final AMQPProtocolVersionWrapper wrapper0_10 = new AMQPProtocolVersionWrapper(Protocol.AMQP_0_10); assertEquals((long) 0, (long) wrapper0_10.getMajor()); assertEquals((long) 10, (long) wrapper0_10.getMinor()); assertEquals((long) 0, (long) wrapper0_10.getPatch()); final AMQPProtocolVersionWrapper wrapper1_0 = new AMQPProtocolVersionWrapper(Protocol.AMQP_1_0); assertEquals((long) 1, (long) wrapper1_0.getMajor()); assertEquals((long) 0, (long) wrapper1_0.getMinor()); assertEquals((long) 0, (long) wrapper1_0.getPatch()); }
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 AMQPProtocolVersionWrapper(pec2.getVersion()); if (v1.getMajor() != v2.getMajor()) { return v1.getMajor() - v2.getMajor(); } else if (v1.getMinor() != v2.getMinor()) { return v1.getMinor() - v2.getMinor(); } else if (v1.getPatch() != v2.getPatch()) { return v1.getPatch() - v2.getPatch(); } else { return 0; } } @Override int compare(ProtocolEngineCreator pec1, ProtocolEngineCreator pec2); }
@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 = createAMQPProtocolEngineCreatorMock(Protocol.AMQP_0_9); final ProtocolEngineCreator amqp_0_9_1 = createAMQPProtocolEngineCreatorMock(Protocol.AMQP_0_9_1); final ProtocolEngineCreator amqp_0_10 = createAMQPProtocolEngineCreatorMock(Protocol.AMQP_0_10); final ProtocolEngineCreator amqp_1_0 = createAMQPProtocolEngineCreatorMock(Protocol.AMQP_1_0); assertTrue(comparator.compare(amqp_0_8, amqp_0_9) < 0); assertTrue(comparator.compare(amqp_0_9, amqp_0_9_1) < 0); assertTrue(comparator.compare(amqp_0_9_1, amqp_0_10) < 0); assertTrue(comparator.compare(amqp_0_10, amqp_1_0) < 0); assertTrue(comparator.compare(amqp_0_9, amqp_0_8) > 0); assertTrue(comparator.compare(amqp_0_9_1, amqp_0_9) > 0); assertTrue(comparator.compare(amqp_0_10, amqp_0_9_1) > 0); assertTrue(comparator.compare(amqp_1_0, amqp_0_10) > 0); assertTrue(comparator.compare(amqp_0_8, amqp_0_8) == 0); assertTrue(comparator.compare(amqp_0_9, amqp_0_9) == 0); assertTrue(comparator.compare(amqp_0_9_1, amqp_0_9_1) == 0); assertTrue(comparator.compare(amqp_0_10, amqp_0_10) == 0); assertTrue(comparator.compare(amqp_1_0, amqp_1_0) == 0); }
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.getLeastSignificantOldestEntry()); queueEntryList.add(createServerMessage(2), null); assertEquals("Unexpected last message", entry1, queueEntryList.getLeastSignificantOldestEntry()); queueEntryList.add(createServerMessage(3), null); assertEquals("Unexpected last message", entry1, queueEntryList.getLeastSignificantOldestEntry()); }
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 ServerMessage message, final MessageEnqueueRecord enqueueRecord); @Override SortedQueueEntry next(final QueueEntry entry); @Override QueueEntryIterator iterator(); @Override SortedQueueEntry getHead(); @Override SortedQueueEntry getTail(); @Override QueueEntry getOldestEntry(); @Override void entryDeleted(final QueueEntry e); @Override int getPriorities(); @Override QueueEntry getLeastSignificantOldestEntry(); }
@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, getSortedKeyValue(iter)); } }
SortedQueueEntryList extends AbstractQueueEntryList { @Override public QueueEntry getLeastSignificantOldestEntry() { return getOldestEntry(); } SortedQueueEntryList(final SortedQueueImpl queue, final QueueStatistics queueStatistics); @Override SortedQueueImpl getQueue(); @Override SortedQueueEntry add(final ServerMessage message, final MessageEnqueueRecord enqueueRecord); @Override SortedQueueEntry next(final QueueEntry entry); @Override QueueEntryIterator iterator(); @Override SortedQueueEntry getHead(); @Override SortedQueueEntry getTail(); @Override QueueEntry getOldestEntry(); @Override void entryDeleted(final QueueEntry e); @Override int getPriorities(); @Override QueueEntry getLeastSignificantOldestEntry(); }
@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.add(generateTestMessage(2, "C"), null); assertEquals("Unexpected last entry", entry1, list.getLeastSignificantOldestEntry()); list.add(generateTestMessage(3, null), null); assertEquals("Unexpected last entry", entry1, list.getLeastSignificantOldestEntry()); list.add(generateTestMessage(4, "A"), null); assertEquals("Unexpected last entry", entry1, list.getLeastSignificantOldestEntry()); }
RollingPolicyDecorator implements RollingPolicy { @Override public CompressionMode getCompressionMode() { return _decorated.getCompressionMode(); } 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; }
@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 newlyEnqueued); }
@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); LogMessage logMessage = QueueMessages.OVERFULL(11, 10, 0, -1); verify(_eventLogger).message(same(_subject), argThat(new LogMessageMatcher(logMessage))); verifyNoMoreInteractions(_eventLogger); verifyNoMoreInteractions(session); } @Test public void testCheckOverflowBlocksSessionWhenOverfullMessages() throws Exception { AMQPSession<?, ?> session = mock(AMQPSession.class); when(_queue.getMaximumQueueDepthMessages()).thenReturn(10L); when(_queue.getQueueDepthMessages()).thenReturn(11); checkOverflow(session); verify(session, times(1)).block(_queue); LogMessage logMessage = QueueMessages.OVERFULL(0, -1, 11, 10); verify(_eventLogger).message(same(_subject), argThat(new LogMessageMatcher(logMessage))); verifyNoMoreInteractions(_eventLogger); verifyNoMoreInteractions(session); }