@Test
  public void testSendAndReceive() throws Exception {

    // Run the main controller
    ControllerRunner controllerRunner =
        new ControllerRunner(10, 9090, InetAddress.getLocalHost(), "127.0.0.1", 8008);
    controllerRunner.run();
    System.out.println("Controller running");

    Random random = new Random();
    int player = random.nextInt();

    // Connect a new controller and send test alarm
    Controller controller = new Controller(10);
    Socket connection1 = controller.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090);
    Alarm alarm = new Alarm(player, System.currentTimeMillis(), new PlayerCause(player));
    controller.send(alarm, connection1);

    Controller controller2 = new Controller(10);
    Socket connection2 = controller2.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090);
    long alarmtime = System.currentTimeMillis() + 500;
    Position position1 = new Position(player, System.currentTimeMillis(), 1, 2, 3);
    Position position2 = new Position(player, alarmtime, 100, 200, 300);
    controller2.send(position1, connection2);
    controller2.send(position2, connection2);
    controller2.send(new Request(player, DataType.ACCEL, -1, -1), connection2);
    controller2.send(new Request(player, DataType.POS, -1, -1), connection2);

    Thread.sleep(15000);
    List<Sendable> received = controller2.receive(connection2);
    List<Alarm> alarms = new ArrayList<Alarm>();
    List<Acceleration> accelerations = new ArrayList<Acceleration>();
    List<Position> positions = new ArrayList<Position>();

    // Distribute the sendable objects
    for (Sendable sendable : received) {
      if (sendable instanceof Alarm) {
        alarms.add((Alarm) sendable);

      } else if (sendable instanceof Service) {
        Service service = (Service) sendable;
        List<?> data = service.getData();
        for (Object o : data) {
          if (o instanceof Acceleration) {
            accelerations.add((Acceleration) o);
          } else if (o instanceof Position) {
            positions.add((Position) o);
          }
        }
      }
    }

    controller.disconnectFromClient(connection1);
    controller2.disconnectFromClient(connection2);

    assertTrue("Alarm was not sent from controller", alarms.size() >= 1);
    assertTrue("Acceleration not received from controller", accelerations.size() >= 1);
    assertTrue("Position 1 not contained in received positions", positions.contains(position1));
    assertTrue("Position 2 not contained in received positions", positions.contains(position2));
  }
Exemple #2
0
  @Test
  public void testInsertInstitucionNoExiste() {
    System.out.println("insertInstitucionExiste");
    Plantel plantel = null;
    PlantelDAO instance = new PlantelDAO();

    plantel = new Plantel();
    CInstitucion institucion = new CInstitucion();
    institucion.setIdCInstitucion((int) (Math.random() * 100));
    institucion.setNombre("No existente " + (int) (Math.random() * 100));
    institucion.setModificadoPor("system");
    institucion.setCreacion(new Date(System.currentTimeMillis()));
    institucion.setUltimaModif(new Date(System.currentTimeMillis()));

    plantel.setNombre("dsadsa 2" + (int) (Math.random() * 1000));
    plantel.setModificadoPor("system");
    plantel.setCreacion(new Date(System.currentTimeMillis()));
    plantel.setUltimaModif(new Date(System.currentTimeMillis()));
    //        plantel.setInstitucion(institucion);
    CInstitucionDAO cInstitucionDAO = new CInstitucionDAO();
    cInstitucionDAO.insert(institucion);

    int expResult = 1;
    // Insertar
    int result = instance.insert(plantel);
    assertEquals(expResult, result);
  }
  /**
   * Shuts down the test harness, and makes the best attempt possible to delete dataDir, unless the
   * system property "solr.test.leavedatadir" is set.
   */
  @Override
  public void tearDown() throws Exception {
    log.info("####TEARDOWN_START " + getTestName());
    if (factoryProp == null) {
      System.clearProperty("solr.directoryFactory");
    }

    if (h != null) {
      h.close();
    }
    String skip = System.getProperty("solr.test.leavedatadir");
    if (null != skip && 0 != skip.trim().length()) {
      System.err.println(
          "NOTE: per solr.test.leavedatadir, dataDir will not be removed: "
              + dataDir.getAbsolutePath());
    } else {
      if (!recurseDelete(dataDir)) {
        System.err.println(
            "!!!! WARNING: best effort to remove " + dataDir.getAbsolutePath() + " FAILED !!!!!");
      }
    }

    resetExceptionIgnores();
    super.tearDown();
  }
