Пример #1
0
  @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));
  }
  @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));
  }
Пример #3
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);
  }
Пример #4
0
 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");
 }
  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));
  }
Пример #6
0
  @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());
  }
Пример #7
0
  @Test
  public void registerUserSuccess_emailAsUsername() {
    configureRelamRegistrationEmailAsUsername(true);

    try {
      loginPage.open();
      loginPage.clickRegister();
      registerPage.assertCurrent();

      registerPage.registerWithEmailAsUsername(
          "firstName", "lastName", "registerUserSuccessE@email", "password", "password");

      assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());

      String userId =
          events
              .expectRegister("registerUserSuccessE@email", "registerUserSuccessE@email")
              .assertEvent()
              .getUserId();
      events
          .expectLogin()
          .detail("username", "registerusersuccesse@email")
          .user(userId)
          .assertEvent();

      UserModel user = getUser(userId);
      Assert.assertNotNull(user);
      Assert.assertNotNull(user.getCreatedTimestamp());
      // test that timestamp is current with 10s tollerance
      Assert.assertTrue((System.currentTimeMillis() - user.getCreatedTimestamp()) < 10000);

    } finally {
      configureRelamRegistrationEmailAsUsername(false);
    }
  }
Пример #8
0
  @Test
  public void registerUserSuccess() {
    loginPage.open();
    loginPage.clickRegister();
    registerPage.assertCurrent();

    registerPage.register(
        "firstName",
        "lastName",
        "registerUserSuccess@email",
        "registerUserSuccess",
        "password",
        "password");

    assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());

    String userId =
        events
            .expectRegister("registerUserSuccess", "registerUserSuccess@email")
            .assertEvent()
            .getUserId();
    events.expectLogin().detail("username", "registerusersuccess").user(userId).assertEvent();

    UserModel user = getUser(userId);
    Assert.assertNotNull(user);
    Assert.assertNotNull(user.getCreatedTimestamp());
    // test that timestamp is current with 10s tollerance
    Assert.assertTrue((System.currentTimeMillis() - user.getCreatedTimestamp()) < 10000);
    // test user info is set from form
    assertEquals("registerusersuccess", user.getUsername());
    assertEquals("registerusersuccess@email", user.getEmail());
    assertEquals("firstName", user.getFirstName());
    assertEquals("lastName", user.getLastName());
  }
Пример #9
0
  @Test
  public void timestamp() throws SQLException {
    connectWithJulianDayModeActivated();
    long now = System.currentTimeMillis();
    Timestamp d1 = new Timestamp(now);
    Date d2 = new Date(now);
    Time d3 = new Time(now);

    stat.execute("create table t (c1);");
    PreparedStatement prep = conn.prepareStatement("insert into t values (?);");
    prep.setTimestamp(1, d1);
    prep.executeUpdate();

    ResultSet rs = stat.executeQuery("select c1 from t;");
    assertTrue(rs.next());
    assertEquals(d1, rs.getTimestamp(1));

    rs = stat.executeQuery("select date(c1, 'localtime') from t;");
    assertTrue(rs.next());
    assertEquals(d2.toString(), rs.getString(1));

    rs = stat.executeQuery("select time(c1, 'localtime') from t;");
    assertTrue(rs.next());
    assertEquals(d3.toString(), rs.getString(1));

    rs = stat.executeQuery("select strftime('%Y-%m-%d %H:%M:%f', c1, 'localtime') from t;");
    assertTrue(rs.next());
    // assertEquals(d1.toString(), rs.getString(1)); // ms are not occurate...
  }
  @Test
  @RunAsClient
  @Ignore
  public void testUpdateAssetFromJaxB(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", MediaType.APPLICATION_XML);
    connection.connect();
    assertEquals(200, connection.getResponseCode());

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    JAXBContext context = JAXBContext.newInstance(Asset.class);
    Unmarshaller un = context.createUnmarshaller();
    Asset a = (Asset) un.unmarshal(br);
    a.setDescription("An updated description.");
    a.setPublished(new Date(System.currentTimeMillis()));
    connection.disconnect();

    HttpURLConnection conn2 = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty(
        "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes())));
    Marshaller ma = context.createMarshaller();
    conn2.setRequestMethod("PUT");
    conn2.setRequestProperty("Content-Type", MediaType.APPLICATION_XML);
    conn2.setRequestProperty("Content-Length", Integer.toString(a.toString().getBytes().length));
    conn2.setUseCaches(false);
    conn2.setDoInput(true);
    conn2.setDoOutput(true);
    ma.marshal(a, conn2.getOutputStream());
    assertEquals(200, connection.getResponseCode());
    conn2.disconnect();
  }
  @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();
    }
  }
Пример #12
0
 private Customer getNewCustomerWithUniqueName() {
   Customer c1 = getCustomerComponent().createNew();
   c1.setName("A" + System.currentTimeMillis());
   c1.setPhoneNumber("808-555-1212");
   getCustomerComponent().persist(c1);
   return c1;
 }
Пример #13
0
  @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);
  }
