Search in sources :

Example 1 with Command

use of org.wildfly.clustering.dispatcher.Command in project wildfly by wildfly.

the class BeanEvictionSchedulerTestCase method test.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
@org.junit.Ignore
public void test() throws Exception {
    String name = "bean";
    String evictedBeanId = "evicted";
    String activeBeanId = "active";
    CommandDispatcherFactory dispatcherFactory = mock(CommandDispatcherFactory.class);
    CommandDispatcher<BeanGroupEvictionContext<String>> dispatcher = mock(CommandDispatcher.class);
    Batcher<TransactionBatch> batcher = mock(Batcher.class);
    TransactionBatch batch = mock(TransactionBatch.class);
    Evictor<String> evictor = mock(Evictor.class);
    PassivationConfiguration<Bean<String, Object>> config = mock(PassivationConfiguration.class);
    BeanPassivationConfiguration passivationConfig = mock(BeanPassivationConfiguration.class);
    ArgumentCaptor<Command> capturedCommand = ArgumentCaptor.forClass(Command.class);
    ArgumentCaptor<BeanGroupEvictionContext> capturedContext = ArgumentCaptor.forClass(BeanGroupEvictionContext.class);
    when(dispatcherFactory.createCommandDispatcher(same(name), (BeanGroupEvictionContext<String>) capturedContext.capture())).thenReturn(dispatcher);
    when(config.getConfiguration()).thenReturn(passivationConfig);
    when(passivationConfig.getMaxSize()).thenReturn(1);
    try (Scheduler<String> scheduler = new BeanGroupEvictionScheduler<>(name, batcher, evictor, dispatcherFactory, config)) {
        BeanGroupEvictionContext<String> context = capturedContext.getValue();
        assertSame(scheduler, context);
        scheduler.schedule(evictedBeanId);
        verifyZeroInteractions(dispatcher);
        scheduler.schedule(activeBeanId);
        verify(dispatcher).submitOnCluster(capturedCommand.capture());
        when(batcher.createBatch()).thenReturn(batch);
        capturedCommand.getValue().execute(context);
        verify(evictor).evict(evictedBeanId);
        verify(evictor, never()).evict(activeBeanId);
        verify(batch).close();
    }
    verify(dispatcher).close();
}
Also used : TransactionBatch(org.wildfly.clustering.ee.infinispan.TransactionBatch) BeanPassivationConfiguration(org.wildfly.clustering.ejb.BeanPassivationConfiguration) Bean(org.wildfly.clustering.ejb.Bean) Command(org.wildfly.clustering.dispatcher.Command) CommandDispatcherFactory(org.wildfly.clustering.dispatcher.CommandDispatcherFactory) Test(org.junit.Test)

Example 2 with Command

use of org.wildfly.clustering.dispatcher.Command in project wildfly by wildfly.

the class ChannelCommandDispatcherFactory method read.

private ExceptionSupplier<Object, Exception> read(Message message) throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap(message.getRawBuffer(), message.getOffset(), message.getLength());
    @SuppressWarnings("unchecked") Map.Entry<Object, MarshalledValue<Command<Object, Object>, Object>> entry = (Map.Entry<Object, MarshalledValue<Command<Object, Object>, Object>>) this.marshaller.read(buffer);
    Object clientId = entry.getKey();
    CommandDispatcherContext<?, ?> context = this.contexts.get(clientId);
    if (context == null)
        return NO_SUCH_SERVICE_SUPPLIER;
    Object commandContext = context.getCommandContext();
    Contextualizer contextualizer = context.getContextualizer();
    MarshalledValue<Command<Object, Object>, Object> value = entry.getValue();
    Command<Object, Object> command = value.get(context.getMarshalledValueFactory().getMarshallingContext());
    ExceptionSupplier<Object, Exception> commandExecutionTask = new ExceptionSupplier<Object, Exception>() {

        @Override
        public Object get() throws Exception {
            return context.getMarshalledValueFactory().createMarshalledValue(command.execute(commandContext));
        }
    };
    ServiceExecutor executor = this.executor;
    return new ExceptionSupplier<Object, Exception>() {

        @Override
        public Object get() throws Exception {
            return executor.execute(contextualizer.contextualize(commandExecutionTask)).orElse(NO_SUCH_SERVICE);
        }
    };
}
Also used : ExceptionSupplier(org.wildfly.common.function.ExceptionSupplier) Contextualizer(org.jboss.as.clustering.context.Contextualizer) MarshalledValue(org.wildfly.clustering.marshalling.spi.MarshalledValue) ByteBuffer(java.nio.ByteBuffer) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException) Command(org.wildfly.clustering.dispatcher.Command) StampedLockServiceExecutor(org.wildfly.clustering.service.concurrent.StampedLockServiceExecutor) ServiceExecutor(org.wildfly.clustering.service.concurrent.ServiceExecutor) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 3 with Command

