public static void send(Socket sa, String data) throws IOException { byte[] content = data.getBytes(); byte[] length = String.format("%04d", content.length).getBytes(); byte[] buf = new byte[1024]; int reslen; int rc; // Bounce the message back. InputStream in = sa.getInputStream(); OutputStream out = sa.getOutputStream(); out.write(length); out.write(content); System.out.println("sent " + data.length() + " " + data); int to_read = 4; // 4 + greeting_size int read = 0; while (to_read > 0) { rc = in.read(buf, read, to_read); read += rc; to_read -= rc; System.out.println("read " + rc + " total_read " + read + " to_read " + to_read); } System.out.println(String.format("%02x %02x %02x %02x", buf[0], buf[1], buf[2], buf[3])); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } reslen = Integer.valueOf(new String(buf, 0, 4)); in.read(buf, 0, reslen); System.out.println("recv " + reslen + " " + new String(buf, 0, reslen)); }
/** * Test of schedule method, immediate execution, blocking in the scheduled task, of class * Scheduler. */ @Test public void scheduleImmediateBlocking() { System.out.println("schedule, immediate, blocking"); final CountDownLatch barrier = new CountDownLatch(1); SchedulerTask task = new SchedulerTask() { public void onSchedule(long timeStamp) { try { barrier.countDown(); Thread.sleep(10000000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; Quantum interval = Quantum.seconds(2000); Scheduler instance = Scheduler.sharedInstance(); ScheduledTask scheduled = instance.schedule(task, interval, true); stasks.add(scheduled); try { boolean executed = barrier.await(1000, TimeUnit.SECONDS); assertTrue(executed); } catch (InterruptedException e) { fail(e.getMessage()); } }
@Test public void testObserveOnWithSlowConsumer() { int NUM = (int) (Observable.bufferSize() * 0.2); AtomicInteger c = new AtomicInteger(); TestSubscriber<Integer> ts = new TestSubscriber<>(); incrementingIntegers(c) .observeOn(Schedulers.computation()) .map( i -> { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } return i; }) .take(NUM) .subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println( "testObserveOnWithSlowConsumer => Received: " + ts.valueCount() + " Emitted: " + c.get()); assertEquals(NUM, ts.valueCount()); assertTrue(c.get() < Observable.bufferSize() * 2); }
@Test public void test() { ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); // 下面的同步方法在executor执行,每次将_MidValue增加输入值 final SyncMethodProxy<Object, Integer, Integer> syncMethodProxy = SyncMethodProxy.NewSyncMethodProxy( null, new Func2<Object, Integer, Integer>() { @Override public Integer DoFunc(Object in1, Integer in2) { out.printf("Current Execute Thread: %d\n", Thread.currentThread().getId()); SyncMethodProxyTest.this._MidValue += in2.intValue(); return Integer.valueOf(SyncMethodProxyTest.this._MidValue); } }, executor); Iterables.RepeatAction( this._Count, new Action0() { @Override public void DoAction() { syncMethodProxy.BeginExecute( Integer.valueOf(1), SyncAccessMode.EXCLUSIVE); // 这里是写操作,要求写锁,否则会出同步问题 Thread.yield(); } }); // 用来做等待所有写操作终止的方法,如果和期望不一致会死循环 final SyncMethodProxy<Object, Integer, Integer> syncMethodProxyEnd = SyncMethodProxy.NewSyncMethodProxy( null, new Func2<Object, Integer, Integer>() { @Override public Integer DoFunc(Object in1, Integer in2) { while (SyncMethodProxyTest.this._MidValue != SyncMethodProxyTest.this._Count) { try { Thread.sleep(1000l); } catch (InterruptedException e) { e.printStackTrace(); } } return Integer.valueOf(SyncMethodProxyTest.this._MidValue); } }, executor); try { Integer resInteger = syncMethodProxyEnd.BeginExecute(null).get(); assertEquals(this._MidValue, resInteger.intValue()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
@Test public void dynamicRescheduleSuspended() { System.out.println("dynamicReschedule suspended"); final CountDownLatch barrier1 = new CountDownLatch(1); final CountDownLatch barrier2 = new CountDownLatch(5); SchedulerTask task = new SchedulerTask() { public void onSchedule(long timeStamp) { System.out.println("dynamicReschedule; executing periodic task"); barrier1.countDown(); barrier2.countDown(); } }; final ScheduledTask scheduled = Scheduler.sharedInstance().schedule(task, Quantum.SUSPENDED, false); stasks.add(scheduled); try { if (barrier1.await(5, TimeUnit.SECONDS)) { fail(); } scheduled.resume(); if (barrier2.await(2, TimeUnit.SECONDS)) { fail(); } scheduled.setInterval(Quantum.seconds(1)); if (!barrier2.await(8, TimeUnit.SECONDS)) { fail(); } } catch (InterruptedException e) { fail(e.getMessage()); } }
@BeforeClass public static void setUp() { duckGame = new DuckGame(); LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.width = 1280; config.height = 720; config.resizable = false; config.title = "SUPER DUCK INVADERS! - Team Mallard"; new LwjglApplication(duckGame, config); while (duckGame.onGameScreen == false) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } testRound = new Round(duckGame, Assets.levelOneMap); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } }
@Test public void testResumeNext() { Subscription s = mock(Subscription.class); // Trigger failure on second element TestObservable f = new TestObservable(s, "one", "fail", "two", "three"); Observable<String> w = Observable.create(f); Observable<String> resume = Observable.from("twoResume", "threeResume"); Observable<String> observable = Observable.create(onErrorResumeNextViaObservable(w, resume)); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); observable.subscribe(observer); try { f.t.join(); } catch (InterruptedException e) { fail(e.getMessage()); } verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onCompleted(); verify(observer, times(1)).onNext("one"); verify(observer, Mockito.never()).onNext("two"); verify(observer, Mockito.never()).onNext("three"); verify(observer, times(1)).onNext("twoResume"); verify(observer, times(1)).onNext("threeResume"); }
public void run() { boolean live = true; Random rand = new Random(); try { for (int j = 0; j < lockCountPerThread && live; j++) { final Lock lock = hz.getLock(key + rand.nextInt(locks)); lock.lock(); try { if (j % 100 == 0) { System.out.println(Thread.currentThread().getName() + " is at:" + j); } totalCount.incrementAndGet(); Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); break; } finally { try { lock.unlock(); } catch (Exception e) { e.printStackTrace(); live = false; } } } } finally { latch.countDown(); } }
@Test public void suspendSuspend() { System.out.println("suspend-suspend"); final CountDownLatch barrier1 = new CountDownLatch(1); final CountDownLatch barrier2 = new CountDownLatch(2); SchedulerTask task = new SchedulerTask() { public void onSchedule(long timeStamp) { barrier1.countDown(); barrier2.countDown(); } }; final ScheduledTask scheduled = Scheduler.sharedInstance().schedule(task, Quantum.seconds(2), false); stasks.add(scheduled); try { if (!barrier1.await(3, TimeUnit.SECONDS)) { fail(); } scheduled.suspend(); if (barrier2.await(3, TimeUnit.SECONDS)) { fail(); } scheduled.suspend(); if (barrier2.await(3, TimeUnit.SECONDS)) { fail(); } } catch (InterruptedException e) { fail(e.getMessage()); } }
@Test public void testCreateBroker() { System.out.println("testCreateBroker"); Platform.runLater( new Runnable() { @Override public void run() { synchronized (lock) { // Setup act = new ChildActivity(); act.setScene(new HBox()); Response response = new Response(); response.setStatus(Status.OK); response.setActivity(act); browser.getBrowserPanel().receiveResponse(response); } } }); try { Thread.sleep(100); } catch (InterruptedException ex) { ex.printStackTrace(); } synchronized (lock) { assertNotNull(act.createBroker()); } }
private void sleepAfterTest() { try { Thread.sleep(SLEEP_TIME_AFTER_TEST_CASE); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void sleep(long time) { try { Thread.sleep(time); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void waitFor(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Assert.fail("Failed while waiting for 10 seconds"); e.printStackTrace(); } }
@Test public void executaPing() { String ip = "200.221.2.45"; try { Monitor.execPing(ip, 2); } catch (InterruptedException e) { e.printStackTrace(); } }
@Test public void parallelRead() { Random rnd = new Random(); int N = 10; // write N key values in hashmap and store for (int i = 0; i < N; i++) { String keyValue = String.valueOf(rnd.nextInt(999999)); String resultValue = String.valueOf(rnd.nextInt(99999)); KeyImpl key = new KeyImpl(); key.setKey(keyValue); ValueImpl value = new ValueImpl(); value.setValue(resultValue); ValueListImpl valueList = new ValueListImpl(); valueList.getValueList().add(value); try { kvbis.insert(key, valueList); testMap.put(keyValue, resultValue); } catch (KeyAlreadyPresentException_Exception e) { // do nothing } catch (IOException_Exception e) { e.printStackTrace(); } catch (ServiceNotInitializedException_Exception e) { e.printStackTrace(); } } keys = new ArrayList<String>(testMap.keySet()); String randomUpdateKey = keys.get(rnd.nextInt(keys.size())); Runnable updater = new UpdateThread(randomUpdateKey); Thread updateThread = new Thread(updater); updateThread.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Runnable reader = new ReadThread(randomUpdateKey); Thread readThread = new Thread(reader); readThread.start(); try { readThread.join(); updateThread.join(); } catch (InterruptedException e) { } // if one read failed fail test case assertEquals("Result", readValue, updatedValue); }
private static void stopXmlRpcWorkflowManager() { System.setProperty( "java.util.logging.config.file", new File("./src/main/resources/logging.properties").getAbsolutePath()); try { System.getProperties().load(new FileInputStream("./src/main/resources/workflow.properties")); } catch (Exception e) { fail(e.getMessage()); } System.setProperty( "workflow.engine.instanceRep.factory", "org.apache.oodt.cas.workflow.instrepo.LuceneWorkflowInstanceRepositoryFactory"); System.setProperty("org.apache.oodt.cas.workflow.instanceRep.lucene.idxPath", luceneCatLoc); try { System.setProperty( "org.apache.oodt.cas.workflow.repo.dirs", "file://" + new File("./src/main/resources/examples").getCanonicalPath()); System.setProperty( "org.apache.oodt.cas.workflow.lifecycle.filePath", new File("./src/main/resources/examples/workflow-lifecycle.xml").getCanonicalPath()); } catch (Exception e) { fail(e.getMessage()); } try { wmgr.shutdown(); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage()); fail(e.getMessage()); } /** Sleep before removing to prevent file not found issues. */ try { Thread.sleep(MILLIS); } catch (InterruptedException e) { e.printStackTrace(); } if (new File(luceneCatLoc).exists()) { // blow away lucene cat LOG.log(Level.INFO, "Removing workflow instance repository: [" + luceneCatLoc + "]"); try { FileUtils.deleteDirectory(new File(luceneCatLoc)); } catch (IOException e) { fail(e.getMessage()); } } }
@Before public final void createGame() { // Create a testgame to be used for running tests. try { javax.swing.SwingUtilities.invokeAndWait( new Runnable() { public void run() { testgame = new BrickBreaker(); } }); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
/** * Runs the simulation using the inputed EarthGridProperties * * @param simProp EarthGridProperties object defining the simulation to run. */ private void runTest(EarthGridProperties simProp) { model.configure(simProp); model.start(); while (true) { try { model.generate(); pm.processMessageQueue(); } catch (InterruptedException e) { assertEquals(true, e.getMessage().contains("Simulation Completed!")); break; } catch (Exception e) { e.printStackTrace(); fail("ERROR: " + e.getMessage()); break; } } }
public static void waitForElement(WebTester tester, String xpath) { int timeout = 7; for (int i = 0; i < timeout; i++) { try { tester.getElementByXPath(xpath); return; } catch (AssertionFailedError e) { // keep trying } try { Thread.sleep(200 + i * 500); } catch (InterruptedException e) { fail(e.getMessage()); } } fail("Element not found (timeout: " + timeout + ") - " + xpath); }
@Test public void testEvictionLFU() { try { final int k = 1; final int size = 10000; final String mapName = "testEvictionLFU"; Config cfg = new Config(); MapConfig mc = cfg.getMapConfig(mapName); mc.setEvictionPolicy(MapConfig.EvictionPolicy.LFU); mc.setEvictionPercentage(20); MaxSizeConfig msc = new MaxSizeConfig(); msc.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.PER_NODE); msc.setSize(size); mc.setMaxSizeConfig(msc); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(cfg); IMap<Object, Object> map = instances[0].getMap(mapName); for (int i = 0; i < size / 2; i++) { map.put(i, i); map.get(i); } Thread.sleep(1000); for (int i = size / 2; i < size; i++) { map.put(i, i); } Thread.sleep(3000); Assert.assertFalse("No eviction!?!?!?", map.size() == size); boolean isFrequentlyUsedEvicted = false; for (int i = 0; i < size / 2; i++) { if (map.get(i) == null) { isFrequentlyUsedEvicted = true; break; } } Assert.assertFalse(isFrequentlyUsedEvicted); instances[0].getLifecycleService().shutdown(); } catch (InterruptedException e) { e.printStackTrace(); } }
@Test public void testLogin() { beginAt("/default.jsp"); // Open the browser on // http://localhost:8080/test/home.xhtml assertTitleEquals("Movies"); assertElementPresent("janrainModal"); String element = getElementAttributeByXPath("//div[@id='janrainModal']", "style"); assertTrue(element.contains("display: none")); clickLink("login"); element = getElementAttributeByXPath("//div[@id='janrainModal']", "style"); assertTrue(element.contains("display: block")); assertElementPresent("janrain-yahoo"); clickElementByXPath("//li[@id='janrain-yahoo']"); assertWindowCountEquals(2); assertWindowPresentWithTitle("Sign in to Yahoo!"); gotoWindowByTitle("Sign in to Yahoo!"); setTextField("login", "*****@*****.**"); setTextField("passwd", "Test12345"); submit(".save"); try { Thread.sleep(20000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // beginAt("/default.jsp"); // gotoWindowByTitle("Movies"); assertTextPresent("Logout"); assertElementPresent("username"); IElement username = getElementById("username"); assertTrue(username.getTextContent().contains("movie hunter")); assertElementNotPresent("login"); assertElementPresent("logout"); clickLink("logout"); assertElementPresent("login"); }
@Test public void testMapResumeAsyncNext() { Subscription sr = mock(Subscription.class); // Trigger multiple failures Observable<String> w = Observable.from("one", "fail", "two", "three", "fail"); // Resume Observable is async TestObservable f = new TestObservable(sr, "twoResume", "threeResume"); Observable<String> resume = Observable.create(f); // Introduce map function that fails intermittently (Map does not prevent this when the observer // is a // rx.operator incl onErrorResumeNextViaObservable) w = w.map( new Func1<String, String>() { public String call(String s) { if ("fail".equals(s)) throw new RuntimeException("Forced Failure"); System.out.println("BadMapper:" + s); return s; } }); Observable<String> observable = Observable.create(onErrorResumeNextViaObservable(w, resume)); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); observable.subscribe(observer); try { f.t.join(); } catch (InterruptedException e) { fail(e.getMessage()); } verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onCompleted(); verify(observer, times(1)).onNext("one"); verify(observer, Mockito.never()).onNext("two"); verify(observer, Mockito.never()).onNext("three"); verify(observer, times(1)).onNext("twoResume"); verify(observer, times(1)).onNext("threeResume"); }
@Test public void stressTest() { for (int i = 0; i < NUMBEROFTHREADS; i++) { threads[i].start(); } try { Thread.sleep(RUN_TIME_MILLIS); } catch (InterruptedException e) { } for (int i = 0; i < NUMBEROFTHREADS; i++) { threads[i].interrupt(); } try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } int fails = 0; int oks = 0; int exceptions = 0; for (int i = 0; i < NUMBEROFTHREADS; i++) { fails += threads[i].fails; oks += threads[i].oks; exceptions += threads[i].exceptions; } System.out.println( "fails: " + fails + " oks: " + oks + " exceptions: " + exceptions + " total " + (fails + oks + exceptions)); assertEquals(0, fails); assertEquals(0, exceptions); }
// @Test public void testGetStatus() { System.out.println("getStatus"); final Task instanceA = new Task(Task.FASTLANE_PRIORITY) { protected Object exec(Object in) { return in; } }; final Task instance2 = new Task(Task.FASTLANE_PRIORITY) { protected Object exec(Object in) { try { Thread.sleep(200); } catch (InterruptedException ex) { } return in; } }; final Task instance3 = new Task(Task.FASTLANE_PRIORITY) { protected Object exec(Object in) { try { Thread.sleep(200); } catch (InterruptedException ex) { } return in; } }; assertEquals(Task.PENDING, instanceA.getStatus()); instance2.fork(); instance3.fork(); instanceA.fork(); assertEquals(Task.PENDING, instanceA.getStatus()); instance2.cancel("testing"); try { Thread.sleep(200); } catch (InterruptedException ex) { ex.printStackTrace(); } assertEquals(Task.FINISHED, instanceA.getStatus()); }
@Test public void testEvictionLRU() { final int k = 2; final int size = 10000; try { final String mapName = "testEvictionLRU"; Config cfg = new Config(); MapConfig mc = cfg.getMapConfig(mapName); mc.setEvictionPolicy(MapConfig.EvictionPolicy.LRU); mc.setEvictionPercentage(10); MaxSizeConfig msc = new MaxSizeConfig(); msc.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.PER_NODE); msc.setSize(size); mc.setMaxSizeConfig(msc); TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(cfg); IMap<Object, Object> map = instances[0].getMap(mapName); Thread.sleep(1000); for (int i = size / 2; i < size; i++) { map.put(i, i); } Thread.sleep(2000); for (int i = 0; i < size / 2; i++) { map.put(i, i); } Thread.sleep(1000); int recentlyUsedEvicted = 0; for (int i = 0; i < size / 2; i++) { if (map.get(i) == null) { recentlyUsedEvicted++; } } Assert.assertTrue(recentlyUsedEvicted == 0); } catch (InterruptedException e) { e.printStackTrace(); } }
/** Test method for {@link com.mychaelstyle.nlp.Juman#parse(java.lang.String)}. */ @Test public void testParse() { Juman juman = new Juman(); try { ObjectNode result = juman.parse("本システムは,計算機による日本語の解析の研究を目指す多くの研究者に共通に使える形態素解析ツールを提供するために開発されました。"); assertThat(result, notNullValue()); System.out.println(result.toString()); result = juman.parse("JUMANは、日本語の形態素解析システムです。"); System.out.println(result.toString()); result = juman.parse("人手で整備した辞書に基づいており、ChaSenの元となったシステム。"); System.out.println(result.toString()); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
/** Test of unschedule method, of class Scheduler. */ @Test public void unschedule() { System.out.println("unschedule"); final AtomicBoolean executed = new AtomicBoolean(false); SchedulerTask task = new SchedulerTask() { public void onSchedule(long timeStamp) { executed.set(true); } }; Scheduler instance = Scheduler.sharedInstance(); ScheduledTask scheduled = instance.schedule(task, Quantum.seconds(3), false); instance.unschedule(scheduled); try { Thread.sleep(5000); } catch (InterruptedException e) { fail(e.getMessage()); } assertFalse(executed.get()); }
@Override public void run() { for (int i = 0; i < 30; i++) { System.err.println("wait"); // wait a bit randomly try { Thread.sleep((long) (2000 * Math.random())); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // run the model System.err.println("run !"); Map<String, Object> result = runModel(); checkResult(result); } // return synchronized (threadsToWait) { this.threadsToWait.remove(this); } }
/** Test of schedule method of class Scheduler. */ @Test public void schedule() { System.out.println("schedule"); final CountDownLatch barrier = new CountDownLatch(1); SchedulerTask task = new SchedulerTask() { public void onSchedule(long timeStamp) { barrier.countDown(); } }; Quantum interval = Quantum.seconds(5); Scheduler instance = Scheduler.sharedInstance(); ScheduledTask scheduled = instance.schedule(task, interval, false); stasks.add(scheduled); try { boolean executed = barrier.await(8, TimeUnit.SECONDS); assertTrue(executed); } catch (InterruptedException e) { fail(e.getMessage()); } }
/** Test of testFork method, of class Task. */ @Test public void testFork() { System.out.println("fork"); Task instance = new Task(Task.FASTLANE_PRIORITY) { protected Object exec(Object in) { return "run"; } }; Task result_1 = instance.fork(); assertEquals(instance, result_1); try { Thread.sleep(200); } catch (InterruptedException ex) { ex.printStackTrace(); } try { assertEquals("run", (String) instance.get()); } catch (Exception ex) { ex.printStackTrace(); fail("Can not get() : " + ex); } }