Пример #14
0
 @AfterClass
 public static void tearDownClass() {
   Logger.info(
       HttpClientUtilsTest.class,
       "============= [tearDownClass]global take time milliseconds: "
           + (System.currentTimeMillis() - g_beginTime));
   if (httpServer != null) {
     httpServer.stop(0);
   }
   if (httpServer2 != null) {
     httpServer2.stop(0);
   }
   if (serverSocket != null && !serverSocket.isClosed()) {
     try {
       serverSocket.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   for (Socket s : clientSockets) {
     try {
       if (!s.isClosed()) s.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Пример #15
0
  @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));
  }
Пример #16
0
  @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);
      }
    }
  }
Пример #17
0
 /*
  * 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();
   }
 }
Пример #18
0
  @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);
  }
Пример #19
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 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));
  }
Пример #21
0
 @After
 public void clean() {
   Logger.info(
       this,
       "============= test take time milliseconds: " + (System.currentTimeMillis() - beginTime));
   if (httpClientUtils != null) {
     httpClientUtils.destroy();
   }
 }
Пример #22
0
  @Test
  public void testDirectoryWithSpaces() throws CoreException, IOException, SAXException {
    String basePath = "sampe/dir with spaces/long" + System.currentTimeMillis();
    createDirectory(basePath);

    WebRequest request = getGetFilesRequest(basePath);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
  }
Пример #23
0
 @Before
 public void reset() {
   Logger.info(this, "-------------- reset begin -------------");
   beginTime = System.currentTimeMillis();
   if (httpClientUtils != null) {
     httpClientUtils.destroy();
   }
   Logger.info(this, "-------------- reset end -------------");
 }
Пример #24
0
 @Test
 public void test007() throws Exception {
   J2V8Handler h =
       new J2V8Handler(
           readFile("../../src/main/resources/js/j2v8test07.js", Charset.defaultCharset()), 1);
   h.init();
   try {
     String data =
         readFile("../../src/main/resources/js/j2v8test07_data.js", Charset.defaultCharset());
     long start = System.currentTimeMillis();
     for (int i = 0; i < 1000000; i++) h.process(data);
     long elapsedTime = System.currentTimeMillis() - start;
     System.err.println(elapsedTime);
     assertEquals(true, true);
   } catch (Exception e) {
     System.err.println(e.getMessage());
     assertEquals(true, false);
   }
 }
Пример #25
0
/** @author Guilhem Legal (Geomatys) */
public class TimePositionTypeTest extends org.geotoolkit.test.TestBase {

  private static final Date date =
      new Date((System.currentTimeMillis() / 1000) * 1000); // remove ms

  private static final SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  private static final SimpleDateFormat f2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  private static final SimpleDateFormat f3 = new SimpleDateFormat("yyyy-MM-dd");

  @BeforeClass
  public static void setUpClass() throws Exception {}

  @AfterClass
  public static void tearDownClass() throws Exception {}

  @Test
  public void dateParsingTest() throws Exception {

    final String s1 = f1.format(date);

    TimePositionType tp = new TimePositionType(s1);
    assertEquals(date, tp.getDate());

    final String s2 = f2.format(date);
    tp = new TimePositionType(s2);
    assertEquals(date, tp.getDate());

    final String s3 = f3.format(date);
    tp = new TimePositionType(s3);

    final Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    final Date dateNoTime = cal.getTime();

    assertEquals(dateNoTime, tp.getDate());
  }

  @Test
  public void setValueTest() throws Exception {
    String s = null;
    TimePositionType tp = new TimePositionType(s);

    final Date d = f3.parse("2010-01-01");
    tp.setValue(d);
    assertEquals(tp.getValues(), Arrays.asList("2010-01-01"));

    final Date d2 = f2.parse("2010-01-01 01:01:02");
    tp.setValue(d2);
    assertEquals(tp.getValues(), Arrays.asList("2010-01-01T01:01:02.00"));
  }
}
Пример #26
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";
 }
Пример #27
0
 @Test
 public void testDurationString() {
   long interval = 6 * HOUR + 4 * MINUTE + 4 * SECOND;
   assertEquals("6 hours, 4 minutes and 4 seconds", durationString(interval));
   Date date = new Date();
   Calendar cal = Calendar.getInstance();
   cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) - 3);
   cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) - 8);
   interval = System.currentTimeMillis() - cal.getTimeInMillis();
   assertEquals("3 years and 8 seconds", durationString(interval));
 }
Пример #28
0
 public static boolean test3Snippet(int a, int b) {
   int val = (int) System.currentTimeMillis();
   int c = val + 1;
   if (a == b) {
     c = val;
   }
   if (c != val) {
     return false;
   }
   return true;
 }
Пример #29
0
 @Test
 public void testVvshortDurationString() {
   long interval = 6 * HOUR + 4 * MINUTE + 4 * SECOND;
   assertEquals("6h4m", vvshortDurationString(interval));
   Date date = new Date();
   Calendar cal = Calendar.getInstance();
   cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) - 3);
   cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) - 8);
   interval = System.currentTimeMillis() - cal.getTimeInMillis();
   assertEquals("3Y8s", vvshortDurationString(interval));
 }
 @Test
 public void getUpdatedGraphTimeNotNull() throws Exception {
   Timestamp expected = new Timestamp(System.currentTimeMillis());
   String values = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ";
   controllerDao.insert(controller());
   controllerDao.updateControllerGraph(1L, values, expected);
   String graphs = controllerDao.getControllerGraph(1L);
   assertNotNull(graphs);
   Timestamp actual = controllerDao.getUpdatedGraphTime(1L);
   assertEquals(expected, actual);
 }