@Before
 public void setUp() throws Exception {
   disableOutput();
   model = new Earth();
   System.gc();
   runtime.gc();
 }
  @Test
  public void customChannelsWithDefaultExecutor() {
    loadBeanDefinitions("websocket-config-broker-customchannels-default-executor.xml");

    testExecutor(
        "clientInboundChannel",
        Runtime.getRuntime().availableProcessors() * 2,
        Integer.MAX_VALUE,
        60);
    testExecutor(
        "clientOutboundChannel",
        Runtime.getRuntime().availableProcessors() * 2,
        Integer.MAX_VALUE,
        60);
    assertFalse(this.appContext.containsBean("brokerChannelExecutor"));
  }
 @Test
 public void testJavaProcessOk() throws Exception {
   final String commandLine =
       String.format(
           JAVA_EXEC_PATH + " -cp %s %s 2 10", classPath, TestExecutable.class.getName());
   final Process process = Runtime.getRuntime().exec(commandLine);
   final MyHandler handler = new MyHandler();
   new ProcessObserver(process).setHandler(handler).start();
   assertTrue(handler.started);
   assertEquals(
       "Start\n"
           + "Progress 10%\n"
           + "Progress 20%\n"
           + "Progress 30%\n"
           + "Progress 40%\n"
           + "Progress 50%\n"
           + "Progress 60%\n"
           + "Progress 70%\n"
           + "Progress 80%\n"
           + "Progress 90%\n"
           + "Progress 100%\n"
           + "Done\n",
       handler.out);
   assertEquals("", handler.err);
   assertTrue(handler.ended);
   assertEquals(0, handler.exitCode.intValue());
 }
  /**
   * This method is called once (and only once) when all test cases have completed.
   *
   * @throws java.lang.Exception
   */
  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    /* remove our short perl script */
    ourTempExe.delete();

    /* remove our temporary directory */
    Runtime.getRuntime().exec("rm -r " + ourTempDir);
  }
 @Test
 public void sameObjectReturned() {
   ObjectReferenceManager<String> referenceManager =
       ObjectReferenceManager.newInstance(Runtime.getSystemRuntime());
   String bar = "bar";
   Pointer ptr = referenceManager.add(bar);
   assertSame(bar, referenceManager.get(ptr));
 }
 public void execute(WorkerProcessContext workerProcessContext) {
   TestListenerInterface sender =
       workerProcessContext.getServerConnection().addOutgoing(TestListenerInterface.class);
   sender.send("message 1", 1);
   sender.send("message 2", 2);
   // crash
   Runtime.getRuntime().halt(1);
 }
 @After
 public void tearDown() throws Exception {
   enableOutput();
   dbFile = new File(Constants.DATABASE_FILE);
   if (dbFile.exists()) System.out.println("#DBFILESIZE:" + dbFile.length());
   model = null;
   System.gc();
   runtime.gc();
 }
  @Test
  @Ignore
  public void testCHMAcquirePerf()
      throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException,
          InterruptedException {
    for (int runs : new int[] {10, 50, 250, 1000, 2500}) {
      System.out.println("Testing " + runs + " million entries");
      final long entries = runs * 1000 * 1000L;
      final ConcurrentMap<String, AtomicInteger> map =
          new ConcurrentHashMap<String, AtomicInteger>((int) (entries * 5 / 4), 1.0f, 1024);

      int procs = Runtime.getRuntime().availableProcessors();
      int threads = procs * 2;
      int count = runs > 500 ? runs > 1200 ? 1 : 2 : 3;
      final int independence = Math.min(procs, runs > 500 ? 8 : 4);
      for (int j = 0; j < count; j++) {
        long start = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(procs);
        for (int i = 0; i < threads; i++) {
          final int t = i;
          es.submit(
              new Runnable() {
                @Override
                public void run() {
                  StringBuilder sb = new StringBuilder();
                  int next = 50 * 1000 * 1000;
                  // use a factor to give up to 10 digit numbers.
                  int factor = Math.max(1, (int) ((10 * 1000 * 1000 * 1000L - 1) / entries));
                  for (long i = t % independence; i < entries; i += independence) {
                    sb.setLength(0);
                    sb.append("u:");
                    sb.append(i * factor);
                    String key = sb.toString();
                    AtomicInteger count = map.get(key);
                    if (count == null) {
                      map.put(key, new AtomicInteger());
                      count = map.get(key);
                    }
                    count.getAndIncrement();
                    if (t == 0 && i == next) {
                      System.out.println(i);
                      next += 50 * 1000 * 1000;
                    }
                  }
                }
              });
        }
        es.shutdown();
        es.awaitTermination(10, TimeUnit.MINUTES);
        printStatus();
        long time = System.currentTimeMillis() - start;
        System.out.printf("Throughput %.1f M ops/sec%n", threads * entries / 1000.0 / time);
      }
    }
  }
 @Test
 public void differentPointerReturnedForSameObject() {
   ObjectReferenceManager<String> referenceManager =
       ObjectReferenceManager.newInstance(Runtime.getSystemRuntime());
   String bar = "bar";
   Pointer ptr = referenceManager.add(bar);
   Pointer ptr2 = referenceManager.add(bar);
   assertSame(bar, referenceManager.get(ptr));
   assertSame(bar, referenceManager.get(ptr2));
   assertNotSame(ptr, ptr2);
 }
  @Test
  @Ignore
  public void testAcquirePerf()
      throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException,
          InterruptedException {
    //        int runs = Integer.getInteger("runs", 10);
    for (int runs : new int[] {10, 50, 250, 1000, 2500}) {
      final long entries = runs * 1000 * 1000L;
      final SharedHashMap<CharSequence, LongValue> map = getSharedMap(entries * 4 / 3, 1024, 24);

      int procs = Runtime.getRuntime().availableProcessors();
      int threads = procs * 2;
      int count = runs > 500 ? runs > 1200 ? 1 : 2 : 3;
      final int independence = Math.min(procs, runs > 500 ? 8 : 4);
      for (int j = 0; j < count; j++) {
        long start = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(procs);
        for (int i = 0; i < threads; i++) {
          final int t = i;
          es.submit(
              new Runnable() {
                @Override
                public void run() {
                  LongValue value = nativeLongValue();
                  StringBuilder sb = new StringBuilder();
                  int next = 50 * 1000 * 1000;
                  // use a factor to give up to 10 digit numbers.
                  int factor = Math.max(1, (int) ((10 * 1000 * 1000 * 1000L - 1) / entries));
                  for (long i = t % independence; i < entries; i += independence) {
                    sb.setLength(0);
                    sb.append("u:");
                    sb.append(i * factor);
                    map.acquireUsing(sb, value);
                    long n = value.addAtomicValue(1);
                    assert n >= 0 && n < 1000 : "Counter corrupted " + n;
                    if (t == 0 && i == next) {
                      System.out.println(i);
                      next += 50 * 1000 * 1000;
                    }
                  }
                }
              });
        }
        es.shutdown();
        es.awaitTermination(runs / 10 + 1, TimeUnit.MINUTES);
        long time = System.currentTimeMillis() - start;
        System.out.printf(
            "Throughput %.1f M ops/sec%n", threads * entries / independence / 1000.0 / time);
      }
      printStatus();
      map.close();
    }
  }
 private static boolean isAaptPresent() throws Exception {
   boolean result = true;
   try {
     Process proc = Runtime.getRuntime().exec("aapt");
     BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
     String line = null;
     while ((line = br.readLine()) != null) {}
   } catch (Exception ex) {
     result = false;
   }
   return result;
 }
 @Test
 public void testJavaProcessMissingArg() throws Exception {
   final String commandLine =
       String.format(JAVA_EXEC_PATH + " -cp %s %s 2", classPath, TestExecutable.class.getName());
   final Process process = Runtime.getRuntime().exec(commandLine);
   final MyHandler handler = new MyHandler();
   new ProcessObserver(process).setHandler(handler).start();
   assertTrue(handler.started);
   assertEquals("", handler.out);
   assertEquals("Usage: TestExecutable <seconds> <steps>\n", handler.err);
   assertTrue(handler.ended);
   assertEquals(1, handler.exitCode.intValue());
 }
 @Test
 public void referenceEqualityOnly() {
   ObjectReferenceManager<String> referenceManager =
       ObjectReferenceManager.newInstance(Runtime.getSystemRuntime());
   String bar = "bar";
   String bar2 = new String("bar");
   Pointer ptr = referenceManager.add(bar);
   Pointer ptr2 = referenceManager.add(bar2);
   assertNotSame(ptr, ptr2);
   assertNotEquals(ptr, ptr2);
   assertSame(bar, referenceManager.get(ptr));
   assertSame(bar2, referenceManager.get(ptr2));
 }