Exemple #4
0
  /** Test an invalid directory name, see if an error occurs */
  @Test
  public void testInvalidDirectory() {
    System.setSecurityManager(new NoExitSecurityManager());
    boolean exceptionThrown = false;

    cobertura = new Cobertura(null);
    try {
      cobertura.executeCobertura();
    } catch (ExitException e) {
      exceptionThrown = true;
      assertEquals(
          "Exit status invalid", OperiasStatus.ERROR_COBERTURA_TASK_CREATION.ordinal(), e.status);
    }

    exceptionThrown = false;

    cobertura = new Cobertura("src/../");
    try {
      cobertura.executeCobertura();
    } catch (ExitException e) {
      exceptionThrown = true;
      assertEquals(
          "Exit status invalid",
          OperiasStatus.ERROR_COBERTURA_TASK_OPERIAS_EXECUTION.ordinal(),
          e.status);
    }

    assertTrue("No exception was thrown", exceptionThrown);

    System.setSecurityManager(null);
  }
  @Test
  public void testDeleteNonEmptyDirectory() throws CoreException, IOException, SAXException {
    String dirPath1 = "sample/directory/path/sample1" + System.currentTimeMillis();
    String dirPath2 = "sample/directory/path/sample2" + System.currentTimeMillis();
    String fileName = "subfile.txt";
    String subDirectory = "subdirectory";

    createDirectory(dirPath1);
    createFile(dirPath1 + "/" + fileName, "Sample file content");
    createDirectory(dirPath2 + "/" + subDirectory);

    WebRequest request = getDeleteFilesRequest(dirPath1);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(
        "Could not delete directory with file",
        HttpURLConnection.HTTP_OK,
        response.getResponseCode());

    assertFalse(
        "Delete directory with file request returned OK, but the file still exists",
        checkDirectoryExists(dirPath1));

    request = getDeleteFilesRequest(dirPath2);
    response = webConversation.getResponse(request);
    assertEquals(
        "Could not delete directory with subdirectory",
        HttpURLConnection.HTTP_OK,
        response.getResponseCode());

    assertFalse(
        "Delete directory with subdirectory request returned OK, but the file still exists",
        checkDirectoryExists(dirPath2));
  }
    public void execute(WorkerProcessContext workerProcessContext) {
      // Check environment
      assertThat(System.getProperty("test.system.property"), equalTo("value"));
      assertThat(System.getenv().get("TEST_ENV_VAR"), equalTo("value"));

      // Check ClassLoaders
      ClassLoader antClassLoader = Project.class.getClassLoader();
      ClassLoader thisClassLoader = getClass().getClassLoader();
      ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

      assertThat(antClassLoader, not(sameInstance(systemClassLoader)));
      assertThat(thisClassLoader, not(sameInstance(systemClassLoader)));
      assertThat(antClassLoader.getParent(), equalTo(systemClassLoader.getParent()));
      try {
        assertThat(
            thisClassLoader.loadClass(Project.class.getName()),
            sameInstance((Object) Project.class));
      } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
      }

      // Send some messages
      TestListenerInterface sender =
          workerProcessContext.getServerConnection().addOutgoing(TestListenerInterface.class);
      sender.send("message 1", 1);
      sender.send("message 2", 2);
    }
Exemple #7
0
 @Before
 public void setup() throws IOException {
   // Avoiding "restx.shell.home_IS_UNDEFINED/ dir due to logs
   this.initialRestxShellHomeValue = System.getProperty("restx.shell.home");
   if (this.initialRestxShellHomeValue == null) {
     System.setProperty("restx.shell.home", workDirectory.newFolder(".restx").getAbsolutePath());
   }
 }
 public void testSpeed(IndexVotable x) {
   long start = System.currentTimeMillis();
   for (int i = 0; i < ivotes.length; i++) {
     x.voteIndexVoteSet(ivotes[i]);
   }
   NameVotingSystem.NameVote[] winners = x.getWinners();
   long end = System.currentTimeMillis();
   double vps = ivotes.length / ((double) (end - start) / 1000.0);
   System.out.println(x.name() + ": " + vps + " votes/second");
 }
  /**
   * Generates a SolrQueryRequest using the LocalRequestFactory
   *
   * @see #lrf
   */
  public SolrQueryRequest req(String[] params, String... moreParams) {
    String[] allParams = moreParams;
    if (params.length != 0) {
      int len = params.length + moreParams.length;
      allParams = new String[len];
      System.arraycopy(params, 0, allParams, 0, params.length);
      System.arraycopy(moreParams, 0, allParams, params.length, moreParams.length);
    }

    return lrf.makeRequest(allParams);
  }
 @Before
 public void setUp() {
   if (!Boolean.parseBoolean(System.getProperty("test.solr.verbose"))) {
     java.util.logging.Logger.getLogger("org.apache.solr")
         .setLevel(java.util.logging.Level.SEVERE);
     Utils.setLog4jLogLevel(org.apache.log4j.Level.WARN);
   }
   testDataParentPath = System.getProperty("test.data.path");
   testConfigFname = System.getProperty("test.config.file");
   // System.out.println("-----testDataParentPath = "+testDataParentPath);
 }