use of org.wildfly.clustering.dispatcher.Command in project wildfly by wildfly.

the class SessionEvictionSchedulerTestCase method test.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void test() throws Exception {
    String name = "cache";
    String evictedSessionId = "evicted";
    String activeSessionId = "active";
    ImmutableSessionMetaData evictedSessionMetaData = mock(ImmutableSessionMetaData.class);
    ImmutableSessionMetaData activeSessionMetaData = mock(ImmutableSessionMetaData.class);
    CommandDispatcherFactory dispatcherFactory = mock(CommandDispatcherFactory.class);
    CommandDispatcher<SessionEvictionContext> dispatcher = mock(CommandDispatcher.class);
    Evictor<String> evictor = mock(Evictor.class);
    Batcher<TransactionBatch> batcher = mock(Batcher.class);
    TransactionBatch batch = mock(TransactionBatch.class);
    ArgumentCaptor<Command> capturedCommand = ArgumentCaptor.forClass(Command.class);
    ArgumentCaptor<SessionEvictionContext> capturedContext = ArgumentCaptor.forClass(SessionEvictionContext.class);
    when(dispatcherFactory.createCommandDispatcher(same(name), capturedContext.capture())).thenReturn(dispatcher);
    try (Scheduler scheduler = new SessionEvictionScheduler(name, evictor, batcher, dispatcherFactory, 1)) {
        SessionEvictionContext context = capturedContext.getValue();
        assertSame(scheduler, context);
        scheduler.schedule(evictedSessionId, evictedSessionMetaData);
        verifyZeroInteractions(dispatcher);
        scheduler.schedule(activeSessionId, activeSessionMetaData);
        verify(dispatcher).submitOnCluster(capturedCommand.capture());
        when(batcher.createBatch()).thenReturn(batch);
        capturedCommand.getValue().execute(context);
        verify(evictor).evict(evictedSessionId);
        verify(batch).close();
        verify(evictor, never()).evict(activeSessionId);
    }
    verify(dispatcher).close();
}
Also used : TransactionBatch(org.wildfly.clustering.ee.infinispan.TransactionBatch) ImmutableSessionMetaData(org.wildfly.clustering.web.session.ImmutableSessionMetaData) Command(org.wildfly.clustering.dispatcher.Command) CommandDispatcherFactory(org.wildfly.clustering.dispatcher.CommandDispatcherFactory) Test(org.junit.Test)

Example 4 with Command

use of org.wildfly.clustering.dispatcher.Command in project wildfly by wildfly.

the class ChannelCommandDispatcher method submitOnCluster.

