diff options
author | Eike Stepper | 2012-06-07 10:14:51 +0000 |
---|---|---|
committer | Eike Stepper | 2012-06-07 10:14:51 +0000 |
commit | a25531ae8a5c85586fdb590c0f806be3a807b634 (patch) | |
tree | 7849f8065be919611dabd87403f9bf5a1743cee7 /plugins/org.eclipse.net4j.tests/src | |
parent | b48ccc46da60cf75aef219ae635c627fb49d3cf2 (diff) | |
download | cdo-a25531ae8a5c85586fdb590c0f806be3a807b634.tar.gz cdo-a25531ae8a5c85586fdb590c0f806be3a807b634.tar.xz cdo-a25531ae8a5c85586fdb590c0f806be3a807b634.zip |
[381472] Design a repository administration API
https://bugs.eclipse.org/bugs/show_bug.cgi?id=381472
Diffstat (limited to 'plugins/org.eclipse.net4j.tests/src')
7 files changed, 1793 insertions, 1798 deletions
diff --git a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/tests/BufferPoolTest.java b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/tests/BufferPoolTest.java index 6090e3b784..3b1445d6e4 100644 --- a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/tests/BufferPoolTest.java +++ b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/tests/BufferPoolTest.java @@ -1,97 +1,97 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.tests;
-
-import org.eclipse.net4j.Net4jUtil;
-import org.eclipse.net4j.buffer.IBuffer;
-import org.eclipse.net4j.buffer.IBufferPool;
-import org.eclipse.net4j.util.ReflectUtil;
-import org.eclipse.net4j.util.io.IOUtil;
-import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
-import org.eclipse.net4j.util.tests.AbstractOMTest;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-/**
- * @author Eike Stepper
- */
-public class BufferPoolTest extends AbstractOMTest
-{
- private static IBufferPool bufferPool = Net4jUtil.createBufferPool();
-
- private static Collection<byte[]> memory = new ArrayList<byte[]>();
-
- @Override
- protected void doTearDown() throws Exception
- {
- memory.clear();
- super.doTearDown();
- }
-
- public void testBufferPool() throws Exception
- {
- LifecycleUtil.activate(bufferPool);
-
- IBuffer[] buffers = new IBuffer[10];
- for (int i = 0; i < buffers.length; i++)
- {
- buffers[i] = bufferPool.provideBuffer();
- }
-
- for (int i = 0; i < buffers.length; i++)
- {
- bufferPool.retainBuffer(buffers[i]);
- buffers[i] = null;
- }
-
- while (Net4jUtil.getPooledBuffers(bufferPool) > 0 && allocate())
- {
- sleep(100);
- ReflectUtil.dump(bufferPool);
- }
-
- LifecycleUtil.deactivate(bufferPool);
- }
-
- private static void msg()
- {
- msg("pooledBuffers = " + Net4jUtil.getPooledBuffers(bufferPool)); //$NON-NLS-1$
- }
-
- private static boolean allocate()
- {
- try
- {
- IOUtil.OUT().println("allocating from " + Runtime.getRuntime().freeMemory()); //$NON-NLS-1$
- for (int i = 0; i < 10; i++)
- {
- memory.add(new byte[1000000]);
- }
-
- msg();
- return true;
- }
- catch (Throwable t)
- {
- return false;
- }
- }
-
- @SuppressWarnings("unused")
- private static void gc()
- {
- msg();
- IOUtil.OUT().println("collecting garbage"); //$NON-NLS-1$
- System.gc();
- msg();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.tests; + +import org.eclipse.net4j.Net4jUtil; +import org.eclipse.net4j.buffer.IBuffer; +import org.eclipse.net4j.buffer.IBufferPool; +import org.eclipse.net4j.util.ReflectUtil; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.lifecycle.LifecycleUtil; +import org.eclipse.net4j.util.tests.AbstractOMTest; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * @author Eike Stepper + */ +public class BufferPoolTest extends AbstractOMTest +{ + private static IBufferPool bufferPool = Net4jUtil.createBufferPool(); + + private static Collection<byte[]> memory = new ArrayList<byte[]>(); + + @Override + protected void doTearDown() throws Exception + { + memory.clear(); + super.doTearDown(); + } + + public void testBufferPool() throws Exception + { + LifecycleUtil.activate(bufferPool); + + IBuffer[] buffers = new IBuffer[10]; + for (int i = 0; i < buffers.length; i++) + { + buffers[i] = bufferPool.provideBuffer(); + } + + for (int i = 0; i < buffers.length; i++) + { + bufferPool.retainBuffer(buffers[i]); + buffers[i] = null; + } + + while (Net4jUtil.getPooledBuffers(bufferPool) > 0 && allocate()) + { + sleep(10); + ReflectUtil.dump(bufferPool); + } + + LifecycleUtil.deactivate(bufferPool); + } + + private static void msg() + { + msg("pooledBuffers = " + Net4jUtil.getPooledBuffers(bufferPool)); //$NON-NLS-1$ + } + + private static boolean allocate() + { + try + { + IOUtil.OUT().println("allocating from " + Runtime.getRuntime().freeMemory()); //$NON-NLS-1$ + for (int i = 0; i < 10; i++) + { + memory.add(new byte[1000000]); + } + + msg(); + return true; + } + catch (Throwable t) + { + return false; + } + } + + @SuppressWarnings("unused") + private static void gc() + { + msg(); + IOUtil.OUT().println("collecting garbage"); //$NON-NLS-1$ + System.gc(); + msg(); + } +} diff --git a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/tests/TCPConnectorTest.java b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/tests/TCPConnectorTest.java index 2fc4cc43b4..fb54418190 100644 --- a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/tests/TCPConnectorTest.java +++ b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/tests/TCPConnectorTest.java @@ -1,637 +1,638 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - SSL
- */
-package org.eclipse.net4j.tests;
-
-import org.eclipse.net4j.Net4jUtil;
-import org.eclipse.net4j.buffer.IBufferPool;
-import org.eclipse.net4j.channel.IChannel;
-import org.eclipse.net4j.connector.ConnectorException;
-import org.eclipse.net4j.connector.IConnector;
-import org.eclipse.net4j.internal.tcp.TCPAcceptor;
-import org.eclipse.net4j.internal.tcp.TCPAcceptorFactory;
-import org.eclipse.net4j.internal.tcp.TCPClientConnector;
-import org.eclipse.net4j.internal.tcp.TCPConnector;
-import org.eclipse.net4j.internal.tcp.TCPConnectorFactory;
-import org.eclipse.net4j.internal.tcp.TCPSelector;
-import org.eclipse.net4j.internal.tcp.ssl.SSLAcceptor;
-import org.eclipse.net4j.internal.tcp.ssl.SSLAcceptorFactory;
-import org.eclipse.net4j.internal.tcp.ssl.SSLClientConnector;
-import org.eclipse.net4j.internal.tcp.ssl.SSLConnectorFactory;
-import org.eclipse.net4j.tcp.ITCPSelector;
-import org.eclipse.net4j.tests.bundle.OM;
-import org.eclipse.net4j.util.collection.RoundRobinBlockingQueue;
-import org.eclipse.net4j.util.concurrent.ConcurrencyUtil;
-import org.eclipse.net4j.util.io.IOUtil;
-import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
-import org.eclipse.net4j.util.security.ChallengeNegotiator;
-import org.eclipse.net4j.util.security.NegotiationException;
-import org.eclipse.net4j.util.security.PasswordCredentials;
-import org.eclipse.net4j.util.security.PasswordCredentialsProvider;
-import org.eclipse.net4j.util.security.Randomizer;
-import org.eclipse.net4j.util.security.ResponseNegotiator;
-import org.eclipse.net4j.util.security.UserManager;
-
-import org.eclipse.spi.net4j.Channel;
-import org.eclipse.spi.net4j.InternalChannel;
-
-import java.nio.channels.ServerSocketChannel;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-/**
- * @author Eike Stepper
- * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
- */
-public class TCPConnectorTest extends AbstractTransportTest
-{
- private static final int TIMEOUT = 10000;
-
- private static final int PORT = 2040;
-
- private static final String USER_ID = "stepper"; //$NON-NLS-1$
-
- private static final String INVALID_USER_ID = "invalid"; //$NON-NLS-1$
-
- private static final char[] PASSWORD = "eike2008".toCharArray(); //$NON-NLS-1$
-
- private static final char[] INVALID_PASSWORD = "invalid".toCharArray(); //$NON-NLS-1$
-
- private static final PasswordCredentials CREDENTIALS = new PasswordCredentials(USER_ID, PASSWORD);
-
- private ExecutorService threadPool;
-
- private IBufferPool bufferPool;
-
- private TCPSelector selector;
-
- private TCPAcceptor acceptor;
-
- private TCPConnector connector;
-
- private Randomizer randomizer;
-
- private UserManager userManager;
-
- private ChallengeNegotiator challengeNegotiator;
-
- private PasswordCredentialsProvider credentialsProvider;
-
- private ResponseNegotiator responseNegotiator;
-
- @Override
- protected void doTearDown() throws Exception
- {
- cleanup();
- super.doTearDown();
- }
-
- private void cleanup() throws Exception
- {
- sleep(100);
-
- if (connector != null)
- {
- connector.close();
- connector = null;
- }
-
- if (responseNegotiator != null)
- {
- LifecycleUtil.deactivate(responseNegotiator);
- responseNegotiator = null;
- }
-
- if (credentialsProvider != null)
- {
- LifecycleUtil.deactivate(credentialsProvider);
- credentialsProvider = null;
- }
-
- if (acceptor != null)
- {
- acceptor.close();
- acceptor = null;
- }
-
- if (challengeNegotiator != null)
- {
- LifecycleUtil.deactivate(challengeNegotiator);
- challengeNegotiator = null;
- }
-
- if (userManager != null)
- {
- LifecycleUtil.deactivate(userManager);
- userManager = null;
- }
-
- if (randomizer != null)
- {
- LifecycleUtil.deactivate(randomizer);
- randomizer = null;
- }
-
- if (selector != null)
- {
- LifecycleUtil.deactivate(selector);
- selector = null;
- }
-
- if (bufferPool != null)
- {
- LifecycleUtil.deactivate(bufferPool);
- bufferPool = null;
- }
-
- if (threadPool != null)
- {
- LifecycleUtil.deactivate(threadPool);
- threadPool = null;
- }
- }
-
- private void provideTransport()
- {
- selector = new TCPSelector();
-
- if (useSSLTransport())
- {
- acceptor = new SSLAcceptor();
- container.putElement(SSLAcceptorFactory.PRODUCT_GROUP, SSLAcceptorFactory.TYPE, null, acceptor);
-
- // cannot use same container with the acceptor.
- connector = new SSLClientConnector();
- separateContainer.putElement(SSLConnectorFactory.PRODUCT_GROUP, SSLConnectorFactory.TYPE, null, acceptor);
- }
- else
- {
- acceptor = new TCPAcceptor();
- container.putElement(TCPAcceptorFactory.PRODUCT_GROUP, TCPAcceptorFactory.TYPE, null, acceptor);
-
- connector = new TCPClientConnector();
- container.putElement(TCPConnectorFactory.PRODUCT_GROUP, TCPConnectorFactory.TYPE, null, acceptor);
- }
- }
-
- private void provideTransport(final long increaseDelayAcceptor)
- {
- selector = new TCPSelector();
-
- if (useSSLTransport())
- {
- acceptor = new SSLAcceptor()
- {
- @Override
- public void handleAccept(ITCPSelector selector, ServerSocketChannel serverSocketChannel)
- {
- ConcurrencyUtil.sleep(increaseDelayAcceptor);
- super.handleAccept(selector, serverSocketChannel);
- }
- };
-
- connector = new SSLClientConnector();
- }
- else
- {
- acceptor = new TCPAcceptor()
- {
- @Override
- public void handleAccept(ITCPSelector selector, ServerSocketChannel serverSocketChannel)
- {
- ConcurrencyUtil.sleep(increaseDelayAcceptor);
- super.handleAccept(selector, serverSocketChannel);
- }
- };
-
- connector = new TCPClientConnector();
- }
- }
-
- public void testDeferredActivation() throws Exception
- {
- final long DELAY = 500L;
- threadPool = Executors.newCachedThreadPool();
- LifecycleUtil.activate(threadPool);
-
- bufferPool = Net4jUtil.createBufferPool();
- LifecycleUtil.activate(bufferPool);
-
- provideTransport(DELAY);
-
- selector.activate();
-
- acceptor.setStartSynchronously(true);
- acceptor.setSynchronousStartTimeout(TIMEOUT);
- acceptor.getConfig().setBufferProvider(bufferPool);
- acceptor.getConfig().setReceiveExecutor(threadPool);
- acceptor.setSelector(selector);
- acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$
- acceptor.setPort(PORT);
- acceptor.activate();
-
- connector.getConfig().setBufferProvider(bufferPool);
- connector.getConfig().setReceiveExecutor(threadPool);
- connector.setSelector(selector);
- connector.setHost("localhost"); //$NON-NLS-1$
- connector.setPort(PORT);
- connector.activate();
- // Can fail due to timing variations: assertEquals(false, connector.isActive());
-
- connector.waitForConnection(DEFAULT_TIMEOUT);
- assertEquals(true, connector.isActive());
- }
-
- public void testDeferredActivation10() throws Exception
- {
- for (int i = 0; i < 10; i++)
- {
- IOUtil.OUT().println();
- IOUtil.OUT().println();
- IOUtil.OUT().println();
- IOUtil.OUT().println("#####################################################"); //$NON-NLS-1$
- IOUtil.OUT().println(" RUN = " + i); //$NON-NLS-1$
- IOUtil.OUT().println("#####################################################"); //$NON-NLS-1$
- IOUtil.OUT().println();
- IOUtil.OUT().println();
- IOUtil.OUT().println();
- testDeferredActivation();
- cleanup();
- }
- }
-
- public void testNegotiationSuccess() throws Exception
- {
- threadPool = Executors.newCachedThreadPool();
- LifecycleUtil.activate(threadPool);
-
- bufferPool = Net4jUtil.createBufferPool();
- LifecycleUtil.activate(bufferPool);
-
- randomizer = new Randomizer();
- randomizer.activate();
-
- userManager = new UserManager();
- userManager.activate();
- userManager.addUser(USER_ID, PASSWORD);
-
- challengeNegotiator = new ChallengeNegotiator();
- challengeNegotiator.setRandomizer(randomizer);
- challengeNegotiator.setUserManager(userManager);
- challengeNegotiator.activate();
-
- provideTransport();
-
- selector.activate();
-
- acceptor.setStartSynchronously(true);
- acceptor.setSynchronousStartTimeout(TIMEOUT);
- acceptor.getConfig().setBufferProvider(bufferPool);
- acceptor.getConfig().setReceiveExecutor(threadPool);
- acceptor.getConfig().setNegotiator(challengeNegotiator);
- acceptor.setSelector(selector);
- acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$
- acceptor.setPort(PORT);
- acceptor.activate();
-
- credentialsProvider = new PasswordCredentialsProvider(CREDENTIALS);
- LifecycleUtil.activate(credentialsProvider);
-
- responseNegotiator = new ResponseNegotiator();
- responseNegotiator.setCredentialsProvider(credentialsProvider);
- responseNegotiator.activate();
-
- connector.getConfig().setBufferProvider(bufferPool);
- connector.getConfig().setReceiveExecutor(threadPool);
- connector.getConfig().setNegotiator(responseNegotiator);
- connector.setSelector(selector);
- connector.setHost("localhost"); //$NON-NLS-1$
- connector.setPort(PORT);
- connector.activate();
-
- connector.waitForConnection(DEFAULT_TIMEOUT);
-
- InternalChannel clientChannel = connector.openChannel();
- assertEquals(USER_ID, clientChannel.getUserID());
-
- IConnector serverConnector = acceptor.getElements()[0];
- IChannel serverChannel = serverConnector.getElements()[0];
- assertEquals(USER_ID, serverChannel.getUserID());
-
- System.out.println(serverChannel);
- }
-
- public void testNegotiationSuccess10() throws Exception
- {
- for (int i = 0; i < 10; i++)
- {
- IOUtil.OUT().println();
- IOUtil.OUT().println();
- IOUtil.OUT().println();
- IOUtil.OUT().println("#####################################################"); //$NON-NLS-1$
- IOUtil.OUT().println(" RUN = " + i); //$NON-NLS-1$
- IOUtil.OUT().println("#####################################################"); //$NON-NLS-1$
- IOUtil.OUT().println();
- IOUtil.OUT().println();
- IOUtil.OUT().println();
- testNegotiationSuccess();
- cleanup();
- }
- }
-
- public void testInvalidUser() throws Exception
- {
- threadPool = Executors.newCachedThreadPool();
- LifecycleUtil.activate(threadPool);
-
- bufferPool = Net4jUtil.createBufferPool();
- LifecycleUtil.activate(bufferPool);
-
- randomizer = new Randomizer();
- randomizer.activate();
-
- userManager = new UserManager();
- userManager.activate();
- userManager.addUser(INVALID_USER_ID, PASSWORD);
-
- challengeNegotiator = new ChallengeNegotiator();
- challengeNegotiator.setRandomizer(randomizer);
- challengeNegotiator.setUserManager(userManager);
- challengeNegotiator.activate();
-
- provideTransport();
-
- selector.activate();
-
- acceptor.setStartSynchronously(true);
- acceptor.setSynchronousStartTimeout(TIMEOUT);
- acceptor.getConfig().setBufferProvider(bufferPool);
- acceptor.getConfig().setReceiveExecutor(threadPool);
- acceptor.getConfig().setNegotiator(challengeNegotiator);
- acceptor.setSelector(selector);
- acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$
- acceptor.setPort(PORT);
- acceptor.activate();
-
- credentialsProvider = new PasswordCredentialsProvider(CREDENTIALS);
- LifecycleUtil.activate(credentialsProvider);
-
- responseNegotiator = new ResponseNegotiator();
- responseNegotiator.setCredentialsProvider(credentialsProvider);
- responseNegotiator.activate();
-
- connector.getConfig().setBufferProvider(bufferPool);
- connector.getConfig().setReceiveExecutor(threadPool);
- connector.getConfig().setNegotiator(responseNegotiator);
- connector.setSelector(selector);
- connector.setHost("localhost"); //$NON-NLS-1$
- connector.setPort(PORT);
-
- try
- {
- connector.connectAsync();
- connector.waitForConnection(DEFAULT_TIMEOUT_EXPECTED);
- fail("ConnectorException expected"); //$NON-NLS-1$
- }
- catch (ConnectorException ex)
- {
- OM.LOG.info("Expected ConnectorException:", ex); //$NON-NLS-1$
- assertEquals(true, ex.getCause() instanceof NegotiationException);
- }
- }
-
- public void testInvalidPassword() throws Exception
- {
- threadPool = Executors.newCachedThreadPool();
- LifecycleUtil.activate(threadPool);
-
- bufferPool = Net4jUtil.createBufferPool();
- LifecycleUtil.activate(bufferPool);
-
- randomizer = new Randomizer();
- randomizer.activate();
-
- userManager = new UserManager();
- userManager.activate();
- userManager.addUser(USER_ID, INVALID_PASSWORD);
-
- challengeNegotiator = new ChallengeNegotiator();
- challengeNegotiator.setRandomizer(randomizer);
- challengeNegotiator.setUserManager(userManager);
- challengeNegotiator.activate();
-
- provideTransport();
-
- selector.activate();
-
- acceptor.setStartSynchronously(true);
- acceptor.setSynchronousStartTimeout(TIMEOUT);
- acceptor.getConfig().setBufferProvider(bufferPool);
- acceptor.getConfig().setReceiveExecutor(threadPool);
- acceptor.getConfig().setNegotiator(challengeNegotiator);
- acceptor.setSelector(selector);
- acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$
- acceptor.setPort(PORT);
- acceptor.activate();
-
- credentialsProvider = new PasswordCredentialsProvider(CREDENTIALS);
- LifecycleUtil.activate(credentialsProvider);
-
- responseNegotiator = new ResponseNegotiator();
- responseNegotiator.setCredentialsProvider(credentialsProvider);
- responseNegotiator.activate();
-
- connector.getConfig().setBufferProvider(bufferPool);
- connector.getConfig().setReceiveExecutor(threadPool);
- connector.getConfig().setNegotiator(responseNegotiator);
- connector.setSelector(selector);
- connector.setHost("localhost"); //$NON-NLS-1$
- connector.setPort(PORT);
-
- try
- {
- connector.connectAsync();
- connector.waitForConnection(DEFAULT_TIMEOUT_EXPECTED);
- fail("ConnectorException expected"); //$NON-NLS-1$
- }
- catch (ConnectorException ex)
- {
- OM.LOG.info("Expected ConnectorException:", ex); //$NON-NLS-1$
- assertEquals(true, ex.getCause() instanceof NegotiationException);
- }
- }
-
- public void testNoNegotiator() throws Exception
- {
- threadPool = Executors.newCachedThreadPool();
- LifecycleUtil.activate(threadPool);
-
- bufferPool = Net4jUtil.createBufferPool();
- LifecycleUtil.activate(bufferPool);
-
- provideTransport();
-
- selector.activate();
-
- acceptor.setStartSynchronously(true);
- acceptor.setSynchronousStartTimeout(TIMEOUT);
- acceptor.getConfig().setBufferProvider(bufferPool);
- acceptor.getConfig().setReceiveExecutor(threadPool);
- acceptor.setSelector(selector);
- acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$
- acceptor.setPort(PORT);
- acceptor.activate();
-
- connector.getConfig().setBufferProvider(bufferPool);
- connector.getConfig().setReceiveExecutor(threadPool);
- connector.setSelector(selector);
- connector.setHost("localhost"); //$NON-NLS-1$
- connector.setPort(PORT);
- connector.setUserID("SHOULD_FAIL_LATER"); //$NON-NLS-1$
-
- try
- {
- connector.connect();
- fail("ConnectorException expected"); //$NON-NLS-1$
- }
- catch (ConnectorException ex)
- {
- OM.LOG.info("Expected ConnectorException:", ex); //$NON-NLS-1$
- assertEquals(true, ex.getCause() instanceof IllegalStateException);
- }
- }
-
- public void testNegotiatorTooLate() throws Exception
- {
- threadPool = Executors.newCachedThreadPool();
- LifecycleUtil.activate(threadPool);
-
- bufferPool = Net4jUtil.createBufferPool();
- LifecycleUtil.activate(bufferPool);
-
- provideTransport();
-
- selector.activate();
-
- acceptor.setStartSynchronously(true);
- acceptor.setSynchronousStartTimeout(TIMEOUT);
- acceptor.getConfig().setBufferProvider(bufferPool);
- acceptor.getConfig().setReceiveExecutor(threadPool);
- acceptor.setSelector(selector);
- acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$
- acceptor.setPort(PORT);
- acceptor.activate();
-
- connector.getConfig().setBufferProvider(bufferPool);
- connector.getConfig().setReceiveExecutor(threadPool);
- connector.setSelector(selector);
- connector.setHost("localhost"); //$NON-NLS-1$
- connector.setPort(PORT);
- connector.connect();
-
- credentialsProvider = new PasswordCredentialsProvider(CREDENTIALS);
- LifecycleUtil.activate(credentialsProvider);
-
- responseNegotiator = new ResponseNegotiator();
- responseNegotiator.setCredentialsProvider(credentialsProvider);
- responseNegotiator.activate();
-
- try
- {
- connector.getConfig().setNegotiator(responseNegotiator);
- fail("IllegalStateException expected"); //$NON-NLS-1$
- }
- catch (IllegalStateException ex)
- {
- OM.LOG.info("Expected IllegalStateException:", ex); //$NON-NLS-1$
- }
- }
-
- public void testRoundRobinBlockingQueue() throws Exception
- {
- BlockingQueue<IChannel> queue = new RoundRobinBlockingQueue<IChannel>();
-
- Channel[] channels = new Channel[3];
-
- for (int i = 0; i < channels.length; i++)
- {
- Channel c = new Channel();
- c.setID((short)i);
- channels[i] = c;
- }
-
- assertEquals(true, queue.isEmpty());
- assertNull(queue.peek());
- assertNull(queue.poll());
-
- // Order will be 0000...1111...2222...
- for (int i = 0; i < channels.length; i++)
- {
- for (int j = 0; j < 10; j++)
- {
- queue.put(channels[i]);
- }
- }
-
- for (int i = 0; i < 30; i++)
- {
- IChannel peek1 = queue.peek();
- IChannel peek2 = queue.peek();
- assertSame(peek1, peek2);
-
- IChannel poll = queue.poll();
- // The order should be 012012012012...
- assertEquals(i % 3, poll.getID());
- assertSame(peek1, poll);
- }
-
- assertEquals(true, queue.isEmpty());
- assertNull(queue.peek());
- assertNull(queue.poll());
- }
-
- /**
- * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
- */
- public static final class TCP extends TCPConnectorTest
- {
- @Override
- protected boolean useJVMTransport()
- {
- return false;
- }
-
- @Override
- protected boolean useSSLTransport()
- {
- return false;
- }
- }
-
- /**
- * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
- */
- public static final class SSL extends TCPConnectorTest
- {
- @Override
- protected boolean useJVMTransport()
- {
- return false;
- }
-
- @Override
- protected boolean useSSLTransport()
- {
- return true;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - SSL + */ +package org.eclipse.net4j.tests; + +import org.eclipse.net4j.Net4jUtil; +import org.eclipse.net4j.buffer.IBufferPool; +import org.eclipse.net4j.channel.IChannel; +import org.eclipse.net4j.connector.ConnectorException; +import org.eclipse.net4j.connector.IConnector; +import org.eclipse.net4j.internal.tcp.TCPAcceptor; +import org.eclipse.net4j.internal.tcp.TCPAcceptorFactory; +import org.eclipse.net4j.internal.tcp.TCPClientConnector; +import org.eclipse.net4j.internal.tcp.TCPConnector; +import org.eclipse.net4j.internal.tcp.TCPConnectorFactory; +import org.eclipse.net4j.internal.tcp.TCPSelector; +import org.eclipse.net4j.internal.tcp.ssl.SSLAcceptor; +import org.eclipse.net4j.internal.tcp.ssl.SSLAcceptorFactory; +import org.eclipse.net4j.internal.tcp.ssl.SSLClientConnector; +import org.eclipse.net4j.internal.tcp.ssl.SSLConnectorFactory; +import org.eclipse.net4j.tcp.ITCPSelector; +import org.eclipse.net4j.tcp.TCPUtil; +import org.eclipse.net4j.tests.bundle.OM; +import org.eclipse.net4j.util.collection.RoundRobinBlockingQueue; +import org.eclipse.net4j.util.concurrent.ConcurrencyUtil; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.lifecycle.LifecycleUtil; +import org.eclipse.net4j.util.security.ChallengeNegotiator; +import org.eclipse.net4j.util.security.NegotiationException; +import org.eclipse.net4j.util.security.PasswordCredentials; +import org.eclipse.net4j.util.security.PasswordCredentialsProvider; +import org.eclipse.net4j.util.security.Randomizer; +import org.eclipse.net4j.util.security.ResponseNegotiator; +import org.eclipse.net4j.util.security.UserManager; + +import org.eclipse.spi.net4j.Channel; +import org.eclipse.spi.net4j.InternalChannel; + +import java.nio.channels.ServerSocketChannel; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * @author Eike Stepper + * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) + */ +public class TCPConnectorTest extends AbstractTransportTest +{ + private static final int TIMEOUT = 10000; + + private static final int PORT = 2040; + + private static final String USER_ID = "stepper"; //$NON-NLS-1$ + + private static final String INVALID_USER_ID = "invalid"; //$NON-NLS-1$ + + private static final char[] PASSWORD = "eike2008".toCharArray(); //$NON-NLS-1$ + + private static final char[] INVALID_PASSWORD = "invalid".toCharArray(); //$NON-NLS-1$ + + private static final PasswordCredentials CREDENTIALS = new PasswordCredentials(USER_ID, PASSWORD); + + private ExecutorService threadPool; + + private IBufferPool bufferPool; + + private TCPSelector selector; + + private TCPAcceptor acceptor; + + private TCPConnector connector; + + private Randomizer randomizer; + + private UserManager userManager; + + private ChallengeNegotiator challengeNegotiator; + + private PasswordCredentialsProvider credentialsProvider; + + private ResponseNegotiator responseNegotiator; + + @Override + protected void doTearDown() throws Exception + { + cleanup(); + super.doTearDown(); + } + + private void cleanup() throws Exception + { + sleep(100); + + if (connector != null) + { + connector.close(); + connector = null; + } + + if (responseNegotiator != null) + { + LifecycleUtil.deactivate(responseNegotiator); + responseNegotiator = null; + } + + if (credentialsProvider != null) + { + LifecycleUtil.deactivate(credentialsProvider); + credentialsProvider = null; + } + + if (acceptor != null) + { + acceptor.close(); + acceptor = null; + } + + if (challengeNegotiator != null) + { + LifecycleUtil.deactivate(challengeNegotiator); + challengeNegotiator = null; + } + + if (userManager != null) + { + LifecycleUtil.deactivate(userManager); + userManager = null; + } + + if (randomizer != null) + { + LifecycleUtil.deactivate(randomizer); + randomizer = null; + } + + if (selector != null) + { + LifecycleUtil.deactivate(selector); + selector = null; + } + + if (bufferPool != null) + { + LifecycleUtil.deactivate(bufferPool); + bufferPool = null; + } + + if (threadPool != null) + { + LifecycleUtil.deactivate(threadPool); + threadPool = null; + } + } + + private void provideTransport() + { + selector = new TCPSelector(); + + if (useSSLTransport()) + { + acceptor = new SSLAcceptor(); + container.putElement(SSLAcceptorFactory.PRODUCT_GROUP, SSLAcceptorFactory.TYPE, null, acceptor); + + // cannot use same container with the acceptor. + connector = new SSLClientConnector(); + separateContainer.putElement(SSLConnectorFactory.PRODUCT_GROUP, SSLConnectorFactory.TYPE, null, acceptor); + } + else + { + acceptor = new TCPAcceptor(); + container.putElement(TCPAcceptorFactory.PRODUCT_GROUP, TCPUtil.FACTORY_TYPE, null, acceptor); + + connector = new TCPClientConnector(); + container.putElement(TCPConnectorFactory.PRODUCT_GROUP, TCPConnectorFactory.TYPE, null, acceptor); + } + } + + private void provideTransport(final long increaseDelayAcceptor) + { + selector = new TCPSelector(); + + if (useSSLTransport()) + { + acceptor = new SSLAcceptor() + { + @Override + public void handleAccept(ITCPSelector selector, ServerSocketChannel serverSocketChannel) + { + ConcurrencyUtil.sleep(increaseDelayAcceptor); + super.handleAccept(selector, serverSocketChannel); + } + }; + + connector = new SSLClientConnector(); + } + else + { + acceptor = new TCPAcceptor() + { + @Override + public void handleAccept(ITCPSelector selector, ServerSocketChannel serverSocketChannel) + { + ConcurrencyUtil.sleep(increaseDelayAcceptor); + super.handleAccept(selector, serverSocketChannel); + } + }; + + connector = new TCPClientConnector(); + } + } + + public void testDeferredActivation() throws Exception + { + final long DELAY = 500L; + threadPool = Executors.newCachedThreadPool(); + LifecycleUtil.activate(threadPool); + + bufferPool = Net4jUtil.createBufferPool(); + LifecycleUtil.activate(bufferPool); + + provideTransport(DELAY); + + selector.activate(); + + acceptor.setStartSynchronously(true); + acceptor.setSynchronousStartTimeout(TIMEOUT); + acceptor.getConfig().setBufferProvider(bufferPool); + acceptor.getConfig().setReceiveExecutor(threadPool); + acceptor.setSelector(selector); + acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$ + acceptor.setPort(PORT); + acceptor.activate(); + + connector.getConfig().setBufferProvider(bufferPool); + connector.getConfig().setReceiveExecutor(threadPool); + connector.setSelector(selector); + connector.setHost("localhost"); //$NON-NLS-1$ + connector.setPort(PORT); + connector.activate(); + // Can fail due to timing variations: assertEquals(false, connector.isActive()); + + connector.waitForConnection(DEFAULT_TIMEOUT); + assertEquals(true, connector.isActive()); + } + + public void testDeferredActivation10() throws Exception + { + for (int i = 0; i < 10; i++) + { + IOUtil.OUT().println(); + IOUtil.OUT().println(); + IOUtil.OUT().println(); + IOUtil.OUT().println("#####################################################"); //$NON-NLS-1$ + IOUtil.OUT().println(" RUN = " + i); //$NON-NLS-1$ + IOUtil.OUT().println("#####################################################"); //$NON-NLS-1$ + IOUtil.OUT().println(); + IOUtil.OUT().println(); + IOUtil.OUT().println(); + testDeferredActivation(); + cleanup(); + } + } + + public void testNegotiationSuccess() throws Exception + { + threadPool = Executors.newCachedThreadPool(); + LifecycleUtil.activate(threadPool); + + bufferPool = Net4jUtil.createBufferPool(); + LifecycleUtil.activate(bufferPool); + + randomizer = new Randomizer(); + randomizer.activate(); + + userManager = new UserManager(); + userManager.activate(); + userManager.addUser(USER_ID, PASSWORD); + + challengeNegotiator = new ChallengeNegotiator(); + challengeNegotiator.setRandomizer(randomizer); + challengeNegotiator.setUserManager(userManager); + challengeNegotiator.activate(); + + provideTransport(); + + selector.activate(); + + acceptor.setStartSynchronously(true); + acceptor.setSynchronousStartTimeout(TIMEOUT); + acceptor.getConfig().setBufferProvider(bufferPool); + acceptor.getConfig().setReceiveExecutor(threadPool); + acceptor.getConfig().setNegotiator(challengeNegotiator); + acceptor.setSelector(selector); + acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$ + acceptor.setPort(PORT); + acceptor.activate(); + + credentialsProvider = new PasswordCredentialsProvider(CREDENTIALS); + LifecycleUtil.activate(credentialsProvider); + + responseNegotiator = new ResponseNegotiator(); + responseNegotiator.setCredentialsProvider(credentialsProvider); + responseNegotiator.activate(); + + connector.getConfig().setBufferProvider(bufferPool); + connector.getConfig().setReceiveExecutor(threadPool); + connector.getConfig().setNegotiator(responseNegotiator); + connector.setSelector(selector); + connector.setHost("localhost"); //$NON-NLS-1$ + connector.setPort(PORT); + connector.activate(); + + connector.waitForConnection(DEFAULT_TIMEOUT); + + InternalChannel clientChannel = connector.openChannel(); + assertEquals(USER_ID, clientChannel.getUserID()); + + IConnector serverConnector = acceptor.getElements()[0]; + IChannel serverChannel = serverConnector.getElements()[0]; + assertEquals(USER_ID, serverChannel.getUserID()); + + System.out.println(serverChannel); + } + + public void testNegotiationSuccess10() throws Exception + { + for (int i = 0; i < 10; i++) + { + IOUtil.OUT().println(); + IOUtil.OUT().println(); + IOUtil.OUT().println(); + IOUtil.OUT().println("#####################################################"); //$NON-NLS-1$ + IOUtil.OUT().println(" RUN = " + i); //$NON-NLS-1$ + IOUtil.OUT().println("#####################################################"); //$NON-NLS-1$ + IOUtil.OUT().println(); + IOUtil.OUT().println(); + IOUtil.OUT().println(); + testNegotiationSuccess(); + cleanup(); + } + } + + public void testInvalidUser() throws Exception + { + threadPool = Executors.newCachedThreadPool(); + LifecycleUtil.activate(threadPool); + + bufferPool = Net4jUtil.createBufferPool(); + LifecycleUtil.activate(bufferPool); + + randomizer = new Randomizer(); + randomizer.activate(); + + userManager = new UserManager(); + userManager.activate(); + userManager.addUser(INVALID_USER_ID, PASSWORD); + + challengeNegotiator = new ChallengeNegotiator(); + challengeNegotiator.setRandomizer(randomizer); + challengeNegotiator.setUserManager(userManager); + challengeNegotiator.activate(); + + provideTransport(); + + selector.activate(); + + acceptor.setStartSynchronously(true); + acceptor.setSynchronousStartTimeout(TIMEOUT); + acceptor.getConfig().setBufferProvider(bufferPool); + acceptor.getConfig().setReceiveExecutor(threadPool); + acceptor.getConfig().setNegotiator(challengeNegotiator); + acceptor.setSelector(selector); + acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$ + acceptor.setPort(PORT); + acceptor.activate(); + + credentialsProvider = new PasswordCredentialsProvider(CREDENTIALS); + LifecycleUtil.activate(credentialsProvider); + + responseNegotiator = new ResponseNegotiator(); + responseNegotiator.setCredentialsProvider(credentialsProvider); + responseNegotiator.activate(); + + connector.getConfig().setBufferProvider(bufferPool); + connector.getConfig().setReceiveExecutor(threadPool); + connector.getConfig().setNegotiator(responseNegotiator); + connector.setSelector(selector); + connector.setHost("localhost"); //$NON-NLS-1$ + connector.setPort(PORT); + + try + { + connector.connectAsync(); + connector.waitForConnection(DEFAULT_TIMEOUT_EXPECTED); + fail("ConnectorException expected"); //$NON-NLS-1$ + } + catch (ConnectorException ex) + { + OM.LOG.info("Expected ConnectorException:", ex); //$NON-NLS-1$ + assertEquals(true, ex.getCause() instanceof NegotiationException); + } + } + + public void testInvalidPassword() throws Exception + { + threadPool = Executors.newCachedThreadPool(); + LifecycleUtil.activate(threadPool); + + bufferPool = Net4jUtil.createBufferPool(); + LifecycleUtil.activate(bufferPool); + + randomizer = new Randomizer(); + randomizer.activate(); + + userManager = new UserManager(); + userManager.activate(); + userManager.addUser(USER_ID, INVALID_PASSWORD); + + challengeNegotiator = new ChallengeNegotiator(); + challengeNegotiator.setRandomizer(randomizer); + challengeNegotiator.setUserManager(userManager); + challengeNegotiator.activate(); + + provideTransport(); + + selector.activate(); + + acceptor.setStartSynchronously(true); + acceptor.setSynchronousStartTimeout(TIMEOUT); + acceptor.getConfig().setBufferProvider(bufferPool); + acceptor.getConfig().setReceiveExecutor(threadPool); + acceptor.getConfig().setNegotiator(challengeNegotiator); + acceptor.setSelector(selector); + acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$ + acceptor.setPort(PORT); + acceptor.activate(); + + credentialsProvider = new PasswordCredentialsProvider(CREDENTIALS); + LifecycleUtil.activate(credentialsProvider); + + responseNegotiator = new ResponseNegotiator(); + responseNegotiator.setCredentialsProvider(credentialsProvider); + responseNegotiator.activate(); + + connector.getConfig().setBufferProvider(bufferPool); + connector.getConfig().setReceiveExecutor(threadPool); + connector.getConfig().setNegotiator(responseNegotiator); + connector.setSelector(selector); + connector.setHost("localhost"); //$NON-NLS-1$ + connector.setPort(PORT); + + try + { + connector.connectAsync(); + connector.waitForConnection(DEFAULT_TIMEOUT_EXPECTED); + fail("ConnectorException expected"); //$NON-NLS-1$ + } + catch (ConnectorException ex) + { + OM.LOG.info("Expected ConnectorException:", ex); //$NON-NLS-1$ + assertEquals(true, ex.getCause() instanceof NegotiationException); + } + } + + public void testNoNegotiator() throws Exception + { + threadPool = Executors.newCachedThreadPool(); + LifecycleUtil.activate(threadPool); + + bufferPool = Net4jUtil.createBufferPool(); + LifecycleUtil.activate(bufferPool); + + provideTransport(); + + selector.activate(); + + acceptor.setStartSynchronously(true); + acceptor.setSynchronousStartTimeout(TIMEOUT); + acceptor.getConfig().setBufferProvider(bufferPool); + acceptor.getConfig().setReceiveExecutor(threadPool); + acceptor.setSelector(selector); + acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$ + acceptor.setPort(PORT); + acceptor.activate(); + + connector.getConfig().setBufferProvider(bufferPool); + connector.getConfig().setReceiveExecutor(threadPool); + connector.setSelector(selector); + connector.setHost("localhost"); //$NON-NLS-1$ + connector.setPort(PORT); + connector.setUserID("SHOULD_FAIL_LATER"); //$NON-NLS-1$ + + try + { + connector.connect(); + fail("ConnectorException expected"); //$NON-NLS-1$ + } + catch (ConnectorException ex) + { + OM.LOG.info("Expected ConnectorException:", ex); //$NON-NLS-1$ + assertEquals(true, ex.getCause() instanceof IllegalStateException); + } + } + + public void testNegotiatorTooLate() throws Exception + { + threadPool = Executors.newCachedThreadPool(); + LifecycleUtil.activate(threadPool); + + bufferPool = Net4jUtil.createBufferPool(); + LifecycleUtil.activate(bufferPool); + + provideTransport(); + + selector.activate(); + + acceptor.setStartSynchronously(true); + acceptor.setSynchronousStartTimeout(TIMEOUT); + acceptor.getConfig().setBufferProvider(bufferPool); + acceptor.getConfig().setReceiveExecutor(threadPool); + acceptor.setSelector(selector); + acceptor.setAddress("0.0.0.0"); //$NON-NLS-1$ + acceptor.setPort(PORT); + acceptor.activate(); + + connector.getConfig().setBufferProvider(bufferPool); + connector.getConfig().setReceiveExecutor(threadPool); + connector.setSelector(selector); + connector.setHost("localhost"); //$NON-NLS-1$ + connector.setPort(PORT); + connector.connect(); + + credentialsProvider = new PasswordCredentialsProvider(CREDENTIALS); + LifecycleUtil.activate(credentialsProvider); + + responseNegotiator = new ResponseNegotiator(); + responseNegotiator.setCredentialsProvider(credentialsProvider); + responseNegotiator.activate(); + + try + { + connector.getConfig().setNegotiator(responseNegotiator); + fail("IllegalStateException expected"); //$NON-NLS-1$ + } + catch (IllegalStateException ex) + { + OM.LOG.info("Expected IllegalStateException:", ex); //$NON-NLS-1$ + } + } + + public void testRoundRobinBlockingQueue() throws Exception + { + BlockingQueue<IChannel> queue = new RoundRobinBlockingQueue<IChannel>(); + + Channel[] channels = new Channel[3]; + + for (int i = 0; i < channels.length; i++) + { + Channel c = new Channel(); + c.setID((short)i); + channels[i] = c; + } + + assertEquals(true, queue.isEmpty()); + assertNull(queue.peek()); + assertNull(queue.poll()); + + // Order will be 0000...1111...2222... + for (int i = 0; i < channels.length; i++) + { + for (int j = 0; j < 10; j++) + { + queue.put(channels[i]); + } + } + + for (int i = 0; i < 30; i++) + { + IChannel peek1 = queue.peek(); + IChannel peek2 = queue.peek(); + assertSame(peek1, peek2); + + IChannel poll = queue.poll(); + // The order should be 012012012012... + assertEquals(i % 3, poll.getID()); + assertSame(peek1, poll); + } + + assertEquals(true, queue.isEmpty()); + assertNull(queue.peek()); + assertNull(queue.poll()); + } + + /** + * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) + */ + public static final class TCP extends TCPConnectorTest + { + @Override + protected boolean useJVMTransport() + { + return false; + } + + @Override + protected boolean useSSLTransport() + { + return false; + } + } + + /** + * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) + */ + public static final class SSL extends TCPConnectorTest + { + @Override + protected boolean useJVMTransport() + { + return false; + } + + @Override + protected boolean useSSLTransport() + { + return true; + } + } +} diff --git a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/ExpectedIOTest.java b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/ExpectedIOTest.java index 6ec72c2142..ab8acbba28 100644 --- a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/ExpectedIOTest.java +++ b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/ExpectedIOTest.java @@ -1,390 +1,390 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.tests;
-
-import org.eclipse.net4j.util.concurrent.ConcurrencyUtil;
-import org.eclipse.net4j.util.io.ExpectedFileInputStream;
-import org.eclipse.net4j.util.io.ExpectedFileReader;
-import org.eclipse.net4j.util.io.IOUtil;
-
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.Reader;
-import java.io.Writer;
-
-/**
- * @author Eike Stepper
- */
-public class ExpectedIOTest extends AbstractOMTest
-{
- private Exception exception;
-
- @Override
- protected void doSetUp() throws Exception
- {
- super.doSetUp();
- exception = null;
- }
-
- public void testInputStream() throws Exception
- {
- final File file = createTempFile("ExpectedIOTest", ".tmp");
- final int LOOPS = 30;
-
- Thread producer = new Thread("PRODUCER")
- {
- @Override
- public void run()
- {
- DataOutputStream out = null;
-
- try
- {
- out = new DataOutputStream(new FileOutputStream(file));
- for (int i = 0; i < LOOPS; i++)
- {
- out.writeInt(i);
- IOUtil.ERR().println(i);
- ConcurrencyUtil.sleep(100);
- }
- }
- catch (Exception ex)
- {
- if (exception == null)
- {
- exception = ex;
- }
- }
- finally
- {
- IOUtil.close(out);
- }
- }
- };
-
- Thread consumer = new Thread("CONSUMER")
- {
- @Override
- public void run()
- {
- DataInputStream in = null;
-
- try
- {
- in = new DataInputStream(new ExpectedFileInputStream(file, LOOPS * 4));
-
- for (int i = 0; i < LOOPS; i++)
- {
- System.out.println(in.readInt());
- }
- }
- catch (Exception ex)
- {
- if (exception == null)
- {
- exception = ex;
- }
- }
- finally
- {
- IOUtil.close(in);
- }
- }
- };
-
- producer.start();
- ConcurrencyUtil.sleep(500);
- consumer.start();
-
- producer.join();
- consumer.join();
-
- if (exception != null)
- {
- throw exception;
- }
- }
-
- public void testInputStreamEOF() throws Exception
- {
- final File file = File.createTempFile("ExpectedIOTest", ".tmp");
- final int LOOPS = 30;
-
- Thread producer = new Thread("PRODUCER")
- {
- @Override
- public void run()
- {
- DataOutputStream out = null;
-
- try
- {
- out = new DataOutputStream(new FileOutputStream(file));
- for (int i = 0; i < LOOPS; i++)
- {
- out.writeInt(i);
- IOUtil.ERR().println(i);
- ConcurrencyUtil.sleep(100);
- }
- }
- catch (Exception ex)
- {
- if (exception == null)
- {
- exception = ex;
- }
- }
- finally
- {
- IOUtil.close(out);
- }
- }
- };
-
- Thread consumer = new Thread("CONSUMER")
- {
- @Override
- public void run()
- {
- DataInputStream in = null;
-
- try
- {
- in = new DataInputStream(new ExpectedFileInputStream(file, LOOPS * 4));
-
- for (int i = 0; i < LOOPS + 10; i++)
- {
- System.out.println(in.readInt());
- }
- }
- catch (Exception ex)
- {
- if (exception == null)
- {
- exception = ex;
- }
- }
- finally
- {
- IOUtil.close(in);
- }
- }
- };
-
- producer.start();
- ConcurrencyUtil.sleep(500);
- consumer.start();
-
- producer.join();
- consumer.join();
-
- if (!(exception instanceof EOFException))
- {
- throw exception;
- }
- }
-
- public void testReader() throws Exception
- {
- final File file = File.createTempFile("ExpectedIOTest", ".tmp");
- final int LOOPS = 30;
-
- Thread producer = new Thread("PRODUCER")
- {
- @Override
- public void run()
- {
- Writer out = null;
-
- try
- {
- out = new FileWriter(file);
- for (int i = 0; i < LOOPS; i++)
- {
- int c = 'a' + i;
- out.write(c);
- IOUtil.ERR().println(c);
-
- out.write(c + 1);
- IOUtil.ERR().println(c + 1);
- ConcurrencyUtil.sleep(100);
- }
- }
- catch (Exception ex)
- {
- if (exception == null)
- {
- exception = ex;
- }
- }
- finally
- {
- IOUtil.close(out);
- }
- }
- };
-
- Thread consumer = new Thread("CONSUMER")
- {
- @Override
- public void run()
- {
- Reader in = null;
-
- try
- {
- in = new ExpectedFileReader(file, LOOPS * 2);
-
- for (int i = 0; i < LOOPS; i++)
- {
- int c = in.read();
- if (c == -1)
- {
- throw new EOFException();
- }
-
- System.out.println(c);
- c = in.read();
- if (c == -1)
- {
- throw new EOFException();
- }
-
- System.out.println(c);
- }
- }
- catch (Exception ex)
- {
- if (exception == null)
- {
- exception = ex;
- }
- }
- finally
- {
- IOUtil.close(in);
- }
- }
- };
-
- producer.start();
- ConcurrencyUtil.sleep(500);
- consumer.start();
-
- producer.join();
- consumer.join();
-
- if (exception != null)
- {
- throw exception;
- }
- }
-
- public void testReaderEOF() throws Exception
- {
- final File file = File.createTempFile("ExpectedIOTest", ".tmp");
- final int LOOPS = 30;
-
- Thread producer = new Thread("PRODUCER")
- {
- @Override
- public void run()
- {
- Writer out = null;
-
- try
- {
- out = new FileWriter(file);
- for (int i = 0; i < LOOPS; i++)
- {
- int c = 'a' + i;
- out.write(c);
- IOUtil.ERR().println(c);
-
- out.write(c + 1);
- IOUtil.ERR().println(c + 1);
- ConcurrencyUtil.sleep(100);
- }
- }
- catch (Exception ex)
- {
- if (exception == null)
- {
- exception = ex;
- }
- }
- finally
- {
- IOUtil.close(out);
- }
- }
- };
-
- Thread consumer = new Thread("CONSUMER")
- {
- @Override
- public void run()
- {
- Reader in = null;
-
- try
- {
- in = new ExpectedFileReader(file, LOOPS * 2);
-
- for (int i = 0; i < LOOPS + 10; i++)
- {
- int c = in.read();
- if (c == -1)
- {
- throw new EOFException();
- }
-
- System.out.println(c);
- c = in.read();
- if (c == -1)
- {
- throw new EOFException();
- }
-
- System.out.println(c);
- }
- }
- catch (Exception ex)
- {
- if (exception == null)
- {
- exception = ex;
- }
- }
- finally
- {
- IOUtil.close(in);
- }
- }
- };
-
- producer.start();
- ConcurrencyUtil.sleep(500);
- consumer.start();
-
- producer.join();
- consumer.join();
-
- if (!(exception instanceof EOFException))
- {
- throw exception;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.tests; + +import org.eclipse.net4j.util.concurrent.ConcurrencyUtil; +import org.eclipse.net4j.util.io.ExpectedFileInputStream; +import org.eclipse.net4j.util.io.ExpectedFileReader; +import org.eclipse.net4j.util.io.IOUtil; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.EOFException; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.Reader; +import java.io.Writer; + +/** + * @author Eike Stepper + */ +public class ExpectedIOTest extends AbstractOMTest +{ + private Exception exception; + + @Override + protected void doSetUp() throws Exception + { + super.doSetUp(); + exception = null; + } + + public void testInputStream() throws Exception + { + final File file = createTempFile("ExpectedIOTest", ".tmp"); + final int LOOPS = 30; + + Thread producer = new Thread("PRODUCER") + { + @Override + public void run() + { + DataOutputStream out = null; + + try + { + out = new DataOutputStream(new FileOutputStream(file)); + for (int i = 0; i < LOOPS; i++) + { + out.writeInt(i); + IOUtil.ERR().println(i); + ConcurrencyUtil.sleep(10); + } + } + catch (Exception ex) + { + if (exception == null) + { + exception = ex; + } + } + finally + { + IOUtil.close(out); + } + } + }; + + Thread consumer = new Thread("CONSUMER") + { + @Override + public void run() + { + DataInputStream in = null; + + try + { + in = new DataInputStream(new ExpectedFileInputStream(file, LOOPS * 4)); + + for (int i = 0; i < LOOPS; i++) + { + System.out.println(in.readInt()); + } + } + catch (Exception ex) + { + if (exception == null) + { + exception = ex; + } + } + finally + { + IOUtil.close(in); + } + } + }; + + producer.start(); + ConcurrencyUtil.sleep(500); + consumer.start(); + + producer.join(); + consumer.join(); + + if (exception != null) + { + throw exception; + } + } + + public void testInputStreamEOF() throws Exception + { + final File file = createTempFile("ExpectedIOTest", ".tmp"); + final int LOOPS = 30; + + Thread producer = new Thread("PRODUCER") + { + @Override + public void run() + { + DataOutputStream out = null; + + try + { + out = new DataOutputStream(new FileOutputStream(file)); + for (int i = 0; i < LOOPS; i++) + { + out.writeInt(i); + IOUtil.ERR().println(i); + ConcurrencyUtil.sleep(10); + } + } + catch (Exception ex) + { + if (exception == null) + { + exception = ex; + } + } + finally + { + IOUtil.close(out); + } + } + }; + + Thread consumer = new Thread("CONSUMER") + { + @Override + public void run() + { + DataInputStream in = null; + + try + { + in = new DataInputStream(new ExpectedFileInputStream(file, LOOPS * 4)); + + for (int i = 0; i < LOOPS + 10; i++) + { + System.out.println(in.readInt()); + } + } + catch (Exception ex) + { + if (exception == null) + { + exception = ex; + } + } + finally + { + IOUtil.close(in); + } + } + }; + + producer.start(); + ConcurrencyUtil.sleep(500); + consumer.start(); + + producer.join(); + consumer.join(); + + if (!(exception instanceof EOFException)) + { + throw exception; + } + } + + public void testReader() throws Exception + { + final File file = createTempFile("ExpectedIOTest", ".tmp"); + final int LOOPS = 30; + + Thread producer = new Thread("PRODUCER") + { + @Override + public void run() + { + Writer out = null; + + try + { + out = new FileWriter(file); + for (int i = 0; i < LOOPS; i++) + { + int c = 'a' + i; + out.write(c); + IOUtil.ERR().println(c); + + out.write(c + 1); + IOUtil.ERR().println(c + 1); + ConcurrencyUtil.sleep(10); + } + } + catch (Exception ex) + { + if (exception == null) + { + exception = ex; + } + } + finally + { + IOUtil.close(out); + } + } + }; + + Thread consumer = new Thread("CONSUMER") + { + @Override + public void run() + { + Reader in = null; + + try + { + in = new ExpectedFileReader(file, LOOPS * 2); + + for (int i = 0; i < LOOPS; i++) + { + int c = in.read(); + if (c == -1) + { + throw new EOFException(); + } + + System.out.println(c); + c = in.read(); + if (c == -1) + { + throw new EOFException(); + } + + System.out.println(c); + } + } + catch (Exception ex) + { + if (exception == null) + { + exception = ex; + } + } + finally + { + IOUtil.close(in); + } + } + }; + + producer.start(); + ConcurrencyUtil.sleep(500); + consumer.start(); + + producer.join(); + consumer.join(); + + if (exception != null) + { + throw exception; + } + } + + public void testReaderEOF() throws Exception + { + final File file = createTempFile("ExpectedIOTest", ".tmp"); + final int LOOPS = 30; + + Thread producer = new Thread("PRODUCER") + { + @Override + public void run() + { + Writer out = null; + + try + { + out = new FileWriter(file); + for (int i = 0; i < LOOPS; i++) + { + int c = 'a' + i; + out.write(c); + IOUtil.ERR().println(c); + + out.write(c + 1); + IOUtil.ERR().println(c + 1); + ConcurrencyUtil.sleep(10); + } + } + catch (Exception ex) + { + if (exception == null) + { + exception = ex; + } + } + finally + { + IOUtil.close(out); + } + } + }; + + Thread consumer = new Thread("CONSUMER") + { + @Override + public void run() + { + Reader in = null; + + try + { + in = new ExpectedFileReader(file, LOOPS * 2); + + for (int i = 0; i < LOOPS + 10; i++) + { + int c = in.read(); + if (c == -1) + { + throw new EOFException(); + } + + System.out.println(c); + c = in.read(); + if (c == -1) + { + throw new EOFException(); + } + + System.out.println(c); + } + } + catch (Exception ex) + { + if (exception == null) + { + exception = ex; + } + } + finally + { + IOUtil.close(in); + } + } + }; + + producer.start(); + ConcurrencyUtil.sleep(500); + consumer.start(); + + producer.join(); + consumer.join(); + + if (!(exception instanceof EOFException)) + { + throw exception; + } + } +} diff --git a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/QueueWorkerWorkSerializerTest.java b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/QueueWorkerWorkSerializerTest.java index eaead2bd36..23768789ea 100644 --- a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/QueueWorkerWorkSerializerTest.java +++ b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/QueueWorkerWorkSerializerTest.java @@ -1,216 +1,211 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Andre Dietisheim - initial API and implementation
- * Eike Stepper - maintenance
- */
-package org.eclipse.net4j.util.tests;
-
-import org.eclipse.net4j.util.concurrent.QueueWorkerWorkSerializer;
-import org.eclipse.net4j.util.io.IOUtil;
-
-import java.util.Random;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * A test for {@link QueueWorkerWorkSerializer}.
- *
- * @author Andre Dietisheim
- */
-public class QueueWorkerWorkSerializerTest extends AbstractOMTest
-{
- /** timeout to wait for execution of all work units. */
- private static final int WORK_COMPLETION_TIMEOUT = 10000;
-
- /** number of work producer threads. */
- private static final int NUM_WORKPRODUCER_THREADS = 10;
-
- /** number of working units to execute. */
- private static final int NUM_WORK = 40;
-
- /** the latch to wait on for the execution of all working units. */
- private CountDownLatch workConsumedLatch;
-
- /** The number of working units created. */
- private AtomicInteger workProduced;
-
- /** The thread pool to execute the work unit producers in. */
- private ExecutorService threadPool;
-
- /** The queue worker to submit the work units to. */
- private QueueWorkerWorkSerializer queueWorker;
-
- public QueueWorkerWorkSerializerTest()
- {
- }
-
- /**
- * Test that asserts that all submitted workers are executed
- */
- public void testAllWorkSubmittedIsConsumed() throws Throwable
- {
- createWorkProducerThreads(new WorkProducerFactory()
- {
- public WorkProducer createWorkProducer()
- {
- return new WorkProducer()
- {
- @Override
- protected Runnable createWork(int id)
- {
- return new Work(id);
- }
- };
- }
- });
-
- waitForAllWorkExecuted();
- assertEquals(workProduced.get(), NUM_WORK - workConsumedLatch.getCount());
- }
-
- /**
- * If the workers throw Exceptions, the QueueWorker stops executing work (deactivates its working thread). Therefore
- * the first work unit gets consumed, the rest is not executed any more.
- */
- public void testGivenWorkExceptionInWorkAllWorkSubmittedOnlyTheFirstWorkerIsConsumed() throws Throwable
- {
- createWorkProducerThreads(new WorkProducerFactory()
- {
- public WorkProducer createWorkProducer()
- {
- return new WorkProducer()
- {
- @Override
- protected Runnable createWork(int id)
- {
- return new Work(id)
- {
- @Override
- public void run()
- {
- super.run();
- throw new RuntimeException("dummy exception to simulate an error in executed workers");
- }
- };
- }
- };
- }
- });
-
- waitForAllWorkExecuted();
- assertEquals(NUM_WORK, workProduced.get());
- assertEquals(1, NUM_WORK - workConsumedLatch.getCount());
- }
-
- private void waitForAllWorkExecuted() throws InterruptedException
- {
- if (!workConsumedLatch.await(WORK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS))
- {
- IOUtil.OUT().println("timeout occured before all workers were executed");
- }
- }
-
- private void createWorkProducerThreads(WorkProducerFactory factory)
- {
- for (int i = 0; i < NUM_WORKPRODUCER_THREADS; i++)
- {
- threadPool.submit(factory.createWorkProducer());
- }
- }
-
- /**
- * A factory that creates work units.
- */
- private static interface WorkProducerFactory
- {
- public WorkProducer createWorkProducer();
- }
-
- /**
- * A Runnable that creates work units
- */
- private abstract class WorkProducer implements Runnable
- {
- private Random random = new Random();
-
- /**
- * Produce work: add work units to the queue worker
- */
- public void run()
- {
- try
- {
- int currentWorkProduced;
- while ((currentWorkProduced = workProduced.getAndIncrement()) < NUM_WORK)
- {
- queueWorker.addWork(createWork(currentWorkProduced));
- Thread.sleep(random.nextInt(1000));
- }
-
- // correct last increment
- workProduced.decrementAndGet();
- IOUtil.OUT().println("work producer " + this + " stopped its production");
- }
- catch (InterruptedException ex)
- {
- return;
- }
- }
-
- /**
- * Creates a working unit (runnable).
- *
- * @param id
- * the id
- * @return the runnable
- */
- protected abstract Runnable createWork(int id);
- }
-
- /**
- * A simple work unit to be executed in the queueWorker.
- *
- * @author Andre Dietisheim
- */
- class Work implements Runnable
- {
- private final int id;
-
- private Work(int id)
- {
- this.id = id;
- IOUtil.OUT().println("work unit " + id + " created");
- }
-
- public void run()
- {
- workConsumedLatch.countDown();
- IOUtil.OUT().println("work unit " + id + " consumed");
- }
- }
-
- @Override
- public void setUp()
- {
- threadPool = Executors.newFixedThreadPool(NUM_WORKPRODUCER_THREADS);
- workConsumedLatch = new CountDownLatch(NUM_WORK);
- queueWorker = new QueueWorkerWorkSerializer();
- workProduced = new AtomicInteger(0);
- }
-
- @Override
- public void tearDown()
- {
- threadPool.shutdown();
- queueWorker.dispose();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andre Dietisheim - initial API and implementation + * Eike Stepper - maintenance + */ +package org.eclipse.net4j.util.tests; + +import org.eclipse.net4j.util.concurrent.QueueWorkerWorkSerializer; +import org.eclipse.net4j.util.io.IOUtil; + +import java.util.Random; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * A test for {@link QueueWorkerWorkSerializer}. + * + * @author Andre Dietisheim + */ +public class QueueWorkerWorkSerializerTest extends AbstractOMTest +{ + /** timeout to wait for execution of all work units. */ + private static final int WORK_COMPLETION_TIMEOUT = 10000; + + /** number of work producer threads. */ + private static final int NUM_WORKPRODUCER_THREADS = 10; + + /** number of working units to execute. */ + private static final int NUM_WORK = 40; + + /** the latch to wait on for the execution of all working units. */ + private CountDownLatch workConsumedLatch; + + /** The number of working units created. */ + private AtomicInteger workProduced; + + /** The thread pool to execute the work unit producers in. */ + private ExecutorService threadPool; + + /** The queue worker to submit the work units to. */ + private QueueWorkerWorkSerializer queueWorker; + + @Override + public void setUp() + { + threadPool = Executors.newFixedThreadPool(NUM_WORKPRODUCER_THREADS); + workConsumedLatch = new CountDownLatch(NUM_WORK); + queueWorker = new QueueWorkerWorkSerializer(); + workProduced = new AtomicInteger(0); + } + + @Override + public void tearDown() + { + threadPool.shutdown(); + queueWorker.dispose(); + } + + /** + * Test that asserts that all submitted workers are executed + */ + public void testAllWorkSubmittedIsConsumed() throws Throwable + { + createWorkProducerThreads(new WorkProducerFactory() + { + public WorkProducer createWorkProducer() + { + return new WorkProducer() + { + @Override + protected Runnable createWork(int id) + { + return new Work(id); + } + }; + } + }); + + waitForAllWorkExecuted(); + assertEquals(workProduced.get(), NUM_WORK - workConsumedLatch.getCount()); + } + + /** + * If the workers throw Exceptions, the QueueWorker stops executing work (deactivates its working thread). Therefore + * the first work unit gets consumed, the rest is not executed any more. + */ + public void testGivenWorkExceptionInWorkAllWorkSubmittedOnlyTheFirstWorkerIsConsumed() throws Throwable + { + createWorkProducerThreads(new WorkProducerFactory() + { + public WorkProducer createWorkProducer() + { + return new WorkProducer() + { + @Override + protected Runnable createWork(int id) + { + return new Work(id) + { + @Override + public void run() + { + super.run(); + throw new RuntimeException("dummy exception to simulate an error in executed workers"); + } + }; + } + }; + } + }); + + waitForAllWorkExecuted(); + assertEquals(NUM_WORK, workProduced.get()); + } + + private void waitForAllWorkExecuted() throws InterruptedException + { + if (!workConsumedLatch.await(WORK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS)) + { + IOUtil.OUT().println("timeout occured before all workers were executed"); + } + } + + private void createWorkProducerThreads(WorkProducerFactory factory) + { + for (int i = 0; i < NUM_WORKPRODUCER_THREADS; i++) + { + threadPool.submit(factory.createWorkProducer()); + } + } + + /** + * A factory that creates work units. + */ + private static interface WorkProducerFactory + { + public WorkProducer createWorkProducer(); + } + + /** + * A Runnable that creates work units + */ + private abstract class WorkProducer implements Runnable + { + private Random random = new Random(); + + /** + * Produce work: add work units to the queue worker + */ + public void run() + { + try + { + int currentWorkProduced; + while ((currentWorkProduced = workProduced.getAndIncrement()) < NUM_WORK) + { + queueWorker.addWork(createWork(currentWorkProduced)); + Thread.sleep(random.nextInt(1000)); + } + + // correct last increment + workProduced.decrementAndGet(); + IOUtil.OUT().println("work producer " + this + " stopped its production"); + } + catch (InterruptedException ex) + { + return; + } + } + + /** + * Creates a working unit (runnable). + * + * @param id + * the id + * @return the runnable + */ + protected abstract Runnable createWork(int id); + } + + /** + * A simple work unit to be executed in the queueWorker. + * + * @author Andre Dietisheim + */ + class Work implements Runnable + { + private final int id; + + private Work(int id) + { + this.id = id; + IOUtil.OUT().println("work unit " + id + " created"); + } + + public void run() + { + workConsumedLatch.countDown(); + IOUtil.OUT().println("work unit " + id + " consumed"); + } + } +} diff --git a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/SortedFileMapTest.java b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/SortedFileMapTest.java index 72404d7afe..342c75326a 100644 --- a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/SortedFileMapTest.java +++ b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/SortedFileMapTest.java @@ -1,108 +1,108 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.tests;
-
-import org.eclipse.net4j.util.io.ExtendedDataInput;
-import org.eclipse.net4j.util.io.ExtendedDataOutput;
-import org.eclipse.net4j.util.io.IOUtil;
-import org.eclipse.net4j.util.io.SortedFileMap;
-
-import java.io.File;
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- */
-public class SortedFileMapTest extends AbstractOMTest
-{
- public void testMap() throws Exception
- {
- File file = new File("testMap.dat"); //$NON-NLS-1$
- if (file.exists())
- {
- file.delete();
- }
-
- SortedFileMap<Integer, String> map = null;
-
- try
- {
- map = new TestMap(file);
- for (int i = 0; i < 500; i++)
- {
- map.put(i, "Value " + i); //$NON-NLS-1$
- }
-
- for (int i = 0; i < 500; i++)
- {
- String value = map.get(i);
- IOUtil.OUT().println(value);
- }
- }
- finally
- {
- IOUtil.close(map);
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static final class TestMap extends SortedFileMap<Integer, String>
- {
- public TestMap(File file)
- {
- super(file, "rw"); //$NON-NLS-1$
- }
-
- @Override
- public int getKeySize()
- {
- return 4;
- }
-
- @Override
- protected Integer readKey(ExtendedDataInput in) throws IOException
- {
- return in.readInt();
- }
-
- @Override
- protected void writeKey(ExtendedDataOutput out, Integer key) throws IOException
- {
- out.writeInt(key);
- }
-
- @Override
- public int getValueSize()
- {
- return 20;
- }
-
- @Override
- protected String readValue(ExtendedDataInput in) throws IOException
- {
- return in.readString();
- }
-
- @Override
- protected void writeValue(ExtendedDataOutput out, String value) throws IOException
- {
- byte[] bytes = value.getBytes();
- if (bytes.length + 4 > getValueSize())
- {
- throw new IllegalArgumentException("Value size of " + getValueSize() + " exceeded: " + value); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- out.writeByteArray(bytes);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.tests; + +import org.eclipse.net4j.util.io.ExtendedDataInput; +import org.eclipse.net4j.util.io.ExtendedDataOutput; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.io.SortedFileMap; + +import java.io.File; +import java.io.IOException; + +/** + * @author Eike Stepper + */ +public class SortedFileMapTest extends AbstractOMTest +{ + public void testMap() throws Exception + { + File file = createTempFile("testMap-", ".dat"); //$NON-NLS-1$ + if (file.exists()) + { + file.delete(); + } + + SortedFileMap<Integer, String> map = null; + + try + { + map = new TestMap(file); + for (int i = 0; i < 500; i++) + { + map.put(i, "Value " + i); //$NON-NLS-1$ + } + + for (int i = 0; i < 500; i++) + { + String value = map.get(i); + IOUtil.OUT().println(value); + } + } + finally + { + IOUtil.close(map); + } + } + + /** + * @author Eike Stepper + */ + public static final class TestMap extends SortedFileMap<Integer, String> + { + public TestMap(File file) + { + super(file, "rw"); //$NON-NLS-1$ + } + + @Override + public int getKeySize() + { + return 4; + } + + @Override + protected Integer readKey(ExtendedDataInput in) throws IOException + { + return in.readInt(); + } + + @Override + protected void writeKey(ExtendedDataOutput out, Integer key) throws IOException + { + out.writeInt(key); + } + + @Override + public int getValueSize() + { + return 20; + } + + @Override + protected String readValue(ExtendedDataInput in) throws IOException + { + return in.readString(); + } + + @Override + protected void writeValue(ExtendedDataOutput out, String value) throws IOException + { + byte[] bytes = value.getBytes(); + if (bytes.length + 4 > getValueSize()) + { + throw new IllegalArgumentException("Value size of " + getValueSize() + " exceeded: " + value); //$NON-NLS-1$ //$NON-NLS-2$ + } + + out.writeByteArray(bytes); + } + } +} diff --git a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/StringCompressorTest.java b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/StringCompressorTest.java index 539c517b2c..4296097445 100644 --- a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/StringCompressorTest.java +++ b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/StringCompressorTest.java @@ -1,291 +1,290 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.tests;
-
-import org.eclipse.net4j.util.io.ExtendedDataInput;
-import org.eclipse.net4j.util.io.ExtendedDataInputStream;
-import org.eclipse.net4j.util.io.ExtendedDataOutputStream;
-import org.eclipse.net4j.util.io.StringCompressor;
-
-import java.io.IOException;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-import java.util.Random;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author Eike Stepper
- */
-public class StringCompressorTest extends AbstractOMTest
-{
- private static long SLEEP_WRITER = 1;
-
- private static long SLEEP_READER = 0;
-
- private static final String[] strings = createStrings(50, 837456);
-
- private static final int[] indices = createIndices(100, 50, 9087346);
-
- private StringCompressor.Counting client;
-
- private StringCompressor.Counting server;
-
- public void testSingleStreamToServer() throws Exception
- {
- run(1, 0);
- }
-
- public void testSingleStreamToClient() throws Exception
- {
- run(0, 1);
- }
-
- public void testBidi1() throws Exception
- {
- run(1, 1);
- }
-
- public void testBidi10() throws Exception
- {
- run(10, 10);
- }
-
- public void testBidi1Plus10() throws Exception
- {
- run(1, 1);
- run(10, 10);
- }
-
- @Override
- protected void doSetUp() throws Exception
- {
- super.doSetUp();
- client = new StringCompressor.Counting(true);
- server = new StringCompressor.Counting(false);
- }
-
- @Override
- protected void doTearDown() throws Exception
- {
- System.out.println("Strings read by client compressor: " + client.getStringsRead());
- System.out.println("Strings read by server compressor: " + server.getStringsRead());
- System.out.println("Strings written by client compressor: " + client.getStringsWritten());
- System.out.println("Strings written by server compressor: " + server.getStringsWritten());
- super.doTearDown();
- }
-
- private void run(int toServer, int toClient) throws IOException, InterruptedException
- {
- CountDownLatch latch = new CountDownLatch(toServer + toClient);
- while (toServer > 0 || toClient > 0)
- {
- if (toServer > 0)
- {
- --toServer;
- new Stream(latch, client, server).start();
- }
-
- if (toClient > 0)
- {
- --toClient;
- new Stream(latch, server, client).start();
- }
- }
-
- latch.await(300, TimeUnit.SECONDS);
- }
-
- private static String[] createStrings(int count, long seed)
- {
- Random random = new Random(seed);
- String[] result = new String[count];
- for (int i = 0; i < result.length; i++)
- {
- String str = "";
- int length = next(random) % 13;
- for (int j = 0; j < length + 1; j++)
- {
- int val = next(random);
- str += Integer.toString(val, 36);
- }
-
- System.out.println(str);
- result[i] = str;
- }
-
- return result;
- }
-
- private static int[] createIndices(int count, int range, long seed)
- {
- Random random = new Random(seed);
- int[] result = new int[count];
- for (int i = 0; i < result.length; i++)
- {
- result[i] = next(random) % range;
- }
-
- return result;
- }
-
- private static int next(Random random)
- {
- for (;;)
- {
- int val = random.nextInt();
- if (val > 0)
- {
- return val;
- }
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class Stream extends Thread
- {
- private CountDownLatch latch;
-
- private Writer writer;
-
- private Reader reader;
-
- public Stream(CountDownLatch latch, StringCompressor writer, StringCompressor reader) throws IOException
- {
- this.latch = latch;
- this.writer = new Writer(writer);
- this.reader = new Reader(reader, this.writer);
- }
-
- @Override
- public void run()
- {
- try
- {
- reader.start();
- writer.start();
-
- reader.join();
- writer.join();
-
- latch.countDown();
- }
- catch (Exception ex)
- {
- ex.printStackTrace();
- }
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class Writer extends Thread
- {
- private StringCompressor compressor;
-
- private PipedOutputStream pipe;
-
- private Exception exception;
-
- public Writer(StringCompressor compressor)
- {
- this.compressor = compressor;
- pipe = new PipedOutputStream();
- }
-
- public PipedOutputStream getPipe()
- {
- return pipe;
- }
-
- public Exception getException()
- {
- return exception;
- }
-
- @Override
- public void run()
- {
- try
- {
- ExtendedDataOutputStream out = new ExtendedDataOutputStream(pipe);
- for (int i = 0; i < indices.length; i++)
- {
- int index = indices[i];
- msg(getName() + " --> " + i);
- compressor.write(out, strings[index]);
- if (SLEEP_WRITER > 0)
- {
- Thread.sleep(SLEEP_WRITER);
- }
- }
- }
- catch (Exception ex)
- {
- exception = ex;
- ex.printStackTrace();
- }
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class Reader extends Thread
- {
- private StringCompressor compressor;
-
- private PipedInputStream pipe;
-
- private Exception exception;
-
- public Reader(StringCompressor compressor, Writer writer) throws IOException
- {
- this.compressor = compressor;
- pipe = new PipedInputStream(writer.getPipe());
- }
-
- public Exception getException()
- {
- return exception;
- }
-
- @Override
- public void run()
- {
- try
- {
- ExtendedDataInput in = new ExtendedDataInputStream(pipe);
- for (int i = 0; i < indices.length; i++)
- {
- int index = indices[i];
- msg(getName() + " --> " + i);
- String toBeRead = strings[index];
-
- String read = compressor.read(in);
- assertEquals(toBeRead, read);
- if (SLEEP_READER > 0)
- {
- Thread.sleep(SLEEP_READER);
- }
- }
- }
- catch (Exception ex)
- {
- exception = ex;
- ex.printStackTrace();
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.tests; + +import org.eclipse.net4j.util.io.ExtendedDataInput; +import org.eclipse.net4j.util.io.ExtendedDataInputStream; +import org.eclipse.net4j.util.io.ExtendedDataOutputStream; +import org.eclipse.net4j.util.io.StringCompressor; + +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.util.Random; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * @author Eike Stepper + */ +public class StringCompressorTest extends AbstractOMTest +{ + private static long SLEEP_WRITER = 1; + + private static long SLEEP_READER = 0; + + private static final String[] strings = createStrings(50, 837456); + + private static final int[] indices = createIndices(100, 50, 9087346); + + private StringCompressor.Counting client; + + private StringCompressor.Counting server; + + public void testSingleStreamToServer() throws Exception + { + run(1, 0); + } + + public void testSingleStreamToClient() throws Exception + { + run(0, 1); + } + + public void testBidi1() throws Exception + { + run(1, 1); + } + + public void testBidi10() throws Exception + { + run(10, 10); + } + + public void testBidi1Plus10() throws Exception + { + run(1, 1); + run(10, 10); + } + + @Override + protected void doSetUp() throws Exception + { + super.doSetUp(); + client = new StringCompressor.Counting(true); + server = new StringCompressor.Counting(false); + } + + @Override + protected void doTearDown() throws Exception + { + System.out.println("Strings read by client compressor: " + client.getStringsRead()); + System.out.println("Strings read by server compressor: " + server.getStringsRead()); + System.out.println("Strings written by client compressor: " + client.getStringsWritten()); + System.out.println("Strings written by server compressor: " + server.getStringsWritten()); + super.doTearDown(); + } + + private void run(int toServer, int toClient) throws IOException, InterruptedException + { + CountDownLatch latch = new CountDownLatch(toServer + toClient); + while (toServer > 0 || toClient > 0) + { + if (toServer > 0) + { + --toServer; + new Stream(latch, client, server).start(); + } + + if (toClient > 0) + { + --toClient; + new Stream(latch, server, client).start(); + } + } + + latch.await(300, TimeUnit.SECONDS); + } + + private static String[] createStrings(int count, long seed) + { + Random random = new Random(seed); + String[] result = new String[count]; + for (int i = 0; i < result.length; i++) + { + String str = ""; + int length = next(random) % 13; + for (int j = 0; j < length + 1; j++) + { + int val = next(random); + str += Integer.toString(val, 36); + } + + result[i] = str; + } + + return result; + } + + private static int[] createIndices(int count, int range, long seed) + { + Random random = new Random(seed); + int[] result = new int[count]; + for (int i = 0; i < result.length; i++) + { + result[i] = next(random) % range; + } + + return result; + } + + private static int next(Random random) + { + for (;;) + { + int val = random.nextInt(); + if (val > 0) + { + return val; + } + } + } + + /** + * @author Eike Stepper + */ + public static class Stream extends Thread + { + private CountDownLatch latch; + + private Writer writer; + + private Reader reader; + + public Stream(CountDownLatch latch, StringCompressor writer, StringCompressor reader) throws IOException + { + this.latch = latch; + this.writer = new Writer(writer); + this.reader = new Reader(reader, this.writer); + } + + @Override + public void run() + { + try + { + reader.start(); + writer.start(); + + reader.join(); + writer.join(); + + latch.countDown(); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + } + + /** + * @author Eike Stepper + */ + public static class Writer extends Thread + { + private StringCompressor compressor; + + private PipedOutputStream pipe; + + private Exception exception; + + public Writer(StringCompressor compressor) + { + this.compressor = compressor; + pipe = new PipedOutputStream(); + } + + public PipedOutputStream getPipe() + { + return pipe; + } + + public Exception getException() + { + return exception; + } + + @Override + public void run() + { + try + { + ExtendedDataOutputStream out = new ExtendedDataOutputStream(pipe); + for (int i = 0; i < indices.length; i++) + { + int index = indices[i]; + msg(getName() + " --> " + i); + compressor.write(out, strings[index]); + if (SLEEP_WRITER > 0) + { + Thread.sleep(SLEEP_WRITER); + } + } + } + catch (Exception ex) + { + exception = ex; + ex.printStackTrace(); + } + } + } + + /** + * @author Eike Stepper + */ + public static class Reader extends Thread + { + private StringCompressor compressor; + + private PipedInputStream pipe; + + private Exception exception; + + public Reader(StringCompressor compressor, Writer writer) throws IOException + { + this.compressor = compressor; + pipe = new PipedInputStream(writer.getPipe()); + } + + public Exception getException() + { + return exception; + } + + @Override + public void run() + { + try + { + ExtendedDataInput in = new ExtendedDataInputStream(pipe); + for (int i = 0; i < indices.length; i++) + { + int index = indices[i]; + msg(getName() + " --> " + i); + String toBeRead = strings[index]; + + String read = compressor.read(in); + assertEquals(toBeRead, read); + if (SLEEP_READER > 0) + { + Thread.sleep(SLEEP_READER); + } + } + } + catch (Exception ex) + { + exception = ex; + ex.printStackTrace(); + } + } + } +} diff --git a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/UUIDGeneratorTest.java b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/UUIDGeneratorTest.java index f786d11fd4..48c1a77464 100644 --- a/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/UUIDGeneratorTest.java +++ b/plugins/org.eclipse.net4j.tests/src/org/eclipse/net4j/util/tests/UUIDGeneratorTest.java @@ -1,59 +1,59 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.tests;
-
-import org.eclipse.net4j.util.UUIDGenerator;
-
-/**
- * @author Eike Stepper
- * @since 4.0
- */
-public class UUIDGeneratorTest extends AbstractOMTest
-{
- public void testCodec()
- {
- byte[] uuid = new byte[16];
- long start = System.currentTimeMillis();
-
- for (int b3 = Byte.MIN_VALUE; b3 <= Byte.MAX_VALUE; b3++)
- {
- for (int b2 = Byte.MIN_VALUE; b2 <= Byte.MAX_VALUE; b2++)
- {
- // System.out.println(b3 + ", " + b2);
- for (int b1 = Byte.MIN_VALUE; b1 <= Byte.MAX_VALUE; b1++)
- {
- for (int off = 0; off < 13; off++)
- {
- check(uuid, b1, b2, b3, off);
- }
- }
- }
- }
-
- long millis = System.currentTimeMillis() - start;
- System.out.println("Millis: " + millis);
- }
-
- private static void check(byte[] uuid, int b1, int b2, int b3, int off)
- {
- uuid[0 + off] = (byte)b1;
- uuid[2 + off] = (byte)b2;
- uuid[3 + off] = (byte)b3;
-
- String encoded = UUIDGenerator.DEFAULT.encode(uuid);
- byte[] decoded = UUIDGenerator.DEFAULT.decode(encoded);
-
- for (int i = 0; i < 3; i++)
- {
- assertEquals(uuid[i + off], decoded[i + off]);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.tests; + +import org.eclipse.net4j.util.UUIDGenerator; +import org.eclipse.net4j.util.io.IOUtil; + +/** + * @author Eike Stepper + * @since 4.0 + */ +public class UUIDGeneratorTest extends AbstractOMTest +{ + public void testCodec() + { + byte[] uuid = new byte[16]; + long start = System.currentTimeMillis(); + + for (int b3 = Byte.MIN_VALUE; b3 <= Byte.MAX_VALUE; b3++) + { + IOUtil.OUT().println(b3); + for (int b2 = Byte.MIN_VALUE; b2 <= Byte.MAX_VALUE; b2++) + { + for (int b1 = Byte.MIN_VALUE; b1 <= Byte.MAX_VALUE; b1++) + { + for (int off = 0; off < 13; off++) + { + check(uuid, b1, b2, b3, off); + } + } + } + } + + IOUtil.OUT().println("Millis: " + (System.currentTimeMillis() - start)); + } + + private static void check(byte[] uuid, int b1, int b2, int b3, int off) + { + uuid[0 + off] = (byte)b1; + uuid[2 + off] = (byte)b2; + uuid[3 + off] = (byte)b3; + + String encoded = UUIDGenerator.DEFAULT.encode(uuid); + byte[] decoded = UUIDGenerator.DEFAULT.decode(encoded); + + for (int i = 0; i < 3; i++) + { + assertEquals(uuid[i + off], decoded[i + off]); + } + } +} |