예제 #14
0
  @BeforeClass
  public static void initialize() throws InterruptedException {
    Runtime rt = Runtime.getRuntime();

    rt.gc();
    freeMemory_preUse = rt.freeMemory();

    ResourceManager rm = new ResourceManager();

    for (int i = 0; i < 1000; i++) {
      Object key = Integer.toString(i);
      keyList.add(key);
      resourceList.add(rm.getResource(key));
    }

    rt.gc();
    freeMemory_useRes = rt.freeMemory();

    for (int i = 0; i < 1000; i++) {
      Object key = keyList.get(i);
      Resource res = resourceList.get(i);
      res.use(key);
    }

    for (int i = 0; i < 1000; i++) {
      Resource res = resourceList.get(i);
      res.release();
    }

    keyList.clear(); // リソースへの参照をすべて削除
    resourceList.clear(); // リソースへの参照をすべて削除

    rm.shutdown();
    rt.gc();

    rm.reaper.join();

    rt.gc();
    freeMemory_clearRes = rt.freeMemory();

    System.out.println("freeMemory_preUse  :" + freeMemory_preUse);
    System.out.println("freeMemory_useRes  :" + freeMemory_useRes);
    System.out.println("freeMemory_clearRes:" + freeMemory_clearRes);
  }
예제 #15
0
  /** given user name - get all the groups. Needs to happen before creating the test users */
  @Test
  public void testGetServerSideGroups() throws IOException, InterruptedException {
    // get the user name
    Process pp = Runtime.getRuntime().exec("whoami");
    BufferedReader br = new BufferedReader(new InputStreamReader(pp.getInputStream()));
    String userName = br.readLine().trim();
    // get the groups
    pp = Runtime.getRuntime().exec("id -Gn");
    br = new BufferedReader(new InputStreamReader(pp.getInputStream()));
    String line = br.readLine();
    System.out.println(userName + ":" + line);

    List<String> groups = new ArrayList<String>();
    for (String s : line.split("[\\s]")) {
      groups.add(s);
    }

    final UserGroupInformation login = UserGroupInformation.getCurrentUser();
    assertEquals(userName, login.getShortUserName());
    String[] gi = login.getGroupNames();
    assertEquals(groups.size(), gi.length);
    for (int i = 0; i < gi.length; i++) {
      assertEquals(groups.get(i), gi[i]);
    }

    final UserGroupInformation fakeUser = UserGroupInformation.createRemoteUser("foo.bar");
    fakeUser.doAs(
        new PrivilegedExceptionAction<Object>() {
          @Override
          public Object run() throws IOException {
            UserGroupInformation current = UserGroupInformation.getCurrentUser();
            assertFalse(current.equals(login));
            assertEquals(current, fakeUser);
            assertEquals(0, current.getGroupNames().length);
            return null;
          }
        });
  }
  public static void main(String[] args) throws IOException {
    // At last count, we could do this in 22 seconds on a 2.4ghz MacBookPro.
    // Although, it looks like when you run it in the test it runs a little slower
    LargeWorkspacePerformanceSimulation testHarness = new LargeWorkspacePerformanceSimulation(true);
    testHarness.inContext();
    System.out.println("File Count: " + testHarness.files.size());
    System.out.println("Max Memory " + humanReadable(Runtime.getRuntime().maxMemory()));

    long timestamp = System.currentTimeMillis();
    System.out.println("Creating Projects...");
    testHarness.createProjects();
    System.out.println("Created in " + (System.currentTimeMillis() - timestamp) + "ms");
    System.out.println("Updating Projects...");

    timestamp = System.currentTimeMillis();
    testHarness.updateProjects();
    System.out.println();
    long time = System.currentTimeMillis() - timestamp;
    System.out.println(
        "Updated " + PROJECT_COUNT + " projects " + UPDATE_COUNT + " times in " + time + "ms");
  }
