PageRenderTime 41ms CodeModel.GetById 26ms app.highlight 12ms RepoModel.GetById 0ms app.codeStats 0ms

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

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