Example usage for org.apache.commons.lang3.mutable MutableObject MutableObject

List of usage examples for org.apache.commons.lang3.mutable MutableObject MutableObject

Introduction

In this page you can find the example usage for org.apache.commons.lang3.mutable MutableObject MutableObject.

Prototype

public MutableObject() 

Source Link

Document

Constructs a new MutableObject with the default value of null.

Usage

From source file:org.jtestplatform.client.TestDriverTest.java

@Test(timeout = 60000)
public void testRunTests() throws Exception {
    // preparation
    File reportDirectory = folder.getRoot();
    File cloudConfigFile = getCloudConfigFile();
    final BlockingQueue<Request> requests = mock(BlockingQueue.class);
    final RequestProducer requestProducer = mock(RequestProducer.class);
    final MutableObject<Thread> requestProducerThread = new MutableObject<Thread>();
    doAnswer(new Answer<Void>() {
        @Override/* w  w w.  ja  v  a  2s . com*/
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            requestProducerThread.setValue(Thread.currentThread());
            return null;
        }
    }).when(requestProducer).produce(any(DomainManager.class));
    final RequestConsumer requestConsumer = mock(RequestConsumer.class);
    final MutableObject<Thread> requestConsumerThread = new MutableObject<Thread>();
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            requestConsumerThread.setValue(Thread.currentThread());
            return null;
        }
    }).when(requestConsumer).consume(any(TransportProvider.class), any(TestReporter.class));
    TestReporter testReporter = mock(TestReporter.class);
    MockTestDriver testDriver = new MockTestDriver(requests, requestProducer, requestConsumer, testReporter);

    // test
    testDriver.runTests(cloudConfigFile, reportDirectory);

    // verifications
    ArgumentCaptor<DomainManager> domainManagerCaptor = ArgumentCaptor.forClass(DomainManager.class);
    ArgumentCaptor<DomainManager> domainManagerCaptor2 = ArgumentCaptor.forClass(DomainManager.class);
    InOrder inOrder = inOrder(requests, requestProducer, requestConsumer, testReporter);
    inOrder.verify(requestConsumer, times(1)).consume(domainManagerCaptor2.capture(), any(TestReporter.class));
    inOrder.verify(requestProducer, times(1)).produce(domainManagerCaptor.capture());
    inOrder.verify(testReporter, times(1)).saveReport();
    inOrder.verifyNoMoreInteractions();

    assertThat(testDriver.getActualCloudConfigFile()).as("cloudConfigFile").isEqualTo(cloudConfigFile);
    Thread mainThread = Thread.currentThread();
    assertThat(requestConsumerThread.getValue()).as("requestConsumerThread").isNotNull()
            .isNotEqualTo(mainThread);
    assertThat(requestProducerThread.getValue()).as("requestProducerThread").isNotNull()
            .isNotEqualTo(mainThread).isNotEqualTo(requestConsumerThread);
}

From source file:org.jtestplatform.cloud.domain.watchdog.WatchDogTest.java

@Test
public void testStart() throws TimeoutException, InterruptedException {
    // prepare//from   w  ww . j  av  a2  s. co m
    MutableObject<WatchDogThread> thread = new MutableObject<WatchDogThread>();
    watchDog = createWatchDog(null, thread);

    // test
    watchDog.start();

    // verify
    assertThat(thread.getValue()).isNotNull();
    waitOrTimeout(isAlive(thread.getValue()), Timeout.timeout(seconds(10)));
}

From source file:org.jtestplatform.common.transport.TransportHelperTest.java

@Test
public void testReceive_ErrorMessage() throws Exception {
    // prepare/*  w  w  w . j a  v a  2 s  . c  om*/
    final String expectedErrorMessage = "errorMessage";
    thrown.expect(TransportException.class);
    thrown.expect(new BaseMatcher<Throwable>() {
        private final String exceptionMessage = "Received Error : " + expectedErrorMessage;

        @Override
        public void describeTo(Description description) {
            description.appendText("a TransportException with ErrorMessage(" + exceptionMessage + ")");
        }

        @Override
        public boolean matches(Object item) {
            if (!(item instanceof TransportException)) {
                return false;
            }

            TransportException exception = (TransportException) item;
            if (!equalTo(exceptionMessage).matches(exception.getMessage())) {
                return false;
            }
            ErrorMessage errorMessage = exception.getErrorMessage();
            return (errorMessage != null) && equalTo(expectedErrorMessage).matches(errorMessage.getMessage());
        }
    });

    final MutableObject<Message> messageWrapper = new MutableObject<Message>();
    Transport transport = mock(Transport.class);
    when(transport.receive()).thenReturn(ErrorMessage.class.getName(), expectedErrorMessage);
    TransportHelper helper = new TransportHelper() {
        @Override
        Message createMessage(Class<? extends Message> clazz)
                throws InstantiationException, IllegalAccessException {
            Message message = spy(super.createMessage(clazz));
            messageWrapper.setValue(message);
            return message;
        }
    };

    // test
    helper.receive(transport);
}