예제 #17
0
  @Test
  public void testMachine() throws Exception {
    if (!isUnix()) return;

    Process p = Runtime.getRuntime().exec(new String[] {"uname", "-m"});
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String uname = r.readLine().trim();
    String m = uname;
    assertTrue(m.length() > 0);

    if (m.matches("i\\d86")) m = "i386";
    else if (m.matches("i86pc")) m = "x86";

    if (m.equals("i386") && Platform.is64Bits()) m = "x86_64";

    assertEquals(
        "uname = " + uname + ", Platform.getMachine = " + Platform.getMachine(),
        m,
        Platform.getMachine());
  }
  @Ignore("This test fails to often on the server. No Idea why.")
  public void testJavaProcessCancel() throws Exception {
    final String commandLine =
        String.format(
            JAVA_EXEC_PATH + " -cp %s %s 10 2", classPath, TestExecutable.class.getName());
    final Process process = Runtime.getRuntime().exec(commandLine);
    final MyHandler handler = new MyHandler();
    final ProcessObserver.ObservedProcess observedProcess =
        new ProcessObserver(process)
            .setMode(ProcessObserver.Mode.NON_BLOCKING)
            .setHandler(handler)
            .start();
    Thread.sleep(250);
    observedProcess.cancel();
    Thread.sleep(250);

    assertTrue(handler.started);
    assertEquals("Start\n", handler.out);
    assertEquals("", handler.err);
    assertFalse(handler.ended);
    assertNull(handler.exitCode);
  }
  @Test
  public void simpleBroker() {
    loadBeanDefinitions("websocket-config-broker-simple.xml");

    HandlerMapping hm = this.appContext.getBean(HandlerMapping.class);
    assertThat(hm, Matchers.instanceOf(SimpleUrlHandlerMapping.class));
    SimpleUrlHandlerMapping suhm = (SimpleUrlHandlerMapping) hm;
    assertThat(suhm.getUrlMap().keySet(), Matchers.hasSize(4));
    assertThat(suhm.getUrlMap().values(), Matchers.hasSize(4));

    HttpRequestHandler httpRequestHandler = (HttpRequestHandler) suhm.getUrlMap().get("/foo");
    assertNotNull(httpRequestHandler);
    assertThat(httpRequestHandler, Matchers.instanceOf(WebSocketHttpRequestHandler.class));

    WebSocketHttpRequestHandler wsHttpRequestHandler =
        (WebSocketHttpRequestHandler) httpRequestHandler;
    HandshakeHandler handshakeHandler = wsHttpRequestHandler.getHandshakeHandler();
    assertNotNull(handshakeHandler);
    assertTrue(handshakeHandler instanceof TestHandshakeHandler);
    List<HandshakeInterceptor> interceptors = wsHttpRequestHandler.getHandshakeInterceptors();
    assertThat(
        interceptors,
        contains(instanceOf(FooTestInterceptor.class), instanceOf(BarTestInterceptor.class)));

    WebSocketHandler wsHandler = unwrapWebSocketHandler(wsHttpRequestHandler.getWebSocketHandler());
    assertNotNull(wsHandler);
    assertThat(wsHandler, Matchers.instanceOf(SubProtocolWebSocketHandler.class));

    SubProtocolWebSocketHandler subProtocolWsHandler = (SubProtocolWebSocketHandler) wsHandler;
    assertEquals(
        Arrays.asList("v10.stomp", "v11.stomp", "v12.stomp"),
        subProtocolWsHandler.getSubProtocols());
    assertEquals(25 * 1000, subProtocolWsHandler.getSendTimeLimit());
    assertEquals(1024 * 1024, subProtocolWsHandler.getSendBufferSizeLimit());

    StompSubProtocolHandler stompHandler =
        (StompSubProtocolHandler) subProtocolWsHandler.getProtocolHandlerMap().get("v12.stomp");
    assertNotNull(stompHandler);
    assertEquals(128 * 1024, stompHandler.getMessageSizeLimit());

    assertNotNull(new DirectFieldAccessor(stompHandler).getPropertyValue("eventPublisher"));

    httpRequestHandler = (HttpRequestHandler) suhm.getUrlMap().get("/test/**");
    assertNotNull(httpRequestHandler);
    assertThat(httpRequestHandler, Matchers.instanceOf(SockJsHttpRequestHandler.class));

    SockJsHttpRequestHandler sockJsHttpRequestHandler =
        (SockJsHttpRequestHandler) httpRequestHandler;
    wsHandler = unwrapWebSocketHandler(sockJsHttpRequestHandler.getWebSocketHandler());
    assertNotNull(wsHandler);
    assertThat(wsHandler, Matchers.instanceOf(SubProtocolWebSocketHandler.class));
    assertNotNull(sockJsHttpRequestHandler.getSockJsService());
    assertThat(
        sockJsHttpRequestHandler.getSockJsService(),
        Matchers.instanceOf(DefaultSockJsService.class));

    DefaultSockJsService defaultSockJsService =
        (DefaultSockJsService) sockJsHttpRequestHandler.getSockJsService();
    WebSocketTransportHandler wsTransportHandler =
        (WebSocketTransportHandler)
            defaultSockJsService.getTransportHandlers().get(TransportType.WEBSOCKET);
    assertNotNull(wsTransportHandler.getHandshakeHandler());
    assertThat(
        wsTransportHandler.getHandshakeHandler(), Matchers.instanceOf(TestHandshakeHandler.class));

    ThreadPoolTaskScheduler scheduler =
        (ThreadPoolTaskScheduler) defaultSockJsService.getTaskScheduler();
    assertEquals(
        Runtime.getRuntime().availableProcessors(),
        scheduler.getScheduledThreadPoolExecutor().getCorePoolSize());
    assertTrue(scheduler.getScheduledThreadPoolExecutor().getRemoveOnCancelPolicy());

    interceptors = defaultSockJsService.getHandshakeInterceptors();
    assertThat(
        interceptors,
        contains(instanceOf(FooTestInterceptor.class), instanceOf(BarTestInterceptor.class)));

    UserSessionRegistry userSessionRegistry = this.appContext.getBean(UserSessionRegistry.class);
    assertNotNull(userSessionRegistry);

    UserDestinationResolver userDestResolver =
        this.appContext.getBean(UserDestinationResolver.class);
    assertNotNull(userDestResolver);
    assertThat(userDestResolver, Matchers.instanceOf(DefaultUserDestinationResolver.class));
    DefaultUserDestinationResolver defaultUserDestResolver =
        (DefaultUserDestinationResolver) userDestResolver;
    assertEquals("/personal/", defaultUserDestResolver.getDestinationPrefix());
    assertSame(
        stompHandler.getUserSessionRegistry(), defaultUserDestResolver.getUserSessionRegistry());

    UserDestinationMessageHandler userDestHandler =
        this.appContext.getBean(UserDestinationMessageHandler.class);
    assertNotNull(userDestHandler);

    SimpleBrokerMessageHandler brokerMessageHandler =
        this.appContext.getBean(SimpleBrokerMessageHandler.class);
    assertNotNull(brokerMessageHandler);
    assertEquals(
        Arrays.asList("/topic", "/queue"),
        new ArrayList<String>(brokerMessageHandler.getDestinationPrefixes()));

    List<Class<? extends MessageHandler>> subscriberTypes =
        Arrays.<Class<? extends MessageHandler>>asList(
            SimpAnnotationMethodMessageHandler.class,
            UserDestinationMessageHandler.class,
            SimpleBrokerMessageHandler.class);
    testChannel("clientInboundChannel", subscriberTypes, 0);
    testExecutor(
        "clientInboundChannel",
        Runtime.getRuntime().availableProcessors() * 2,
        Integer.MAX_VALUE,
        60);

    subscriberTypes =
        Arrays.<Class<? extends MessageHandler>>asList(SubProtocolWebSocketHandler.class);
    testChannel("clientOutboundChannel", subscriberTypes, 0);
    testExecutor(
        "clientOutboundChannel",
        Runtime.getRuntime().availableProcessors() * 2,
        Integer.MAX_VALUE,
        60);

    subscriberTypes =
        Arrays.<Class<? extends MessageHandler>>asList(
            SimpleBrokerMessageHandler.class, UserDestinationMessageHandler.class);
    testChannel("brokerChannel", subscriberTypes, 0);
    try {
      this.appContext.getBean("brokerChannelExecutor", ThreadPoolTaskExecutor.class);
      fail("expected exception");
    } catch (NoSuchBeanDefinitionException ex) {
      // expected
    }

    assertNotNull(this.appContext.getBean("webSocketScopeConfigurer", CustomScopeConfigurer.class));

    DirectFieldAccessor subscriptionRegistryAccessor =
        new DirectFieldAccessor(brokerMessageHandler.getSubscriptionRegistry());
    String pathSeparator =
        (String)
            new DirectFieldAccessor(subscriptionRegistryAccessor.getPropertyValue("pathMatcher"))
                .getPropertyValue("pathSeparator");
    assertEquals(".", pathSeparator);
  }
 @Test
 public void remove() {
   ObjectReferenceManager<String> referenceManager =
       ObjectReferenceManager.newInstance(Runtime.getSystemRuntime());
   assertTrue(referenceManager.remove(referenceManager.add("bar")));
 }