Exemple #11
0
 @Before
 public void setUp() throws Exception {
   lastTestFailed = false; // hope for the best, but set to true in asserts that fail
   // new output dir for each test
   tmpdir =
       new File(
               System.getProperty("java.io.tmpdir"),
               getClass().getSimpleName() + "-" + System.currentTimeMillis())
           .getAbsolutePath();
   //		tmpdir = "/tmp";
 }
  public void runTest(
      final String url,
      final int urlGroupSize,
      final ExceptionHandler exceptionHandler,
      int threadCount) {
    ok = true;
    long beginTime = System.currentTimeMillis();
    ArrayList<Thread> list = new ArrayList<Thread>();
    for (int t = 1; t <= threadCount; t++) {
      Thread tt =
          new Thread(url + "_runTest_" + t) {
            @Override
            public void run() {
              boolean useGroup = urlGroupSize > 1;
              for (int i = 1; i <= urlGroupSize; i++) {
                if (!ok) return;

                String resp = null;
                Throwable t = null;
                try {
                  if (useGroup) {
                    resp = httpClientUtils.get(url + i);
                  } else {
                    resp = httpClientUtils.get(url);
                  }
                } catch (Throwable e) {
                  Throwable ee = ExceptionUtils.getRootCause(e);
                  if (ee == null) {
                    ee = e;
                  }
                  Logger.error(this, "", ee);
                  t = ee;
                } finally {
                  if (ok) {
                    ok = exceptionHandler.handle(t);
                  }
                }
                Logger.info(this, "resp[" + i + "]=========[" + resp + "]=========");
              }
            }
          };
      list.add(tt);
      tt.start();
    }
    for (Thread tt : list) {
      try {
        tt.join();
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
    Assert.assertTrue(ok);
    Logger.info(this, "take time milliseconds: " + (System.currentTimeMillis() - beginTime));
  }
 @Override
 protected String run(final String... args) throws IOException {
   try {
     final ArrayOutput ao = new ArrayOutput();
     System.setOut(new PrintStream(ao));
     System.setErr(NULL);
     new BaseX(args);
     return ao.toString();
   } finally {
     System.setOut(OUT);
     System.setErr(ERR);
   }
 }
  public static int test(int n) throws Exception {
    PrintStream oldOut = System.out;
    int sum = 0;
    for (int i = 0; i < 10; i++) {
      ByteArrayOutputStream ba = new ByteArrayOutputStream(n * 10);
      PrintStream newOut = new PrintStream(ba);
      System.setOut(newOut);
      doPrint(n);
      sum += ba.size();
    }

    System.setOut(oldOut);
    return sum;
  }
  @Test
  public void testReadFileContents() throws CoreException, IOException, SAXException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);
    String fileName = "sampleFile" + System.currentTimeMillis() + ".txt";
    String fileContent = "Sample File Cotnent " + System.currentTimeMillis();
    createFile(directoryPath + "/" + fileName, fileContent);

    WebRequest request = getGetFilesRequest(directoryPath + "/" + fileName);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    assertEquals("Invalid file content", fileContent, response.getText());
  }
Exemple #16
0
  @Before
  public void init() {
    alist.add(a1);
    alist.add(a2);
    alist.add(a3);
    alist.add(a4);
    alist.add(a5);
    alist.add(a6);
    alist.add(a7);
    alist.add(a8);
    alist.add(a9);

    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));
  }
