use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.
the class WebSocketProvider method start.
@Override
public void start() {
_idleTimeoutChecker.start();
_server = new Server(new QBBTrackingThreadPool());
final ServerConnector connector;
HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory();
httpConnectionFactory.getHttpConfiguration().setSendServerVersion(false);
httpConnectionFactory.getHttpConfiguration().setSendXPoweredBy(false);
if (_transport == Transport.WS) {
connector = new ServerConnector(_server, httpConnectionFactory);
} else if (_transport == Transport.WSS) {
SslContextFactory sslContextFactory = new SslContextFactory() {
@Override
public void customize(final SSLEngine sslEngine) {
super.customize(sslEngine);
SSLUtil.updateEnabledCipherSuites(sslEngine, _port.getTlsCipherSuiteWhiteList(), _port.getTlsCipherSuiteBlackList());
SSLUtil.updateEnabledTlsProtocols(sslEngine, _port.getTlsProtocolWhiteList(), _port.getTlsProtocolBlackList());
if (_port.getTlsCipherSuiteWhiteList() != null && !_port.getTlsCipherSuiteWhiteList().isEmpty()) {
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setUseCipherSuitesOrder(true);
sslEngine.setSSLParameters(sslParameters);
}
}
};
sslContextFactory.setSslContext(_sslContext);
sslContextFactory.setNeedClientAuth(_port.getNeedClientAuth());
sslContextFactory.setWantClientAuth(_port.getWantClientAuth());
connector = new ServerConnector(_server, sslContextFactory, httpConnectionFactory);
connector.addBean(new SslHandshakeListener() {
@Override
public void handshakeFailed(final Event event, final Throwable failure) {
SSLEngine sslEngine = event.getSSLEngine();
if (LOGGER.isDebugEnabled()) {
LOGGER.info("TLS handshake failed: host='{}', port={}", sslEngine.getPeerHost(), sslEngine.getPeerPort(), failure);
} else {
LOGGER.info("TLS handshake failed: host='{}', port={}: {}", sslEngine.getPeerHost(), sslEngine.getPeerPort(), String.valueOf(failure));
}
}
});
} else {
throw new IllegalArgumentException("Unexpected transport on port " + _port.getName() + ":" + _transport);
}
String bindingAddress = _port.getBindingAddress();
if (bindingAddress != null && !bindingAddress.trim().equals("") && !bindingAddress.trim().equals("*")) {
connector.setHost(bindingAddress.trim());
}
connector.setPort(_port.getPort());
_server.addConnector(connector);
WebSocketHandler wshandler = new WebSocketHandler() {
@Override
public void configure(final WebSocketServletFactory factory) {
factory.setCreator((req, resp) -> {
resp.setAcceptedSubProtocol(AMQP_WEBSOCKET_SUBPROTOCOL);
return new AmqpWebSocket();
});
}
@Override
public void configurePolicy(final WebSocketPolicy policy) {
super.configurePolicy(policy);
// See https://github.com/eclipse/jetty.project/issues/488
try {
Field maxBinaryMessageSize = policy.getClass().getDeclaredField("maxBinaryMessageSize");
maxBinaryMessageSize.setAccessible(true);
maxBinaryMessageSize.set(policy, 0);
} catch (IllegalAccessException | NoSuchFieldException e) {
LOGGER.warn("Could not override maxBinaryMessageSize", e);
}
}
};
_server.setHandler(wshandler);
wshandler.setHandler(new AbstractHandler() {
@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
if (response.isCommitted() || baseRequest.isHandled()) {
return;
}
baseRequest.setHandled(true);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
});
try {
_server.start();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new ServerScopedRuntimeException(e);
}
}
use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.
the class AbstractQueue method addConsumerInternal.
private <T extends ConsumerTarget<T>> QueueConsumerImpl<T> addConsumerInternal(final T target, FilterManager filters, final Class<? extends ServerMessage> messageClass, final String consumerName, EnumSet<ConsumerOption> optionSet, final Integer priority) throws ExistingExclusiveConsumer, ConsumerAccessRefused, ExistingConsumerPreventsExclusive, QueueDeleted {
if (isDeleted()) {
throw new QueueDeleted();
}
if (hasExclusiveConsumer()) {
throw new ExistingExclusiveConsumer();
}
Object exclusiveOwner = _exclusiveOwner;
final AMQPSession<?, T> session = target.getSession();
switch(_exclusive) {
case CONNECTION:
if (exclusiveOwner == null) {
exclusiveOwner = session.getAMQPConnection();
addExclusivityConstraint(session.getAMQPConnection());
} else {
if (exclusiveOwner != session.getAMQPConnection()) {
throw new ConsumerAccessRefused();
}
}
break;
case SESSION:
if (exclusiveOwner == null) {
exclusiveOwner = session;
addExclusivityConstraint(session);
} else {
if (exclusiveOwner != session) {
throw new ConsumerAccessRefused();
}
}
break;
case LINK:
if (getConsumerCount() != 0) {
throw new ConsumerAccessRefused();
}
break;
case PRINCIPAL:
Principal currentAuthorizedPrincipal = session.getAMQPConnection().getAuthorizedPrincipal();
if (exclusiveOwner == null) {
exclusiveOwner = currentAuthorizedPrincipal;
} else {
if (!Objects.equals(((Principal) exclusiveOwner).getName(), currentAuthorizedPrincipal.getName())) {
throw new ConsumerAccessRefused();
}
}
break;
case CONTAINER:
if (exclusiveOwner == null) {
exclusiveOwner = session.getAMQPConnection().getRemoteContainerName();
} else {
if (!exclusiveOwner.equals(session.getAMQPConnection().getRemoteContainerName())) {
throw new ConsumerAccessRefused();
}
}
break;
case SHARED_SUBSCRIPTION:
break;
case NONE:
break;
default:
throw new ServerScopedRuntimeException("Unknown exclusivity policy " + _exclusive);
}
boolean exclusive = optionSet.contains(ConsumerOption.EXCLUSIVE);
boolean isTransient = optionSet.contains(ConsumerOption.TRANSIENT);
if (_noLocal && !optionSet.contains(ConsumerOption.NO_LOCAL)) {
optionSet = EnumSet.copyOf(optionSet);
optionSet.add(ConsumerOption.NO_LOCAL);
}
if (exclusive && getConsumerCount() != 0) {
throw new ExistingConsumerPreventsExclusive();
}
if (!_defaultFiltersMap.isEmpty()) {
if (filters == null) {
filters = new FilterManager();
}
for (Map.Entry<String, Callable<MessageFilter>> filter : _defaultFiltersMap.entrySet()) {
if (!filters.hasFilter(filter.getKey())) {
MessageFilter f;
try {
f = filter.getValue().call();
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
// Should never happen
throw new ServerScopedRuntimeException(e);
}
}
filters.add(filter.getKey(), f);
}
}
}
if (_ensureNondestructiveConsumers) {
optionSet = EnumSet.copyOf(optionSet);
optionSet.removeAll(EnumSet.of(ConsumerOption.SEES_REQUEUES, ConsumerOption.ACQUIRES));
}
QueueConsumerImpl<T> consumer = new QueueConsumerImpl<>(this, target, consumerName, filters, messageClass, optionSet, priority);
_exclusiveOwner = exclusiveOwner;
if (exclusive && !isTransient) {
_exclusiveSubscriber = consumer;
}
QueueContext queueContext;
if (filters == null || !filters.startAtTail()) {
queueContext = new QueueContext(getEntries().getHead());
} else {
queueContext = new QueueContext(getEntries().getTail());
}
consumer.setQueueContext(queueContext);
_queueConsumerManager.addConsumer(consumer);
if (consumer.isNotifyWorkDesired()) {
_activeSubscriberCount.incrementAndGet();
}
childAdded(consumer);
consumer.addChangeListener(_deletedChildListener);
session.incConsumerCount();
addChangeListener(new AbstractConfigurationChangeListener() {
@Override
public void childRemoved(final ConfiguredObject<?> object, final ConfiguredObject<?> child) {
if (child.equals(consumer)) {
session.decConsumerCount();
removeChangeListener(this);
}
}
});
return consumer;
}
use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.
the class FileKeyStoreImpl method validateKeyStoreAttributes.
private void validateKeyStoreAttributes(FileKeyStore<?> fileKeyStore) {
java.security.KeyStore keyStore;
try {
URL url = getUrlFromString(fileKeyStore.getStoreUrl());
String password = fileKeyStore.getPassword();
String keyStoreType = fileKeyStore.getKeyStoreType();
keyStore = SSLUtil.getInitializedKeyStore(url, password, keyStoreType);
} catch (Exception e) {
final String message;
if (e instanceof IOException && e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException) {
message = "Check key store password. Cannot instantiate key store from '" + fileKeyStore.getStoreUrl() + "'.";
} else {
message = "Cannot instantiate key store from '" + fileKeyStore.getStoreUrl() + "'.";
}
throw new IllegalConfigurationException(message, e);
}
try {
final String certAlias = fileKeyStore.getCertificateAlias();
if (certAlias != null) {
Certificate cert = keyStore.getCertificate(certAlias);
if (cert == null) {
throw new IllegalConfigurationException(String.format("Cannot find a certificate with alias '%s' in key store : %s", certAlias, fileKeyStore.getStoreUrl()));
}
if (keyStore.isCertificateEntry(certAlias)) {
throw new IllegalConfigurationException(String.format("Alias '%s' in key store : %s does not identify a key.", certAlias, fileKeyStore.getStoreUrl()));
}
}
if (!containsPrivateKey(keyStore)) {
throw new IllegalConfigurationException("Keystore must contain at least one private key.");
}
} catch (KeyStoreException e) {
// key store should be initialized above
throw new ServerScopedRuntimeException("Key store has not been initialized", e);
}
try {
KeyManagerFactory.getInstance(fileKeyStore.getKeyManagerFactoryAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new IllegalConfigurationException("Unknown keyManagerFactoryAlgorithm: " + fileKeyStore.getKeyManagerFactoryAlgorithm());
}
if (!fileKeyStore.isDurable()) {
throw new IllegalArgumentException(getClass().getSimpleName() + " must be durable");
}
checkCertificateExpiry();
}
use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.
the class MD5AuthenticationProvider method createStoredPassword.
@Override
protected String createStoredPassword(final String password) {
byte[] data = password.getBytes(StandardCharsets.UTF_8);
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new ServerScopedRuntimeException("MD5 not supported although Java compliance requires it");
}
md.update(data);
return DatatypeConverter.printBase64Binary(md.digest());
}
use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.
the class AbstractConsumerTarget method sendNextMessage.
@Override
public boolean sendNextMessage() {
MessageContainer messageContainer = null;
MessageInstanceConsumer consumer = null;
boolean iteratedCompleteList = false;
while (messageContainer == null) {
if (_pullIterator == null || !_pullIterator.hasNext()) {
if (iteratedCompleteList) {
break;
}
iteratedCompleteList = true;
_pullIterator = getConsumers().iterator();
}
if (_pullIterator.hasNext()) {
consumer = _pullIterator.next();
messageContainer = consumer.pullMessage();
}
}
if (messageContainer != null) {
MessageInstance entry = messageContainer.getMessageInstance();
try {
send(consumer, entry, false);
} catch (MessageConversionException mce) {
restoreCredit(entry.getMessage());
final TransactionLogResource owningResource = entry.getOwningResource();
if (owningResource instanceof MessageSource) {
final MessageSource.MessageConversionExceptionHandlingPolicy handlingPolicy = ((MessageSource) owningResource).getMessageConversionExceptionHandlingPolicy();
switch(handlingPolicy) {
case CLOSE:
entry.release(consumer);
throw new ConnectionScopedRuntimeException(String.format("Unable to convert message %s for this consumer", entry.getMessage()), mce);
case ROUTE_TO_ALTERNATE:
if (consumer.acquires()) {
int enqueues = entry.routeToAlternate(null, null);
if (enqueues == 0) {
LOGGER.info("Failed to convert message {} for this consumer because '{}'." + " Message discarded.", entry.getMessage(), mce.getMessage());
} else {
LOGGER.info("Failed to convert message {} for this consumer because '{}'." + " Message routed to alternate.", entry.getMessage(), mce.getMessage());
}
} else {
LOGGER.info("Failed to convert message {} for this browser because '{}'." + " Message skipped.", entry.getMessage(), mce.getMessage());
}
break;
case REJECT:
entry.reject(consumer);
entry.release(consumer);
LOGGER.info("Failed to convert message {} for this consumer because '{}'." + " Message skipped.", entry.getMessage(), mce.getMessage());
break;
default:
throw new ServerScopedRuntimeException("Unrecognised policy " + handlingPolicy);
}
} else {
throw new ConnectionScopedRuntimeException(String.format("Unable to convert message %s for this consumer", entry.getMessage()), mce);
}
} finally {
if (messageContainer.getMessageReference() != null) {
messageContainer.getMessageReference().release();
}
}
return true;
} else {
return false;
}
}
Aggregations