@BenchmarkOptions(
    callgc = true,
    benchmarkRounds = Constants.numberOfBenchmarkRounds,
    warmupRounds = 5)
public class Benchmark_Runtime_10Precision extends AbstractBenchmark {

  Earth model;
  static PersistenceManager pm;
  File dbFile;

  Runtime runtime = Runtime.getRuntime();
  private PrintStream original = System.out;

  @Test
  public void args10PR_1GP_1TP() {
    runTest(Constants.args10PR_1GP_1TP);
  }

  @Test
  public void args10PR_1GP_5TP() {
    runTest(Constants.args10PR_1GP_5TP);
  }

  @Test
  public void args10PR_1GP_10TP() {
    runTest(Constants.args10PR_1GP_10TP);
  }

  @Test
  public void args10PR_1GP_50TP() {
    runTest(Constants.args10PR_1GP_50TP);
  }

  @Test
  public void args10PR_1GP_100TP() {
    runTest(Constants.args10PR_1GP_100TP);
  }

  @Test
  public void args10PR_5GP_1TP() {
    runTest(Constants.args10PR_5GP_1TP);
  }

  @Test
  public void args10PR_5GP_5TP() {
    runTest(Constants.args10PR_5GP_5TP);
  }

  @Test
  public void args10PR_5GP_10TP() {
    runTest(Constants.args10PR_5GP_10TP);
  }