Exemple #17
0
  @BeforeClass
  public static void setUpOnce() throws Exception {
    miniCluster = System.getProperty("cluster.type").equals("mini");
    securedCluster = System.getProperty("cluster.secured").equals("true");
    System.out.println("realCluster - " + !miniCluster);
    System.out.println("securedCluster - " + securedCluster);

    Util.setLoggingThreshold("ERROR");

    if (miniCluster) {
      if (hbase == null) {
        hbase = new HBaseTestingUtility();
        conf = hbase.getConfiguration();
        conf.set("zookeeper.session.timeout", "3600000");
        conf.set("dfs.client.socket-timeout", "3600000");

        if (securedCluster) {
          hbase.startMiniCluster(RS_COUNT);
          hbase.waitTableEnabled(AccessControlLists.ACL_TABLE_NAME, 30000L);
          admin = new HBaseAdminWrapper(conf);
        } else {
          hbase.startMiniCluster(RS_COUNT);
          admin = hbase.getHBaseAdmin();
        }
      }
    } else {
      if (admin == null) {
        final String argsFileName =
            securedCluster
                ? "../../testClusterRealSecured.args"
                : "../../testClusterRealNonSecured.args";
        if (!Util.isFile(argsFileName)) {
          throw new IllegalStateException(
              "You have to define args file " + argsFileName + " for tests.");
        }

        String[] testArgs = {argsFileName};
        Args args = new TestArgs(testArgs);
        admin = HBaseClient.getAdmin(args);
        conf = admin.getConfiguration();
        RS_COUNT = getServerNameList().size();
      }
    }
    previousBalancerRunning = admin.setBalancerRunning(false, true);
    hConnection = HConnectionManager.createConnection(conf);

    USER_RW = User.createUserForTesting(conf, "rwuser", new String[0]);
  }
  @Test(timeout = TIMEOUT)
  public void testQuickSort() {
    DValue[] arrZero = new DValue[0];
    Sorting.quickSort(arrZero, new BasicComparator(), new Random());
    assertEquals(0, arrZero.length);
    DValue[] arrOne = new DValue[1];
    arrOne[0] = new DValue(4, 0);
    Sorting.quickSort(arrOne, new BasicComparator(), new Random());
    assertEquals(1, arrOne.length);
    assertEquals(4, arrOne[0].val.intValue());

    Random rand = new Random();
    HashMap<Integer, Integer> values = new HashMap<Integer, Integer>();
    for (int i = 0; i < 50; i++) {
      int arrlen = rand.nextInt(1000) + 2;
      DValue[] arrMany = new DValue[arrlen];
      DValue[] arrManySorted = new DValue[arrlen];
      for (int j = 0; j < arrlen; j++) {
        arrMany[j] = new DValue(rand.nextInt(200) - 90, 0);
        if (values.containsKey(arrMany[j].val)) {
          arrMany[j].count = values.get(arrMany[j].val) + 1;
          values.put(arrMany[j].val, arrMany[j].count);
        } else {
          values.put(arrMany[j].val, 0);
        }
      }
      System.arraycopy(arrMany, 0, arrManySorted, 0, arrlen);
      Arrays.sort(arrManySorted);
      Sorting.quickSort(arrMany, new BasicComparator(), new Random());
      assertArrayEquals(arrManySorted, arrMany);
    }
  }
  @Test
  public void testCopyFileOverwrite() throws Exception {
    String directoryPath = "/testCopyFile/directory/path" + System.currentTimeMillis();
    String sourcePath = directoryPath + "/source.txt";
    String destName = "destination.txt";
    String destPath = directoryPath + "/" + destName;
    createDirectory(directoryPath);
    createFile(sourcePath, "This is the contents");
    createFile(destPath, "Original file");

    // with no-overwrite, copy should fail
    JSONObject requestObject = new JSONObject();
    addSourceLocation(requestObject, sourcePath);
    WebRequest request =
        getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "copy,no-overwrite");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, response.getResponseCode());

    // now omit no-overwrite and copy should succeed and return 200 instead of 201
    request = getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "copy");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject responseObject = new JSONObject(response.getText());
    checkFileMetadata(responseObject, destName, null, null, null, null, null, null, null);
    assertTrue(checkFileExists(sourcePath));
    assertTrue(checkFileExists(destPath));
  }
  @Test
  public void testReadDirectoryChildren()
      throws CoreException, IOException, SAXException, JSONException {
    String dirName = "path" + System.currentTimeMillis();
    String directoryPath = "sample/directory/" + dirName;
    createDirectory(directoryPath);

    String subDirectory = "subdirectory";
    createDirectory(directoryPath + "/" + subDirectory);

    String subFile = "subfile.txt";
    createFile(directoryPath + "/" + subFile, "Sample file");

    WebRequest request = getGetFilesRequest(directoryPath + "?depth=1");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));

    assertEquals("Wrong number of directory children", 2, children.size());

    for (JSONObject child : children) {
      if (child.getBoolean("Directory")) {
        checkDirectoryMetadata(child, subDirectory, null, null, null, null, null);
      } else {
        checkFileMetadata(child, subFile, null, null, null, null, null, null, null);
      }
    }
  }
  @Test
  public void testCreateTopLevelFile()
      throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample" + System.currentTimeMillis();
    createDirectory(directoryPath);
    String fileName = "testfile.txt";

    WebRequest request =
        getPostFilesRequest(directoryPath, getNewFileJSON(fileName).toString(), fileName);
    WebResponse response = webConversation.getResponse(request);

    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    assertTrue(
        "Create file response was OK, but the file does not exist",
        checkFileExists(directoryPath + "/" + fileName));
    assertEquals(
        "Response should contain file metadata in JSON, but was " + response.getText(),
        "application/json",
        response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No file information in responce", responseObject);
    checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null);

    // should be able to perform GET on location header to obtain metadata
    String location = response.getHeaderField("Location");
    request = getGetFilesRequest(location + "?parts=meta");
    response = webConversation.getResource(request);
    assertNotNull(location);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    responseObject = new JSONObject(response.getText());
    assertNotNull("No direcory information in responce", responseObject);
    checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null);
  }
  @Test
  public void testCreateDirectory() throws CoreException, IOException, SAXException, JSONException {
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);

    String dirName = "testdir";
    webConversation.setExceptionsThrownOnErrorStatus(false);

    WebRequest request =
        getPostFilesRequest(directoryPath, getNewDirJSON(dirName).toString(), dirName);
    WebResponse response = webConversation.getResponse(request);

    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    assertTrue(
        "Create directory response was OK, but the directory does not exist",
        checkDirectoryExists(directoryPath + "/" + dirName));
    assertEquals(
        "Response should contain directory metadata in JSON, but was " + response.getText(),
        "application/json",
        response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No directory information in response", responseObject);
    checkDirectoryMetadata(responseObject, dirName, null, null, null, null, null);

    // should be able to perform GET on location header to obtain metadata
    String location = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
    request = getGetFilesRequest(location);
    response = webConversation.getResource(request);
    assertNotNull(location);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    responseObject = new JSONObject(response.getText());
    assertNotNull("No direcory information in responce", responseObject);
    checkDirectoryMetadata(responseObject, dirName, null, null, null, null, null);
  }
 private static DatabaseEngine databaseEngine() {
   String databaseEngine = System.getProperty(DATABASE_ENGINE_SYSTEM_PARAMETER);
   DatabaseEngine engine =
       databaseEngine != null ? DatabaseEngine.valueOf(databaseEngine) : DatabaseEngine.mysql;
   // logger.info("Using database enigine: " + engine);
   return engine;
 }
  @Test
  public void testSoakTestWithRandomData() throws IOException, InterruptedException {

    // for (int i = 30; i < 50; i++) {
    System.out.print("SoakTesting ");
    int max = 1000000;
    for (int j = 1; j < max; j++) {
      if (j % 100 == 0) System.out.print(".");
      Random rnd = new Random(System.currentTimeMillis());

      final ChronicleMap<Integer, CharSequence> map = rnd.nextBoolean() ? map1 : map2;

      if (rnd.nextBoolean()) {
        map.put((int) rnd.nextInt(100), "test" + j);
      } else {
        map.remove((int) rnd.nextInt(100));
      }
    }

    System.out.println("\nwaiting till equal");

    waitTillUnchanged(1000);
    System.out.println("time t=" + t);
    Assert.assertEquals(new TreeMap(map1), new TreeMap(map2));
  }