From source file:org.jtestplatform.common.transport.UDPClientServerTest.java

@Test
public void testClientAndServer() throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    MutableObject<String> actualRequest = new MutableObject<String>();
    executor.submit(createServer(actualRequest));
    MutableObject<String> actualAnswer = new MutableObject<String>();
    executor.submit(createClient(actualAnswer));

    MoreExecutors.shutdownAndAwaitTermination(executor, 10, MINUTES);

    assertThat(actualRequest.getValue()).as("request").isEqualTo(REQUEST);
    assertThat(actualAnswer.getValue()).as("answer").isEqualTo(ANSWER);
}

From source file:org.nuxeo.ecm.core.api.CoreInstance.java

/**
 * Runs the given {@link Function} with a system {@link CoreSession} while logged in as a system user.
 *
 * @param repositoryName the repository name for the {@link CoreSession}
 * @param function the function taking a system {@link CoreSession} and returning a result of type {@code <R>}
 * @param <R> the function return type
 * @return the result of the function// w w  w.  ja v  a 2  s . c o  m
 * @since 8.4
 */
public static <R> R doPrivileged(String repositoryName, Function<CoreSession, R> function) {
    MutableObject<R> result = new MutableObject<R>();
    new UnrestrictedSessionRunner(repositoryName, getCurrentPrincipalName()) {
        @Override
        public void run() {
            result.setValue(function.apply(session));
        }
    }.runUnrestricted();
    return result.getValue();
}

From source file:org.nuxeo.ecm.core.api.CoreInstance.java

/**
 * Runs the given {@link Function} with a system {@link CoreSession} while logged in as a system user.
 *
 * @param session an existing session//from ww w .j  av  a2 s .co m
 * @param function the function taking a system {@link CoreSession} and returning a result of type {@code <R>}
 * @param <R> the function return type
 * @return the result of the function
 * @since 8.4
 */
public static <R> R doPrivileged(CoreSession session, Function<CoreSession, R> function) {
    MutableObject<R> result = new MutableObject<R>();
    new UnrestrictedSessionRunner(session) {
        @Override
        public void run() {
            result.setValue(function.apply(session));
        }
    }.runUnrestricted();
    return result.getValue();
}

From source file:org.pircbotx.CAPTest.java

public void runTest(String cap, final OutputParser callback) throws Exception {
    final MutableObject<Exception> connectionException = new MutableObject<Exception>();
    botInWrite = new PipedOutputStream();
    botIn = new BufferedInputStream(new PipedInputStream(botInWrite));
    botOut = new ByteArrayOutputStream() {
        @Override/*  ww  w .  j  a  v a  2s  .com*/
        public synchronized void write(byte[] bytes, int i, int i1) {
            super.write(bytes, i, i1);
            String outputText = new String(bytes, i, i1).trim();

            try {
                try {
                    String callbackText = callback.handleOutput(outputText);
                    if (callbackText == null)
                        //Will close bots input loop
                        botInWrite.close();
                    else if (!callbackText.equals("")) {
                        botInWrite.write((callbackText + "\r\n").getBytes());
                        botInWrite.flush();
                    }
                } catch (Exception ex) {
                    log.error("Recieved error, closing bot and escelating", ex);
                    connectionException.setValue(ex);
                    botInWrite.close();
                }
            } catch (IOException ex) {
                log.error("Recieved IO error, closing bot and escelating", ex);
                connectionException.setValue(ex);
                try {
                    botInWrite.close();
                } catch (Exception e) {
                    throw new RuntimeException("Can't close botInWrite", e);
                }
            }
        }
    };
    Socket socket = mock(Socket.class);
    when(socket.isConnected()).thenReturn(true);
    when(socket.getInputStream()).thenReturn(botIn);
    when(socket.getOutputStream()).thenReturn(botOut);

    Configuration.Builder configurationBuilder = TestUtils.generateConfigurationBuilder();

    SocketFactory socketFactory = mock(SocketFactory.class);
    when(socketFactory.createSocket(
            InetAddress.getByName(configurationBuilder.getServers().get(0).getHostname()), 6667, null, 0))
                    .thenReturn(socket);

    configurationBuilder.getCapHandlers().clear();
    configurationBuilder.getCapHandlers().addAll(capHandlers);
    bot = new PircBotX(
            configurationBuilder.setSocketFactory(socketFactory).setAutoReconnect(false).buildConfiguration());

    botInWrite.write((":ircd.test CAP * LS :" + cap + "\r\n").getBytes());
    bot.connect();
    if (connectionException.getValue() != null)
        throw connectionException.getValue();
}