  @Test
  public void args10PR_5GP_50TP() {
    runTest(Constants.args10PR_5GP_50TP);
  }

  @Test
  public void args10PR_5GP_100TP() {
    runTest(Constants.args10PR_5GP_100TP);
  }

  @Test
  public void args10PR_10GP_1TP() {
    runTest(Constants.args10PR_10GP_1TP);
  }

  @Test
  public void args10PR_10GP_5TP() {
    runTest(Constants.args10PR_10GP_5TP);
  }

  @Test
  public void args10PR_10GP_10TP() {
    runTest(Constants.args10PR_10GP_10TP);
  }

  @Test
  public void args10PR_10GP_50TP() {
    runTest(Constants.args10PR_10GP_50TP);
  }

  @Test
  public void args10PR_10GP_100TP() {
    runTest(Constants.args10PR_10GP_100TP);
  }

  @Test
  public void args10PR_50GP_1TP() {
    runTest(Constants.args10PR_50GP_1TP);
  }

  @Test
  public void args10PR_50GP_50TP() {
    runTest(Constants.args10PR_50GP_5TP);
  }

  @Test
  public void args10PR_50GP_5TP() {
    runTest(Constants.args10PR_50GP_5TP);
  }

  @Test
  public void defaultTest() {
    runTest(Constants.args10PR_50GP_10TP);
  }

