Search in sources :

Example 16 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class ConfiguredObjectMethodOperation method perform.

@Override
public Object perform(C subject, Map<String, Object> parameters) {
    final Map<String, ConfiguredObjectOperation<?>> operationsOnSubject = _typeRegistry.getOperations(subject.getClass());
    if (operationsOnSubject == null || operationsOnSubject.get(_operation.getName()) == null) {
        throw new IllegalArgumentException("No operation " + _operation.getName() + " on " + subject.getClass().getSimpleName());
    } else if (!hasSameParameters(operationsOnSubject.get(_operation.getName()))) {
        throw new IllegalArgumentException("Operation " + _operation.getName() + " on " + _objectType + " cannot be used on an object of type " + subject.getClass().getSimpleName());
    } else if (operationsOnSubject.get(_operation.getName()) != this) {
        return ((ConfiguredObjectOperation<C>) operationsOnSubject.get(_operation.getName())).perform(subject, parameters);
    } else {
        Set<String> providedNames = new HashSet<>(parameters.keySet());
        providedNames.removeAll(_validNames);
        if (!providedNames.isEmpty()) {
            throw new IllegalArgumentException("Parameters " + providedNames + " are not accepted by " + getName());
        }
        Object[] paramValues = new Object[_params.length];
        for (int i = 0; i < _params.length; i++) {
            paramValues[i] = getParameterValue(subject, parameters, _params[i]);
        }
        try {
            return _operation.invoke(subject, paramValues);
        } catch (IllegalAccessException e) {
            throw new ServerScopedRuntimeException(e);
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof RuntimeException) {
                throw (RuntimeException) e.getCause();
            } else if (e.getCause() instanceof Error) {
                throw (Error) e.getCause();
            } else {
                throw new ServerScopedRuntimeException(e);
            }
        }
    }
}
Also used : InvocationTargetException(java.lang.reflect.InvocationTargetException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 17 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class ConfiguredObjectTypeRegistry method processDefaultContext.

private <X extends ConfiguredObject> void processDefaultContext(final Class<X> clazz, final Set<String> contextSet) {
    for (Field field : clazz.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()) && field.isAnnotationPresent(ManagedContextDefault.class)) {
            try {
                ManagedContextDefault annotation = field.getAnnotation(ManagedContextDefault.class);
                String name = annotation.name();
                Object value = field.get(null);
                if (!_defaultContext.containsKey(name)) {
                    final String stringValue;
                    if (value instanceof Collection || value instanceof Map) {
                        try {
                            stringValue = ConfiguredObjectJacksonModule.newObjectMapper(false).writeValueAsString(value);
                        } catch (JsonProcessingException e) {
                            throw new ServerScopedRuntimeException("Unable to convert value of type '" + value.getClass() + "' to a JSON string for context variable ${" + name + "}");
                        }
                    } else {
                        stringValue = String.valueOf(value);
                    }
                    _defaultContext.put(name, stringValue);
                    _contextDefinitions.put(name, annotation);
                    contextSet.add(name);
                } else {
                    throw new IllegalArgumentException("Multiple definitions of the default context variable ${" + name + "}");
                }
            } catch (IllegalAccessException e) {
                throw new ServerScopedRuntimeException("Unexpected illegal access exception (only inspecting public static fields)", e);
            }
        }
    }
}
Also used : Field(java.lang.reflect.Field) AbstractCollection(java.util.AbstractCollection) Collection(java.util.Collection) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TreeMap(java.util.TreeMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException)

Example 18 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class BDBHARemoteReplicationNodeTest method testUpdateRole.

public void testUpdateRole() throws Exception {
    String remoteReplicationName = getName();
    BDBHARemoteReplicationNode remoteReplicationNode = createRemoteReplicationNode(remoteReplicationName);
    // Simulate an election that put the node in REPLICA state
    ((BDBHARemoteReplicationNodeImpl) remoteReplicationNode).setRole(NodeRole.REPLICA);
    Future<Void> future = mock(Future.class);
    when(_facade.transferMasterAsynchronously(remoteReplicationName)).thenReturn(future);
    remoteReplicationNode.setAttributes(Collections.singletonMap(BDBHARemoteReplicationNode.ROLE, NodeRole.MASTER));
    verify(_facade).transferMasterAsynchronously(remoteReplicationName);
    remoteReplicationNode = createRemoteReplicationNode(remoteReplicationName);
    ((BDBHARemoteReplicationNodeImpl) remoteReplicationNode).setRole(NodeRole.REPLICA);
    doThrow(new ExecutionException(new RuntimeException("Test"))).when(future).get(anyLong(), any(TimeUnit.class));
    try {
        remoteReplicationNode.setAttributes(Collections.singletonMap(BDBHARemoteReplicationNode.ROLE, NodeRole.MASTER));
        fail("ConnectionScopedRuntimeException is expected");
    } catch (ConnectionScopedRuntimeException e) {
    // pass
    }
    remoteReplicationNode = createRemoteReplicationNode(remoteReplicationName);
    ((BDBHARemoteReplicationNodeImpl) remoteReplicationNode).setRole(NodeRole.REPLICA);
    doThrow(new ExecutionException(new ServerScopedRuntimeException("Test"))).when(future).get(anyLong(), any(TimeUnit.class));
    try {
        remoteReplicationNode.setAttributes(Collections.singletonMap(BDBHARemoteReplicationNode.ROLE, NodeRole.MASTER));
        fail("ServerScopedRuntimeException is expected");
    } catch (ServerScopedRuntimeException e) {
    // pass
    }
}
Also used : ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) TimeUnit(java.util.concurrent.TimeUnit) ExecutionException(java.util.concurrent.ExecutionException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException)