From source file:org.pircbotx.dcc.DCCTest.java

@Test
public void incommingDccChatTest() throws IOException, InterruptedException, IrcException {
    Inet6Address localhost6 = (Inet6Address) InetAddress.getByName("::1");

    //Create listener to handle everything
    final MutableObject<IncomingChatRequestEvent> mutableEvent = new MutableObject<IncomingChatRequestEvent>();
    bot.getConfiguration().getListenerManager().addListener(new ListenerAdapter() {
        @Override/*from   w w w.j a  va  2 s  .  co  m*/
        public void onIncomingChatRequest(IncomingChatRequestEvent event) throws Exception {
            mutableEvent.setValue(event);
        }
    });

    System.out.println("localhost6 byte array: " + Arrays.toString(localhost6.getAddress()));
    System.out.println("localhost6 int: " + new BigInteger(localhost6.getAddress()));

    bot.getInputParser().handleLine(":ANick!~ALogin@::2 PRIVMSG Quackbot5 :DCC CHAT chat 1 35589");
    IncomingChatRequestEvent event = mutableEvent.getValue();
    assertNotNull(event, "No IncomingChatRequestEvent dispatched");

    System.out.println("Test ran");
}

From source file:org.pircbotx.hooks.managers.ThreadedListenerManagerTest.java

@Test
public void exceptionTest() {
    ThreadedListenerManager manager = new ThreadedListenerManager(MoreExecutors.newDirectExecutorService());

    final MutableObject<ListenerExceptionEvent> eventResult = new MutableObject<ListenerExceptionEvent>();
    Listener testListener;/*from  w  w w . ja  va  2  s  .c  om*/
    manager.addListener(testListener = new Listener() {
        @Override
        public void onEvent(Event event) throws Exception {
            if (event instanceof ListenerExceptionEvent) {
                eventResult.setValue((ListenerExceptionEvent) event);
            } else
                throw new RuntimeException("Default fail");
        }
    });

    Event event = new ConnectEvent(null);
    manager.onEvent(event);

    assertEquals(eventResult.getValue().getListener(), testListener);
    assertEquals(eventResult.getValue().getSourceEvent(), event);
    assertNotNull(eventResult.getValue().getException());
}

From source file:org.pircbotx.hooks.TemporaryListenerTest.java

@Test(singleThreaded = true)
public void eventDispatched() throws IOException, IrcException {
    final MutableObject<MessageEvent> mutableEvent = new MutableObject<MessageEvent>();
    Listener listener = new TemporaryListener(bot) {
        @Override/*  ww w . j a v a2 s.co  m*/
        public void onMessage(MessageEvent event) throws Exception {
            mutableEvent.setValue(event);
        }
    };
    listenerManager.addListener(listener);

    //Make sure the listener is there
    assertTrue(listenerManager.listenerExists(listener), "Listener doesn't exist in ListenerManager");

    //Send some arbitrary line
    bot.getInputParser()
            .handleLine(":" + userSource.getHostmask() + " PRIVMSG #aChannel :Some very long message");
    MessageEvent mevent = mutableEvent.getValue();

    //Verify event contents
    assertNotNull(mevent, "MessageEvent not dispatched");
    assertEquals(mevent.getMessage(), "Some very long message", "Message sent does not match");

    //Make sure the listner is still there
    assertTrue(listenerManager.listenerExists(listener), "Listener doesn't exist in ListenerManager");
}