PageRenderTime 58ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/com/limegroup/gnutella/LimeTestUtils.java

https://github.com/r3n/limewire5-ruby
Java | 318 lines | 220 code | 44 blank | 54 comment | 10 complexity | e2882fb97f4147a3141a48b2efda837d MD5 | raw file
Possible License(s): LGPL-2.1
  1. package com.limegroup.gnutella;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.net.InetSocketAddress;
  8. import java.net.Socket;
  9. import java.net.SocketTimeoutException;
  10. import java.util.ArrayList;
  11. import java.util.Arrays;
  12. import java.util.List;
  13. import java.util.concurrent.ExecutionException;
  14. import java.util.concurrent.Future;
  15. import org.hamcrest.BaseMatcher;
  16. import org.hamcrest.Description;
  17. import org.hamcrest.Matcher;
  18. import org.limewire.io.IOUtils;
  19. import org.limewire.io.IpPort;
  20. import org.limewire.nio.NIODispatcher;
  21. import org.limewire.util.AssertComparisons;
  22. import org.limewire.util.Base32;
  23. import org.limewire.net.TLSManager;
  24. import org.limewire.net.address.AddressEvent;
  25. import org.limewire.listener.ListenerSupport;
  26. import com.google.inject.AbstractModule;
  27. import com.google.inject.Guice;
  28. import com.google.inject.Injector;
  29. import com.google.inject.Module;
  30. import com.google.inject.Stage;
  31. import com.google.inject.TypeLiteral;
  32. import com.google.inject.util.Modules;
  33. import com.limegroup.gnutella.connection.BlockingConnectionFactory;
  34. import com.limegroup.gnutella.connection.BlockingConnectionFactoryImpl;
  35. import com.limegroup.gnutella.stubs.ActivityCallbackStub;
  36. import com.limegroup.gnutella.stubs.NetworkManagerStub;
  37. @SuppressWarnings("deprecation")
  38. public class LimeTestUtils {
  39. public static void waitForNIO() throws InterruptedException {
  40. Future<?> future = NIODispatcher.instance().getScheduledExecutorService().submit(new Runnable() {
  41. public void run() {
  42. }
  43. });
  44. try {
  45. future.get();
  46. } catch(ExecutionException ee) {
  47. throw new IllegalStateException(ee);
  48. }
  49. // the runnable is run at the beginning of the processing cycle so
  50. // we need a second runnable to make sure the cycle has been completed
  51. future = NIODispatcher.instance().getScheduledExecutorService().submit(new Runnable() {
  52. public void run() {
  53. }
  54. });
  55. try {
  56. future.get();
  57. } catch(ExecutionException ee) {
  58. throw new IllegalStateException(ee);
  59. }
  60. }
  61. public static void setActivityCallBack(ActivityCallback cb)
  62. throws Exception {
  63. throw new RuntimeException("fix me");
  64. }
  65. public static void readBytes(InputStream in, long count) throws IOException {
  66. for (long i = 0; i < count; i++) {
  67. try {
  68. if (in.read() == -1) {
  69. throw new AssertionError("Unexpected end of stream after "
  70. + i + " bytes");
  71. }
  72. } catch (SocketTimeoutException e) {
  73. throw new AssertionError("Timeout while reading " + count
  74. + " bytes (read " + i + " bytes)");
  75. }
  76. }
  77. }
  78. /**
  79. * generate a dummy repeating String of the specified length
  80. */
  81. public static String generateRepeatingStringByLength(String stringtoRepeat, int length) {
  82. StringBuilder longStr = new StringBuilder();
  83. while (longStr.length() < length) {
  84. longStr.append(stringtoRepeat);
  85. }
  86. return longStr.substring(0, length);
  87. }
  88. /**
  89. * Simple copy. Horrible performance for large files.
  90. * Good performance for alphabets.
  91. */
  92. public static void copyFile(File source, File dest) throws Exception {
  93. FileInputStream fis = new FileInputStream(source);
  94. try {
  95. FileOutputStream fos = new FileOutputStream(dest);
  96. try {
  97. int read = fis.read();
  98. while(read != -1) {
  99. fos.write(read);
  100. read = fis.read();
  101. }
  102. } finally {
  103. fos.close();
  104. }
  105. } finally {
  106. fis.close();
  107. }
  108. }
  109. /**
  110. * Creates subdirs in tmp dir and ensures that they are deleted on JVM
  111. * exit.
  112. */
  113. public static File[] createTmpDirs(String... dirs) {
  114. File tmpDir = new File(System.getProperty("java.io.tmpdir"));
  115. AssertComparisons.assertTrue(tmpDir.isDirectory());
  116. return createDirs(tmpDir, dirs);
  117. }
  118. /**
  119. * Creates <code>dirs</code> as subdirs of <code>parent</code> and ensures
  120. * that they are deleted on JVM exit.
  121. */
  122. public static File[] createDirs(File parent, String... dirs) {
  123. List<File> list = new ArrayList<File>(dirs.length);
  124. for (String name : dirs) {
  125. File dir = new File(parent, name);
  126. AssertComparisons.assertTrue(dir.mkdirs() || dir.exists());
  127. // Make sure it's clean!
  128. deleteFiles(dir.listFiles());
  129. list.add(dir);
  130. while (!dir.equals(parent)) {
  131. dir.deleteOnExit();
  132. dir = dir.getParentFile();
  133. }
  134. }
  135. return list.toArray(new File[list.size()]);
  136. }
  137. /** Deletes all files listed. */
  138. public static void deleteFiles(File...files) {
  139. for(int i = 0; i < files.length; i++)
  140. files[i].delete();
  141. }
  142. /**
  143. * Creates the Guice injector with the limewire default modules and the
  144. * test module that can override bindings in the former modules.
  145. *
  146. * @param module the test modules that can override bindings
  147. * @param callbackClass the class that is used as a callback
  148. * @return the injector
  149. */
  150. public static Injector createInjector(Class<? extends ActivityCallback> callbackClass, Module...modules) {
  151. return createInjector(Stage.DEVELOPMENT, callbackClass, modules);
  152. }
  153. public static Injector createInjector(Stage stage, Class<? extends ActivityCallback> callbackClass, Module...modules) {
  154. Module combinedReplacements = Modules.combine(modules);
  155. Module combinedOriginals = Modules.combine(new LimeWireCoreModule(callbackClass), new BlockingConnectionFactoryModule());
  156. Module replaced = Modules.override(combinedOriginals).with(combinedReplacements);
  157. return Guice.createInjector(stage, replaced);
  158. }
  159. /**
  160. * Wraps {@link #createInjector(Module, Class) createInjector(Module, ActivityCallbackStub.class)}.
  161. */
  162. public static Injector createInjector(Module... modules) {
  163. return createInjector(ActivityCallbackStub.class, modules);
  164. }
  165. public static Injector createInjector(Stage stage, Module... modules) {
  166. return createInjector(stage, ActivityCallbackStub.class, modules);
  167. }
  168. /**
  169. * Creates the Guice injector with the limewire default modules and the
  170. * test module that can override bindings in the former modules.
  171. *
  172. * Also starts the {@link LifecycleManager}.
  173. *
  174. * @param module the test modules that can override bindings
  175. * @param callbackClass the class that is used as a callback
  176. * @return the injector
  177. */
  178. public static Injector createInjectorAndStart(Class<? extends ActivityCallback> callbackClass, Module...modules) {
  179. // Use PRODUCTION to ensure all Services are created.
  180. Injector injector = createInjector(Stage.PRODUCTION, callbackClass, modules);
  181. LifecycleManager lifecycleManager = injector.getInstance(LifecycleManager.class);
  182. lifecycleManager.start();
  183. return injector;
  184. }
  185. /**
  186. * Wraps {@link #createInjectorAndStart(Module, Class) createInjectorAndStart(Module, ActivityCallbackStub.class)}.
  187. */
  188. public static Injector createInjectorAndStart(Module...modules) {
  189. return createInjectorAndStart(ActivityCallbackStub.class, modules);
  190. }
  191. public static class NetworkManagerStubModule extends AbstractModule {
  192. private final NetworkManagerStub networkManagerStub;
  193. public NetworkManagerStubModule(NetworkManagerStub networkManagerStub) {
  194. this.networkManagerStub = networkManagerStub;
  195. }
  196. @Override
  197. protected void configure() {
  198. bind(NetworkManager.class).toInstance(networkManagerStub);
  199. bind(TLSManager.class).toInstance(networkManagerStub);
  200. bind(new TypeLiteral<ListenerSupport<AddressEvent>>(){}).toInstance(networkManagerStub);
  201. }
  202. }
  203. public static class BlockingConnectionFactoryModule extends AbstractModule {
  204. @Override
  205. protected void configure() {
  206. bind(BlockingConnectionFactory.class).to(BlockingConnectionFactoryImpl.class);
  207. }
  208. }
  209. /**
  210. * Establishes an incoming connection. It is necessary to send a proper
  211. * connect back string. We ignore exceptions because various components
  212. * may have been stubbed out in the specific test case.
  213. * @param port where to establish the connection to.
  214. */
  215. public static void establishIncoming(int port) {
  216. Socket s = null;
  217. try {
  218. s = new Socket();
  219. s.connect(new InetSocketAddress("127.0.0.1",port));
  220. s.getOutputStream().write("CONNECT ".getBytes());
  221. s.getOutputStream().flush();
  222. s.close();
  223. } catch (IOException ignore) {}
  224. finally {
  225. IOUtils.close(s);
  226. }
  227. }
  228. public static String getRelativeRequest(URN urn) {
  229. return getRelativeRequest(urn.httpStringValue());
  230. }
  231. public static String getRelativeRequest(String urn) {
  232. return "/uri-res/N2R?" + urn;
  233. }
  234. public static String getRequest(IpPort host, URN urn) {
  235. return getRequest(host.getAddress(), host.getPort(), urn);
  236. }
  237. public static String getRequest(IpPort host, String urn) {
  238. return getRequest(host.getAddress(), host.getPort(), urn);
  239. }
  240. public static String getRequest(String host, int port, URN urn) {
  241. return getRequest(host + ":" + port, urn);
  242. }
  243. public static String getRequest(String host, int port, String urn) {
  244. return getRequest(host + ":" + port, urn);
  245. }
  246. public static String getRequest(String hostAndPort, URN urn) {
  247. return getRequest(hostAndPort, urn.httpStringValue());
  248. }
  249. public static String getRequest(String hostAndPort, String urn) {
  250. return "http://" + hostAndPort + getRelativeRequest(urn);
  251. }
  252. /**
  253. * @return a <tt>Matcher</tt> to use with JMock that compares byte []
  254. * using Arrays.equals
  255. */
  256. public static Matcher<byte []> createByteMatcher(byte [] toMatch) {
  257. return new ByteMatcher(toMatch.clone());
  258. }
  259. private static class ByteMatcher extends BaseMatcher<byte []> {
  260. private final byte[] toMatch;
  261. ByteMatcher(byte [] toMatch) {
  262. this.toMatch = toMatch.clone();
  263. }
  264. public boolean matches(Object item) {
  265. if (! (item instanceof byte []))
  266. return false;
  267. byte [] b = (byte [])item;
  268. return Arrays.equals(toMatch,b);
  269. }
  270. public void describeTo(Description description) {
  271. description.appendText("byte [] matcher for "+Base32.encode(toMatch));
  272. }
  273. }
  274. }