  @Test
  public void args10PR_50GP_10TP() {
    runTest(Constants.args10PR_50GP_50TP);
  }

  @Test
  public void args10PR_50GP_100TP() {
    runTest(Constants.args10PR_50GP_100TP);
  }

  @Test
  public void args10PR_100GP_1TP() {
    runTest(Constants.args10PR_100GP_1TP);
  }

  @Test
  public void args10PR_100GP_5TP() {
    runTest(Constants.args10PR_100GP_5TP);
  }

  @Test
  public void args10PR_100GP_10TP() {
    runTest(Constants.args10PR_100GP_10TP);
  }

  @Test
  public void args10PR_100GP_50TP() {
    runTest(Constants.args10PR_100GP_50TP);
  }

  @Test
  public void args10PR_100GP_100TP() {
    runTest(Constants.args10PR_100GP_100TP);
  }

  /**
   * 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;
      }
    }
  }

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    SimulationDatabase.getSimulationDatabase().resetDatabase();
    pm = new PersistenceManager();
    System.gc();
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    SimulationDatabase.getSimulationDatabase().resetDatabase();
    System.gc();
  }

  @Before
  public void setUp() throws Exception {
    disableOutput();
    model = new Earth();
    System.gc();
    runtime.gc();
  }

  @After
  public void tearDown() throws Exception {
    enableOutput();
    dbFile = new File(Constants.DATABASE_FILE);
    if (dbFile.exists()) System.out.println("#DBFILESIZE:" + dbFile.length());
    model = null;
    System.gc();
    runtime.gc();
  }

  private void disableOutput() {
    System.setOut(Constants.outNull);
  }

  private void enableOutput() {
    System.setOut(original);
  }
}
예제 #22
0
파일: LFT.java 프로젝트: qarocks/SPW
  @Test
  public void LFTMain() throws Exception {
    JavascriptExecutor js = (JavascriptExecutor) webDriver;
    selenium.open(baseUrl);
    selenium.type("id=id_username", sender);
    selenium.type("id=id_password", "123abc");
    selenium.click("css=input[type=\"submit\"]");

    selenium.waitForPageToLoad("2000");

    System.out.println("First: The page title is " + selenium.getTitle());
    // code to upload file

    driver.findElement(By.linkText("Compose")).click();

    selenium.waitForPageToLoad("3000");

    // Runtime.getRuntime().exec("C:\\Users\\Sneha\\Desktop\\IE.exe");
    Runtime.getRuntime().exec("C:\\Users\\Sneha\\Desktop\\silver_autoit.exe");

    Functions.MyWaitfunc(driver, "//*[@id='uploader_browse']");
    WebElement ele = driver.findElement(By.xpath("//*[@id='uploader_browse']"));
    ele.click();

    // ele.sendKeys("C:\\Users\\Sneha\\Desktop\\Lighthouse.jpg");

    // send secure mail
    // driver.findElement(By.id("secure")).click();

    driver.findElement(By.id("addrin")).sendKeys(recipient);

    driver.findElement(By.id("id_subject")).sendKeys(stringToTest_tc001);

    String torun = "document.getElementById('tinymce').innerHTML='Hi there!'";

    driver.findElement(By.id("addrsubmit")).click();

    /*selenium.waitForPageToLoad("3000");

    		Thread.sleep(100);
    		js.executeScript(torun);

    		System.out.println((String)js.executeScript("return document.title"));

    */