Exemple #25
0
 @Test
 public void now() throws Exception {
   assertTrue(sufficientlyEqual(DynamicDate.getInstance("now"), new Date()));
   assertTrue(
       sufficientlyEqual(
           DynamicDate.getInstance("now - 5 minute"),
           new Date(System.currentTimeMillis() - 5 * 60 * 1000)));
   assertTrue(
       sufficientlyEqual(
           DynamicDate.getInstance("now + 5 minute"),
           new Date(System.currentTimeMillis() + 5 * 60 * 1000)));
   assertTrue(
       sufficientlyEqual(
           DynamicDate.getInstance("now + 5 hour"),
           new Date(System.currentTimeMillis() + 5 * 60 * 60 * 1000)));
 }
  @Test
  public void testDisruptorCommandBusRepositoryNotAvailableOutsideOfInvokerThread() {
    DisruptorCommandBus commandBus = new DisruptorCommandBus(eventStore, eventBus);
    Repository<Aggregate> repository =
        commandBus.createRepository(new GenericAggregateFactory<Aggregate>(Aggregate.class));

    AggregateAnnotationCommandHandler<Aggregate> handler =
        new AggregateAnnotationCommandHandler<Aggregate>(Aggregate.class, repository);
    AggregateAnnotationCommandHandler.subscribe(handler, commandBus);
    DefaultCommandGateway gateway = new DefaultCommandGateway(commandBus);

    // Create the aggregate
    String aggregateId = "" + System.currentTimeMillis();
    gateway.sendAndWait(new CreateCommandAndEvent(aggregateId));

    // Load the aggretate from the repository -- from "worker" thread
    UnitOfWork uow = DefaultUnitOfWork.startAndGet();
    try {
      Aggregate aggregate = repository.load(aggregateId);
      fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
      assertTrue(e.getMessage().contains("DisruptorCommandBus"));
    } finally {
      uow.rollback();
    }
  }
 /*
  * Write some entries in the log file.
  * 7 different tables with name "testtb-%d"
  * 10 region per table with name "tableName-region-%d"
  * 50 entry with row key "row-%d"
  */
 private void writeTestLog(final Path logFile) throws IOException {
   fs.mkdirs(logFile.getParent());
   HLog.Writer writer = HLog.createWriter(fs, logFile, conf);
   try {
     for (int i = 0; i < 7; ++i) {
       byte[] tableName = getTableName(i);
       for (int j = 0; j < 10; ++j) {
         byte[] regionName = getRegionName(tableName, j);
         for (int k = 0; k < 50; ++k) {
           byte[] rowkey = Bytes.toBytes("row-" + k);
           HLogKey key =
               new HLogKey(
                   regionName,
                   tableName,
                   (long) k,
                   System.currentTimeMillis(),
                   HConstants.DEFAULT_CLUSTER_ID);
           WALEdit edit = new WALEdit();
           edit.add(new KeyValue(rowkey, TEST_FAMILY, TEST_QUALIFIER, rowkey));
           writer.append(new HLog.Entry(key, edit));
         }
       }
     }
   } finally {
     writer.close();
   }
 }