@Override
public <R> Map<Node, Future<R>> submitOnCluster(Command<R, ? super C> command, Node... excludedNodes) throws CommandDispatcherException {
    Map<Node, Future<R>> results = new ConcurrentHashMap<>();
    FutureListener<RspList<R>> listener = future -> {
        try {
            future.get().keySet().stream().map(address -> this.factory.createNode(address)).forEach(node -> results.remove(node));
        } catch (CancellationException e) {
        } catch (ExecutionException e) {
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    };
    Message message = this.createMessage(command);
    RequestOptions options = this.createRequestOptions(excludedNodes);
    try {
        Future<? extends Map<Address, Rsp<R>>> futureResponses = this.dispatcher.castMessageWithFuture(null, message, options, listener);
        Set<Node> excluded = (excludedNodes != null) ? new HashSet<>(Arrays.asList(excludedNodes)) : Collections.<Node>emptySet();
        for (Address address : this.dispatcher.getChannel().getView().getMembers()) {
            Node node = this.factory.createNode(address);
            if (!excluded.contains(node)) {
                Future<R> future = new Future<R>() {

                    @Override
                    public boolean cancel(boolean mayInterruptIfRunning) {
                        return futureResponses.cancel(mayInterruptIfRunning);
                    }

                    @Override
                    public R get() throws InterruptedException, ExecutionException {
                        Map<Address, Rsp<R>> responses = futureResponses.get();
                        Rsp<R> response = responses.get(address);
                        if (response == null) {
                            throw new CancellationException();
                        }
                        return createCommandResponse(response).get();
                    }

                    @Override
                    public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                        Map<Address, Rsp<R>> responses = futureResponses.get(timeout, unit);
                        Rsp<R> response = responses.get(address);
                        if (response == null) {
                            throw new CancellationException();
                        }
                        return createCommandResponse(response).get();
                    }

                    @Override
                    public boolean isCancelled() {
                        return futureResponses.isCancelled();
                    }

                    @Override
                    public boolean isDone() {
                        return futureResponses.isDone();
                    }
                };
                results.put(node, future);
            }
        }
        return results;
    } catch (Exception e) {
        throw new CommandDispatcherException(e);
    }
}
Also used : Arrays(java.util.Arrays) Rsp(org.jgroups.util.Rsp) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) FutureListener(org.jgroups.util.FutureListener) HashSet(java.util.HashSet) CommandDispatcher(org.wildfly.clustering.dispatcher.CommandDispatcher) Command(org.wildfly.clustering.dispatcher.Command) Future(java.util.concurrent.Future) RspFilter(org.jgroups.blocks.RspFilter) RequestOptions(org.jgroups.blocks.RequestOptions) Map(java.util.Map) RspList(org.jgroups.util.RspList) Address(org.jgroups.Address) NodeFactory(org.wildfly.clustering.group.NodeFactory) CancellationException(java.util.concurrent.CancellationException) ResponseMode(org.jgroups.blocks.ResponseMode) CommandResponse(org.wildfly.clustering.dispatcher.CommandResponse) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Addressable(org.wildfly.clustering.server.Addressable) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Message(org.jgroups.Message) Node(org.wildfly.clustering.group.Node) CommandDispatcherException(org.wildfly.clustering.dispatcher.CommandDispatcherException) Collections(java.util.Collections) MessageDispatcher(org.jgroups.blocks.MessageDispatcher) Message(org.jgroups.Message) Address(org.jgroups.Address) RequestOptions(org.jgroups.blocks.RequestOptions) CommandDispatcherException(org.wildfly.clustering.dispatcher.CommandDispatcherException) Node(org.wildfly.clustering.group.Node) RspList(org.jgroups.util.RspList) Rsp(org.jgroups.util.Rsp) TimeoutException(java.util.concurrent.TimeoutException) CancellationException(java.util.concurrent.CancellationException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) CommandDispatcherException(org.wildfly.clustering.dispatcher.CommandDispatcherException) CancellationException(java.util.concurrent.CancellationException) Future(java.util.concurrent.Future) TimeUnit(java.util.concurrent.TimeUnit) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ExecutionException(java.util.concurrent.ExecutionException)

Example 5 with Command

use of org.wildfly.clustering.dispatcher.Command in project wildfly by wildfly.

the class ChannelCommandDispatcherFactory method handle.

@Override
public Object handle(Message message) throws Exception {
    try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(message.getRawBuffer(), message.getOffset(), message.getLength()))) {
        int version = IndexExternalizer.VARIABLE.readData(input);
        try (Unmarshaller unmarshaller = this.marshallingContext.createUnmarshaller(version)) {
            unmarshaller.start(Marshalling.createByteInput(input));
            Object clientId = unmarshaller.readObject();
            Optional<Object> context = this.contexts.get(clientId);
            if (context == null)
                return NoSuchService.INSTANCE;
            @SuppressWarnings("unchecked") Command<Object, Object> command = (Command<Object, Object>) unmarshaller.readObject();
            Callable<Optional<Object>> task = new Callable<Optional<Object>>() {

                @Override
                public Optional<Object> call() throws Exception {
                    // Wrap in an Optional, since command execution might return null
                    return Optional.ofNullable(command.execute(context.orElse(null)));
                }
            };
            return this.executor.execute(task).orElse(Optional.of(NoSuchService.INSTANCE)).orElse(null);
        }
    }
}
Also used : Optional(java.util.Optional) ByteArrayInputStream(java.io.ByteArrayInputStream) Command(org.wildfly.clustering.dispatcher.Command) DataInputStream(java.io.DataInputStream) Unmarshaller(org.jboss.marshalling.Unmarshaller) Callable(java.util.concurrent.Callable)

Aggregations

Command (org.wildfly.clustering.dispatcher.Command)5 IOException (java.io.IOException)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 Test (org.junit.Test)2 CommandDispatcherFactory (org.wildfly.clustering.dispatcher.CommandDispatcherFactory)2 TransactionBatch (org.wildfly.clustering.ee.infinispan.TransactionBatch)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 DataInputStream (java.io.DataInputStream)1 ByteBuffer (java.nio.ByteBuffer)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Optional (java.util.Optional)1 Set (java.util.Set)1 Callable (java.util.concurrent.Callable)1 CancellationException (java.util.concurrent.CancellationException)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1 ExecutionException (java.util.concurrent.ExecutionException)1