    driver.switchTo().frame("id_body_ifr");

    selenium.typeKeys("//body[@id='tinymce']", "Finally wohoooo!!");
    driver.switchTo().defaultContent();

    driver.findElement(By.id("submitter")).click();

    /* code only if it is LFT

    String per_done="//html/body/div/div[2]/div[4]/form/fieldset/div[9]/div/div/div/div[2]/table[2]/tbody/tr/td[3]/span";
    NoSuchElementException e1 = null;

    // code to wait for file to be uploaded
    for (int second = 0;; second++) {

    	if (second >= 60) {fail("timeout");}
    	try { if (driver.findElement(By.xpath(per_done)).getText().equalsIgnoreCase("548 KB")) break; } catch (Exception e) {}
    	Thread.sleep(1000);


    }
    */
    // mail body

    /* code to run if LFT
    //System.out.println((String)js.
    if((this.doesWebElementExist(driver,By.xpath(per_done))) && (driver.findElement(By.xpath(per_done)).getText().equalsIgnoreCase("548 KB")))

    	{//driver.findElement(By.id("submitter")).click();
    	}

    else
    	throw e1;

    */

    /* this section if confirm dialog pops up!

    this.MyWaitfunc("//html/body/div[4]/div[11]/div/button/span");

          if(driver.findElement(By.xpath("//html/body/div[4]/div[11]/div/button/span")).isDisplayed())

    	driver.findElement(By.xpath("//html/body/div[4]/div[11]/div/button/span")).click();
    else
    	System.out.println("Confirm dialog not up yet!");
    */

    // to check if mail was sent successfully

    String success_str_xpath = "//html/body/div/div[2]/div[3]/ul/li";