Example 19 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class ConsumerTarget_1_0 method doSend.

@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 {
        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()) {
            if (SenderSettleMode.SETTLED.equals(getEndpoint().getSendingSettlementMode())) {
                transfer.setSettled(true);
            } 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);
                        }
                    });
                } 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);
        } else {
            entry.release(consumer);
        }
    } finally {
        transfer.dispose();
        if (converter != null) {
            converter.dispose(message);
        }
    }
}
Also used : ServerMessage(org.apache.qpid.server.message.ServerMessage) ArrayList(java.util.ArrayList) Error(org.apache.qpid.server.protocol.v1_0.type.transport.Error) TransactionError(org.apache.qpid.server.protocol.v1_0.type.transaction.TransactionError) HeaderSection(org.apache.qpid.server.protocol.v1_0.type.messaging.HeaderSection) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) TransactionalState(org.apache.qpid.server.protocol.v1_0.type.transaction.TransactionalState) Header(org.apache.qpid.server.protocol.v1_0.type.messaging.Header) Transfer(org.apache.qpid.server.protocol.v1_0.type.transport.Transfer) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer) Binary(org.apache.qpid.server.protocol.v1_0.type.Binary) UnsignedInteger(org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger) ServerTransaction(org.apache.qpid.server.txn.ServerTransaction)

Example 20 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class AsynchronousMessageStoreRecovererTest method testExceptionOnRecovery.

public void testExceptionOnRecovery() throws Exception {
    ServerScopedRuntimeException exception = new ServerScopedRuntimeException("test");
    doThrow(exception).when(_storeReader).visitMessageInstances(any(TransactionLogResource.class), any(MessageInstanceHandler.class));
    Queue<?> queue = mock(Queue.class);
    when(_virtualHost.getChildren(eq(Queue.class))).thenReturn(Collections.singleton(queue));
    AsynchronousMessageStoreRecoverer recoverer = new AsynchronousMessageStoreRecoverer();
    ListenableFuture<Void> result = recoverer.recover(_virtualHost);
    try {
        result.get();
        fail("ServerScopedRuntimeException should be rethrown");
    } catch (ExecutionException e) {
        assertEquals("Unexpected cause", exception, e.getCause());
    }
}
Also used : MessageInstanceHandler(org.apache.qpid.server.store.handler.MessageInstanceHandler) ExecutionException(java.util.concurrent.ExecutionException) TransactionLogResource(org.apache.qpid.server.store.TransactionLogResource) Queue(org.apache.qpid.server.model.Queue) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException)

Aggregations

ServerScopedRuntimeException (org.apache.qpid.server.util.ServerScopedRuntimeException)45 IOException (java.io.IOException)17 GeneralSecurityException (java.security.GeneralSecurityException)10 Map (java.util.Map)10 ConnectionScopedRuntimeException (org.apache.qpid.server.util.ConnectionScopedRuntimeException)10 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)9 URL (java.net.URL)9 InputStream (java.io.InputStream)8 HttpURLConnection (java.net.HttpURLConnection)8 ConnectionBuilder (org.apache.qpid.server.util.ConnectionBuilder)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 IllegalConfigurationException (org.apache.qpid.server.configuration.IllegalConfigurationException)6 TrustStore (org.apache.qpid.server.model.TrustStore)6 UsernamePrincipal (org.apache.qpid.server.security.auth.UsernamePrincipal)6 IdentityResolverException (org.apache.qpid.server.security.auth.manager.oauth2.IdentityResolverException)6 Field (java.lang.reflect.Field)5 Method (java.lang.reflect.Method)4 ArrayList (java.util.ArrayList)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3