Exemple #28
0
  /**
   * Runs a request with the specified arguments and server arguments.
   *
   * @param args command-line arguments
   * @param sargs server arguments
   * @return result
   * @throws IOException I/O exception
   */
  private static String run(final String[] args, final String[] sargs) throws IOException {
    final BaseXServer server = createServer(sargs);
    final ArrayOutput ao = new ArrayOutput();
    System.setOut(new PrintStream(ao));
    System.setErr(NULL);

    final StringList sl = new StringList();
    sl.add("-p9999").add("-U" + Text.S_ADMIN).add("-P" + Text.S_ADMIN).add(args);
    try {
      new BaseXClient(sl.finish());
      return ao.toString();
    } finally {
      System.setErr(ERR);
      stopServer(server);
    }
  }
 private Customer getNewCustomerWithUniqueName() {
   Customer c1 = getCustomerComponent().createNew();
   c1.setName("A" + System.currentTimeMillis());
   c1.setPhoneNumber("808-555-1212");
   getCustomerComponent().persist(c1);
   return c1;
 }
  @Test(timeout = TIMEOUT)
  public void testRadixSort() {
    int[] arrZero = new int[0];
    arrZero = Sorting.radixSort(arrZero);
    assertEquals(0, arrZero.length);
    int[] arrOne = new int[1];
    arrOne[0] = 4;
    arrOne = Sorting.radixSort(arrOne);
    assertEquals(1, arrOne.length);
    assertEquals(4, arrOne[0]);

    Random rand = new Random();
    for (int i = 0; i < 50; i++) {
      int arrlen = rand.nextInt(1000) + 2;
      int[] arrMany = new int[arrlen];
      int[] arrManySorted = new int[arrlen];
      for (int j = 0; j < arrlen; j++) {
        arrMany[j] = rand.nextInt(200) - 90;
      }
      System.arraycopy(arrMany, 0, arrManySorted, 0, arrlen);
      Arrays.sort(arrManySorted);
      arrMany = Sorting.radixSort(arrMany);
      assertArrayEquals(arrManySorted, arrMany);
    }
  }