    Functions.MyWaitfunc(driver, success_str_xpath);
    if ((Functions.doesWebElementExist(driver, By.xpath(success_str_xpath)))
        && (driver
            .findElement(By.xpath(success_str_xpath))
            .getText()
            .contains("Successfully sent the email")))
      System.out.println("SUCCESS:Mail successfully sent !");
    else {
      System.out.println("FAIL:Mail NOT SENT !");
      System.out.println(driver.findElement(By.xpath(success_str_xpath)).getText());
      Exception e1 = null;
      throw e1;
    }
  }
  @Test
  public void stompBrokerRelay() {
    loadBeanDefinitions("websocket-config-broker-relay.xml");

    HandlerMapping hm = this.appContext.getBean(HandlerMapping.class);
    assertNotNull(hm);
    assertThat(hm, Matchers.instanceOf(SimpleUrlHandlerMapping.class));

    SimpleUrlHandlerMapping suhm = (SimpleUrlHandlerMapping) hm;
    assertThat(suhm.getUrlMap().keySet(), Matchers.hasSize(1));
    assertThat(suhm.getUrlMap().values(), Matchers.hasSize(1));
    assertEquals(2, suhm.getOrder());

    HttpRequestHandler httpRequestHandler = (HttpRequestHandler) suhm.getUrlMap().get("/foo/**");
    assertNotNull(httpRequestHandler);
    assertThat(httpRequestHandler, Matchers.instanceOf(SockJsHttpRequestHandler.class));
    SockJsHttpRequestHandler sockJsHttpRequestHandler =
        (SockJsHttpRequestHandler) httpRequestHandler;
    WebSocketHandler wsHandler =
        unwrapWebSocketHandler(sockJsHttpRequestHandler.getWebSocketHandler());
    assertNotNull(wsHandler);
    assertThat(wsHandler, Matchers.instanceOf(SubProtocolWebSocketHandler.class));
    assertNotNull(sockJsHttpRequestHandler.getSockJsService());

    UserDestinationResolver userDestResolver =
        this.appContext.getBean(UserDestinationResolver.class);
    assertNotNull(userDestResolver);
    assertThat(userDestResolver, Matchers.instanceOf(DefaultUserDestinationResolver.class));
    DefaultUserDestinationResolver defaultUserDestResolver =
        (DefaultUserDestinationResolver) userDestResolver;
    assertEquals("/user/", defaultUserDestResolver.getDestinationPrefix());

    StompBrokerRelayMessageHandler messageBroker =
        this.appContext.getBean(StompBrokerRelayMessageHandler.class);
    assertNotNull(messageBroker);
    assertEquals("clientlogin", messageBroker.getClientLogin());
    assertEquals("clientpass", messageBroker.getClientPasscode());
    assertEquals("syslogin", messageBroker.getSystemLogin());
    assertEquals("syspass", messageBroker.getSystemPasscode());
    assertEquals("relayhost", messageBroker.getRelayHost());
    assertEquals(1234, messageBroker.getRelayPort());
    assertEquals("spring.io", messageBroker.getVirtualHost());
    assertEquals(5000, messageBroker.getSystemHeartbeatReceiveInterval());
    assertEquals(5000, messageBroker.getSystemHeartbeatSendInterval());
    assertThat(
        messageBroker.getDestinationPrefixes(), Matchers.containsInAnyOrder("/topic", "/queue"));

    List<Class<? extends MessageHandler>> subscriberTypes =
        Arrays.<Class<? extends MessageHandler>>asList(
            SimpAnnotationMethodMessageHandler.class,
            UserDestinationMessageHandler.class,
            StompBrokerRelayMessageHandler.class);
    testChannel("clientInboundChannel", subscriberTypes, 0);
    testExecutor(
        "clientInboundChannel",
        Runtime.getRuntime().availableProcessors() * 2,
        Integer.MAX_VALUE,
        60);

    subscriberTypes =
        Arrays.<Class<? extends MessageHandler>>asList(SubProtocolWebSocketHandler.class);
    testChannel("clientOutboundChannel", subscriberTypes, 0);
    testExecutor(
        "clientOutboundChannel",
        Runtime.getRuntime().availableProcessors() * 2,
        Integer.MAX_VALUE,
        60);

    subscriberTypes =
        Arrays.<Class<? extends MessageHandler>>asList(
            StompBrokerRelayMessageHandler.class, UserDestinationMessageHandler.class);
    testChannel("brokerChannel", subscriberTypes, 0);
    try {
      this.appContext.getBean("brokerChannelExecutor", ThreadPoolTaskExecutor.class);
      fail("expected exception");
    } catch (NoSuchBeanDefinitionException ex) {
      // expected
    }

    String name = "webSocketMessageBrokerStats";
    WebSocketMessageBrokerStats stats =
        this.appContext.getBean(name, WebSocketMessageBrokerStats.class);
    String actual = stats.toString();
    String expected =
        "WebSocketSession\\[0 current WS\\(0\\)-HttpStream\\(0\\)-HttpPoll\\(0\\), "
            + "0 total, 0 closed abnormally \\(0 connect failure, 0 send limit, 0 transport error\\)\\], "
            + "stompSubProtocol\\[processed CONNECT\\(0\\)-CONNECTED\\(0\\)-DISCONNECT\\(0\\)\\], "
            + "stompBrokerRelay\\[0 sessions, relayhost:1234 \\(not available\\), processed CONNECT\\(0\\)-CONNECTED\\(0\\)-DISCONNECT\\(0\\)\\], "
            + "inboundChannel\\[pool size = \\d, active threads = \\d, queued tasks = \\d, completed tasks = \\d\\], "
            + "outboundChannelpool size = \\d, active threads = \\d, queued tasks = \\d, completed tasks = \\d\\], "
            + "sockJsScheduler\\[pool size = \\d, active threads = \\d, queued tasks = \\d, completed tasks = \\d\\]";

    assertTrue(
        "\nExpected: " + expected.replace("\\", "") + "\n  Actual: " + actual,
        actual.matches(expected));
  }