@Test
  public void getTopologyLogLocalWhileAuthenticated() {
    final String requestTopologyId = "topology-test";
    final TopologyLog mockedLog = RandomGenerator.randomObject(TopologyLog.class);

    doReturn(mockedLog)
        .when(topologyServiceMock)
        .getTopologyLogLocal(
            requestTopologyId, TEST_SUBJECT_ID, mockedLog.getOffset(), mockedLog.getCount());

    mockAuthenticatedSubject();

    TopologyLog responseLog =
        resource()
            .path("/api/topologies/" + requestTopologyId + "/log")
            .queryParam("offset", Long.toString(mockedLog.getOffset()))
            .queryParam("limit", Long.toString(mockedLog.getCount()))
            .accept(MediaType.APPLICATION_JSON)
            .get(TopologyLog.class);

    assertEquals(
        "Response topology log should match the request topology log", mockedLog, responseLog);

    verify(topologyServiceMock)
        .getTopologyLogLocal(
            requestTopologyId, TEST_SUBJECT_ID, mockedLog.getOffset(), mockedLog.getCount());
  }
 @Test
 public void test() throws IOException, ClassNotFoundException {
   this.test((Serializable) null, true);
   this.test("test", true);
   this.test(Boolean.TRUE, true);
   this.test(Byte.valueOf(Byte.MAX_VALUE), true);
   this.test(Character.valueOf(Character.MAX_VALUE), true);
   this.test(Double.valueOf(Double.MAX_VALUE), true);
   this.test(Float.valueOf(Float.MAX_VALUE), true);
   this.test(Integer.valueOf(Integer.MAX_VALUE), true);
   this.test(Long.valueOf(Long.MAX_VALUE), true);
   this.test(Short.valueOf(Short.MAX_VALUE), true);
   this.test(new String[] {"test"}, true);
   this.test(new boolean[] {Boolean.TRUE}, true);
   this.test(new byte[] {Byte.MAX_VALUE}, true);
   this.test(new char[] {Character.MAX_VALUE}, true);
   this.test(new double[] {Double.MAX_VALUE}, true);
   this.test(new float[] {Float.MAX_VALUE}, true);
   this.test(new int[] {Integer.MAX_VALUE}, true);
   this.test(new long[] {Long.MAX_VALUE}, true);
   this.test(new short[] {Short.MAX_VALUE}, true);
   this.test(new Boolean[] {Boolean.TRUE}, true);
   this.test(new Byte[] {Byte.valueOf(Byte.MAX_VALUE)}, true);
   this.test(new Character[] {Character.valueOf(Character.MAX_VALUE)}, true);
   this.test(new Double[] {Double.valueOf(Double.MAX_VALUE)}, true);
   this.test(new Float[] {Float.valueOf(Float.MAX_VALUE)}, true);
   this.test(new Integer[] {Integer.valueOf(Integer.MAX_VALUE)}, true);
   this.test(new Long[] {Long.valueOf(Long.MAX_VALUE)}, true);
   this.test(new Short[] {Short.valueOf(Short.MAX_VALUE)}, true);
   this.test(this.getClass(), false);
   this.test(new Date(System.currentTimeMillis()), false);
   this.test(new Object(), false);
 }
Example #3
0
  @Test
  public void testUpsertDateValues() throws Exception {
    long ts = nextTimestamp();
    Date now = new Date(System.currentTimeMillis());
    ensureTableCreated(getUrl(), TestUtil.PTSDB_NAME, null, ts - 2);
    Properties props = new Properties();
    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1)); // Execute at timestamp 1
    Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String dateString = "1999-01-01 02:00:00";
    PreparedStatement upsertStmt =
        conn.prepareStatement(
            "upsert into ptsdb(inst,host,date) values('aaa','bbb',to_date('" + dateString + "'))");
    int rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    upsertStmt =
        conn.prepareStatement(
            "upsert into ptsdb(inst,host,date) values('ccc','ddd',current_date())");
    rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    conn.commit();

    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 1
    conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String select = "SELECT date,current_date() FROM ptsdb";
    ResultSet rs = conn.createStatement().executeQuery(select);
    Date then = new Date(System.currentTimeMillis());
    assertTrue(rs.next());
    Date date = DateUtil.parseDate(dateString);
    assertEquals(date, rs.getDate(1));
    assertTrue(rs.next());
    assertTrue(rs.getDate(1).after(now) && rs.getDate(1).before(then));
    assertFalse(rs.next());
  }
  @Test
  public void testRemoveCookbook() throws IOException {
    Long testAccountId = Long.valueOf(2);
    Long testAppId = Long.valueOf(2);

    File accountDirectory = new File(cookbookDestinationRoot + "/" + testAccountId);
    ensureFileNotExists(accountDirectory);

    File cookbookInput = new File("src/test/resources/test-xlc-fds");
    File cookbookTarget =
        new File(
            cookbookDestinationRoot + "/" + testAccountId + "/" + testAppId + "/" + "test-xlc-fds");

    ApplicationModel application =
        ApplicationModelBuilder.newInstance().accountId(testAccountId).appId(testAppId).build();
    CookbookModel cookbook =
        CookbookModelBuilder.newInstance().application(application).name("test-xlc-fds").build();

    givenCookbookExists(cookbook);
    givenCookbookFileExists(cookbookInput, cookbookTarget);

    assertTrue(cookbookTarget.exists());
    manager.removeCookbook(1L);
    assertFalse(cookbookTarget.exists());

    ensureFileNotExists(accountDirectory);
  }
Example #5
0
  @Test
  public void testUpsertValuesWithExpression() throws Exception {
    long ts = nextTimestamp();
    ensureTableCreated(getUrl(), "IntKeyTest", null, ts - 2);
    Properties props = new Properties();
    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1)); // Execute at timestamp 1
    Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String upsert = "UPSERT INTO IntKeyTest VALUES(-1)";
    PreparedStatement upsertStmt = conn.prepareStatement(upsert);
    int rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    upsert = "UPSERT INTO IntKeyTest VALUES(1+2)";
    upsertStmt = conn.prepareStatement(upsert);
    rowsInserted = upsertStmt.executeUpdate();
    assertEquals(1, rowsInserted);
    conn.commit();
    conn.close();

    props.setProperty(
        PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 1
    conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    String select = "SELECT i FROM IntKeyTest";
    ResultSet rs = conn.createStatement().executeQuery(select);
    assertTrue(rs.next());
    assertEquals(-1, rs.getInt(1));
    assertTrue(rs.next());
    assertEquals(3, rs.getInt(1));
    assertFalse(rs.next());
  }
  @Test
  public void test_manuel_int32_t() throws IOException {
    // 6B 73 68 6F
    // 107 115 104 111
    // 29547 28520
    // 1869116267

    byte[] input1 = {107, 115, 104, 111}; // 6B 73 68 6F
    Long expected1 = 1869116267L; // 1869116267
    BinFileReader binFileReader =
        new BinFileReader(new BufferedInputStream(new ByteArrayInputStream(input1)));
    SignedInteger result1 = binFileReader.int32_t();
    assertEquals("int32_t6B 73 68 6F asLong() = 1869116267", expected1, result1.asLong());
    assertEquals(
        "int32_t6B 73 68 6F getSignedValue() = 1869116267",
        (Integer) expected1.intValue(),
        result1.getSignedValue());
    byte[] input2 = {32, 75, -61, -68}; // 20 4B C3 BC
    Long expected2 = -1128051936L; // -1128051936
    binFileReader = new BinFileReader(new BufferedInputStream(new ByteArrayInputStream(input2)));
    SignedInteger result2 = binFileReader.int32_t();
    assertEquals("int32_t20 4B C3 BC asLong() = -1128051936", expected2, result2.asLong());
    assertEquals(
        "int32_t20 4B C3 BC getSignedValue() = -1128051936",
        (Integer) expected2.intValue(),
        result2.getSignedValue());
  }
 /**
  * Verifies blob properties from output, to that sent in during input
  *
  * @param expectedHeaders the expected headers in the response.
  * @param response the {@link HttpResponse} that contains the headers.
  */
 private void verifyBlobProperties(HttpHeaders expectedHeaders, HttpResponse response) {
   assertEquals(
       "Blob size does not match",
       Long.parseLong(expectedHeaders.get(RestUtils.Headers.BLOB_SIZE)),
       Long.parseLong(HttpHeaders.getHeader(response, RestUtils.Headers.BLOB_SIZE)));
   assertEquals(
       RestUtils.Headers.SERVICE_ID + " does not match",
       expectedHeaders.get(RestUtils.Headers.SERVICE_ID),
       HttpHeaders.getHeader(response, RestUtils.Headers.SERVICE_ID));
   assertEquals(
       RestUtils.Headers.PRIVATE + " does not match",
       expectedHeaders.get(RestUtils.Headers.PRIVATE),
       HttpHeaders.getHeader(response, RestUtils.Headers.PRIVATE));
   assertEquals(
       RestUtils.Headers.AMBRY_CONTENT_TYPE + " does not match",
       expectedHeaders.get(RestUtils.Headers.AMBRY_CONTENT_TYPE),
       HttpHeaders.getHeader(response, RestUtils.Headers.AMBRY_CONTENT_TYPE));
   assertTrue(
       "No " + RestUtils.Headers.CREATION_TIME,
       HttpHeaders.getHeader(response, RestUtils.Headers.CREATION_TIME, null) != null);
   if (Long.parseLong(expectedHeaders.get(RestUtils.Headers.TTL)) != Utils.Infinite_Time) {
     assertEquals(
         RestUtils.Headers.TTL + " does not match",
         expectedHeaders.get(RestUtils.Headers.TTL),
         HttpHeaders.getHeader(response, RestUtils.Headers.TTL));
   }
   if (expectedHeaders.contains(RestUtils.Headers.OWNER_ID)) {
     assertEquals(
         RestUtils.Headers.OWNER_ID + " does not match",
         expectedHeaders.get(RestUtils.Headers.OWNER_ID),
         HttpHeaders.getHeader(response, RestUtils.Headers.OWNER_ID));
   }
 }
Example #8
0
  @Test
  public void testUpsertValuesWithDate() throws Exception {
    long ts = nextTimestamp();
    Properties props = new Properties();
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
    Connection conn = DriverManager.getConnection(getUrl(), props);
    conn.createStatement()
        .execute("create table UpsertDateTest (k VARCHAR not null primary key,date DATE)");
    conn.close();

    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5));
    conn = DriverManager.getConnection(getUrl(), props);
    conn.createStatement()
        .execute("upsert into UpsertDateTest values ('a',to_date('2013-06-08 00:00:00'))");
    conn.commit();
    conn.close();

    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10));
    conn = DriverManager.getConnection(getUrl(), props);
    ResultSet rs =
        conn.createStatement().executeQuery("select k,to_char(date) from UpsertDateTest");
    assertTrue(rs.next());
    assertEquals("a", rs.getString(1));
    assertEquals("2013-06-08 00:00:00", rs.getString(2));
  }
  /**
   * 根据角色id获取角色菜单关系测试方法.
   *
   * @throws Exception 普通异常.
   */
  @Test
  public final void testQueryRoleMenuItemMap() throws Exception {
    Subject currentUser = ShiroHelper.getSubject(this.request, this.response);
    UsernamePasswordToken token =
        new UsernamePasswordToken("user1", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    token.setRememberMe(true);
    try {
      currentUser.login(token);
      UserPo uPo = new UserPo();
      uPo.setUserId(Long.valueOf("1"));
      uPo.setLoginName("user1");
      uPo.setPassword("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
      Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-01-12 23:30:20");
      uPo.setCreateTime(date);
      uPo.setCreatorId(Long.valueOf("1"));
      uPo.setIsDelete(false);
      uPo.setIsLockUp(false);
      uPo.setVersion(Long.valueOf("0"));
      currentUser.getSession().setAttribute("user", uPo);
    } catch (Exception se) {
      se.printStackTrace();
    }

    request.setParameter("roleMenuItemMap", "{\"roleId\":\"2\"}");
    String resultMessage = executeAction("/SuperW/queryRoleMenuItemMap.action");
    boolean rs =
        -1
            != resultMessage.indexOf(
                "{\"userToken\":true,\"serviceResult\":true," + "\"resultInfo\":\"查询角色菜单关系列表成功\"");
    assertTrue("返回服務信息錯誤失敗", rs);
  }
Example #10
0
  @Test
  public void subBufferTest02FloatBuffer() {

    out.println(" - - - subBufferTest - - - ");

    @SuppressWarnings("unchecked")
    final CLPlatform platform = CLPlatform.getDefault(version(CL_1_1));
    if (platform == null) {
      out.println("aborting subBufferTest");
      return;
    }

    final CLContext context = CLContext.create(platform);
    try {
      final int subelements = 5;
      final long lMaxAlignment = context.getMaxMemBaseAddrAlign();
      final int iMaxAlignment = Bitstream.uint32LongToInt(lMaxAlignment);
      System.err.println(
          "XXX: maxAlignment "
              + lMaxAlignment
              + ", 0x"
              + Long.toHexString(lMaxAlignment)
              + ", (int)"
              + iMaxAlignment
              + ", (int)0x"
              + Integer.toHexString(iMaxAlignment));
      if (-1 == iMaxAlignment) {
        throw new RuntimeException(
            "Cannot handle MaxMemBaseAddrAlign > MAX_INT, has 0x"
                + Long.toHexString(lMaxAlignment));
      }
      // FIXME: See Bug 979: Offset/Alignment via offset calculation per element-count is faulty!
      final int floatsPerAlignment = iMaxAlignment / Buffers.SIZEOF_FLOAT;
      // device + direct buffer
      final CLBuffer<FloatBuffer> buffer =
          context.createFloatBuffer(floatsPerAlignment + subelements);
      assertFalse(buffer.isSubBuffer());
      assertNotNull(buffer.getSubBuffers());
      assertTrue(buffer.getSubBuffers().isEmpty());

      final CLSubBuffer<FloatBuffer> subBuffer =
          buffer.createSubBuffer(floatsPerAlignment, subelements);

      assertTrue(subBuffer.isSubBuffer());
      assertEquals(subelements, subBuffer.getBuffer().capacity());
      assertEquals(floatsPerAlignment, subBuffer.getOffset());
      assertEquals(iMaxAlignment, subBuffer.getCLOffset());
      assertEquals(buffer, subBuffer.getParent());
      assertEquals(1, buffer.getSubBuffers().size());

      assertEquals(subBuffer.getCLCapacity(), subBuffer.getBuffer().capacity());

      subBuffer.release();
      assertEquals(0, buffer.getSubBuffers().size());

    } finally {
      context.release();
    }
  }
 @Test
 public void test_int64_t() throws IOException {
   for (Long exp : expected_int64) {
     SignedLong result = binFileReader.int64_t();
     assertEquals("int64_t " + exp + " getSignedValue()", exp, result.getSignedValue());
     assertEquals("int64_t " + exp + " toString()", exp.toString(), result.toString());
   }
 }
 @Test
 public void test()
     throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException,
         SQLException {
   JDBC dao = JDBC.getInstance();
   dao.insertToTweet(
       Long.parseLong("111"), "aaaa", 52.1, 2.36, Long.parseLong("454555"), "sdfg", "asdf");
 }
 /** goal 0-100 (impose finish at 100) */
 @Test
 public void testGetEnd() {
   int offset = 0;
   int limit = 5;
   Long finish = 100l;
   long total = 213;
   Sharding d = new Sharding();
   d.setLimit(offset, limit, finish);
   d.setCounts(total);
   long end = d.getEnd();
   assertEquals(finish.longValue(), end);
 }
 @Test
 public void test_int32_t() throws IOException {
   for (Long exp : expected_int32) {
     SignedInteger result = binFileReader.int32_t();
     assertEquals("int32_t " + exp + " asInt()", exp, result.asLong());
     assertEquals(
         "int32_t " + exp + " getSignedValue()",
         (Integer) exp.intValue(),
         result.getSignedValue());
     assertEquals("int32_t " + exp + " toString()", exp.toString(), result.toString());
   }
 }
 @Test
 public void testLANG984() { // Long durations
   assertEquals("0", DurationFormatUtils.formatDuration(0, "S"));
   assertEquals(
       Integer.toString(Integer.MAX_VALUE),
       DurationFormatUtils.formatDuration(Integer.MAX_VALUE, "S"));
   long maxIntPlus = Integer.MAX_VALUE;
   maxIntPlus++;
   assertEquals(Long.toString(maxIntPlus), DurationFormatUtils.formatDuration(maxIntPlus, "S"));
   assertEquals(
       Long.toString(Long.MAX_VALUE), DurationFormatUtils.formatDuration(Long.MAX_VALUE, "S"));
 }
Example #16
0
  @Test
  public void subBufferTest01ByteBuffer() {

    out.println(" - - - subBufferTest - - - ");

    @SuppressWarnings("unchecked")
    final CLPlatform platform = CLPlatform.getDefault(version(CL_1_1));
    if (platform == null) {
      out.println("aborting subBufferTest");
      return;
    }

    final CLContext context = CLContext.create(platform);
    try {
      final int subelements = 5;
      final long lMaxAlignment = context.getMaxMemBaseAddrAlign();
      final int iMaxAlignment = Bitstream.uint32LongToInt(lMaxAlignment);
      System.err.println(
          "XXX: maxAlignment "
              + lMaxAlignment
              + ", 0x"
              + Long.toHexString(lMaxAlignment)
              + ", (int)"
              + iMaxAlignment
              + ", (int)0x"
              + Integer.toHexString(iMaxAlignment));
      if (-1 == iMaxAlignment) {
        throw new RuntimeException(
            "Cannot handle MaxMemBaseAddrAlign > MAX_INT, has 0x"
                + Long.toHexString(lMaxAlignment));
      }
      // device only
      final CLBuffer<?> buffer = context.createBuffer(iMaxAlignment + subelements);

      assertFalse(buffer.isSubBuffer());
      assertNotNull(buffer.getSubBuffers());
      assertTrue(buffer.getSubBuffers().isEmpty());

      final CLSubBuffer<?> subBuffer = buffer.createSubBuffer(iMaxAlignment, subelements);

      assertTrue(subBuffer.isSubBuffer());
      assertEquals(subelements, subBuffer.getCLSize());
      assertEquals(iMaxAlignment, subBuffer.getOffset());
      assertEquals(iMaxAlignment, subBuffer.getCLOffset());
      assertEquals(buffer, subBuffer.getParent());
      assertEquals(1, buffer.getSubBuffers().size());

      subBuffer.release();
      assertEquals(0, buffer.getSubBuffers().size());
    } finally {
      context.release();
    }
  }
Example #17
0
  /**
   * The <body/> element of every client request MUST possess a sequential request ID encapsulated
   * via the 'rid' attribute.
   *
   * @param node node to validate
   * @param previous previous node
   */
  private void assertRequestIDSequential(final Node node, final Node previous) {
    String ridStr = node.getBody().getAttribute(Attributes.RID);
    assertNotNull("Request ID attribute not present", ridStr);

    long rid = Long.parseLong(ridStr);
    if (previous != null) {
      String prevRidStr = previous.getBody().getAttribute(Attributes.RID);
      assertNotNull("Previous request ID attribute not present", prevRidStr);
      long prevRid = Long.parseLong(prevRidStr);
      assertEquals("Request ID is not sequential", prevRid + 1, rid);
    }
  }
 /**
  * Test method for {@link
  * org.jhove2.persist.berkeleydpl.BerkeleyDbBaseModuleAccessor#persistModule(org.jhove2.module.Module)}.
  */
 @Test
 public void testPersistModule() {
   Long oldId = bdbUTF8Module.getModuleId();
   try {
     bdbUTF8Module = (UTF8Module) bdbUTF8Module.getModuleAccessor().persistModule(bdbUTF8Module);
     assertEquals(oldId.longValue(), bdbUTF8Module.getModuleId().longValue());
     BerkeleyDbBaseModuleAccessor ma =
         (BerkeleyDbBaseModuleAccessor) bdbUTF8Module.getModuleAccessor();
     bdbUTF8Module = (UTF8Module) ma.retrieveModule(bdbUTF8Module.getModuleId());
     assertEquals(oldId.longValue(), bdbUTF8Module.getModuleId().longValue());
   } catch (JHOVE2Exception e) {
     e.printStackTrace();
     fail(e.getMessage());
   }
 }
  @Test
  public void testCloseSessionByNormalUser() throws Exception {
    String sessionIdString = "555";
    String actionString = Action.CloseSession.toString();
    long sessionIdLong = Long.parseLong(sessionIdString);
    when(mockHttpServletRequest.getParameter(ServletUtil.ACTION)).thenReturn(actionString);
    when(mockHttpServletRequest.getParameter(ServletUtil.SESSION_ID)).thenReturn(sessionIdString);

    // set AuthenticateOneTimeUser false
    prepareEnterAuthenticateOneTimeUser(false);
    User user = stubbingCheckUser();

    UsersCache userCacheHelper = mock(UsersCache.class);
    mockStatic(UsersCacheFactory.class);
    when(UsersCacheFactory.getInstance()).thenReturn(userCacheHelper);
    doNothing().when(userCacheHelper);
    userCacheHelper.remove(sessionIdLong);

    // RUN...
    defaultConnectionStrategy.execute(mockHttpServletRequest, mockHttpServletResponse);

    verifyNecessaryChecks(actionString);

    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.checkUser(loginString, password, false);

    PrintWriter writer = mockHttpServletResponse.getWriter();
    writer.flush();
    System.out.println(outStringWriter.toString());
    // ASSERT...
    assertThat(outStringWriter.toString(), is("RESPONSE:" + String.valueOf(sessionIdLong)));
  }
 @Test
 public void testCompareLongGTEDecimal() throws Exception {
   long ts = nextTimestamp();
   initTableValues(null, ts);
   String query = "SELECT l FROM LongInKeyTest where l >= 1.5";
   Properties props = new Properties();
   props.setProperty(
       PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 2
   Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
   try {
     PreparedStatement statement = conn.prepareStatement(query);
     ResultSet rs = statement.executeQuery();
     /*
      *  Failing because we're not converting the constant to the type of the RHS
      *  when forming the start/stop key.
      *  For this case, 1.5 -> 1L
      *  if where l < 1.5 then 1.5 -> 1L and then to 2L because it's not inclusive
      *
      */
     assertTrue(rs.next());
     assertEquals(2, rs.getLong(1));
     assertFalse(rs.next());
   } finally {
     conn.close();
   }
 }
Example #21
0
 @Test
 public void testQueryForLong() throws Exception {
   String tableName = "testHiveDriverTable";
   assertEquals(
       Long.valueOf(0),
       hiveTemplate.queryForLong("select count(1) as cnt from " + tableName + ";"));
 }
Example #22
0
 @Test
 public void testScanUri() throws Exception {
   GroupByCaseTest gbt = new GroupByCaseTest();
   long ts = gbt.createTable();
   gbt.loadData(ts);
   Properties props = new Properties(TEST_PROPERTIES);
   props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1));
   Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
   Statement stmt = conn.createStatement();
   ResultSet rs = stmt.executeQuery("select uri from " + GROUPBYTEST_NAME);
   assertTrue(rs.next());
   assertEquals("Report1", rs.getString(1));
   assertTrue(rs.next());
   assertEquals("Report2", rs.getString(1));
   assertTrue(rs.next());
   assertEquals("Report3", rs.getString(1));
   assertTrue(rs.next());
   assertEquals("Report4", rs.getString(1));
   assertTrue(rs.next());
   assertEquals("SOQL1", rs.getString(1));
   assertTrue(rs.next());
   assertEquals("SOQL2", rs.getString(1));
   assertTrue(rs.next());
   assertEquals("SOQL3", rs.getString(1));
   assertTrue(rs.next());
   assertEquals("SOQL4", rs.getString(1));
   assertFalse(rs.next());
   conn.close();
 }
    @Override
    public void initialize() throws EventHubException {
      if (curInitFaults < initFaultCount) {
        curInitFaults++;
        isFault = true;
        throw new EventHubException("Simulate fault in initialize()");
      }

      // after recovery, forget all the faults
      initFaultCount = 0;
      curInitFaults = 0;
      receiveFaultOffset = -1;
      isFault = false;
      isReceiveNull = false;
      curOffset = -1;

      if (lastMessage != null) {
        String tmpOffset = EventHubMessage.parseAmqpMessage(lastMessage).getOffset();
        // make sure filter is updated
        EventHubOffsetFilter tmpFilter = new EventHubOffsetFilter(tmpOffset);
        assertEquals(filter.getFilterString(), tmpFilter.getFilterString());
        // update curOffset
        curOffset = Long.parseLong(tmpOffset);
      }
    }
Example #24
0
  /**
   * Assert that getSplitEditFilesSorted returns files in expected order and that it skips
   * moved-aside files.
   *
   * @throws IOException
   */
  @Test
  public void testGetSplitEditFilesSorted() throws IOException {
    FileSystem fs = FileSystem.get(util.getConfiguration());
    Path regiondir = util.getDataTestDir("regiondir");
    fs.delete(regiondir, true);
    fs.mkdirs(regiondir);
    Path recoverededits = WALSplitter.getRegionDirRecoveredEditsDir(regiondir);
    String first = WALSplitter.formatRecoveredEditsFileName(-1);
    createFile(fs, recoverededits, first);
    createFile(fs, recoverededits, WALSplitter.formatRecoveredEditsFileName(0));
    createFile(fs, recoverededits, WALSplitter.formatRecoveredEditsFileName(1));
    createFile(fs, recoverededits, WALSplitter.formatRecoveredEditsFileName(11));
    createFile(fs, recoverededits, WALSplitter.formatRecoveredEditsFileName(2));
    createFile(fs, recoverededits, WALSplitter.formatRecoveredEditsFileName(50));
    String last = WALSplitter.formatRecoveredEditsFileName(Long.MAX_VALUE);
    createFile(fs, recoverededits, last);
    createFile(
        fs, recoverededits, Long.toString(Long.MAX_VALUE) + "." + System.currentTimeMillis());

    final Configuration walConf = new Configuration(util.getConfiguration());
    FSUtils.setRootDir(walConf, regiondir);
    (new WALFactory(walConf, null, "dummyLogName")).getWAL(new byte[] {}, null);

    NavigableSet<Path> files = WALSplitter.getSplitEditFilesSorted(fs, regiondir);
    assertEquals(7, files.size());
    assertEquals(files.pollFirst().getName(), first);
    assertEquals(files.pollLast().getName(), last);
    assertEquals(files.pollFirst().getName(), WALSplitter.formatRecoveredEditsFileName(0));
    assertEquals(files.pollFirst().getName(), WALSplitter.formatRecoveredEditsFileName(1));
    assertEquals(files.pollFirst().getName(), WALSplitter.formatRecoveredEditsFileName(2));
    assertEquals(files.pollFirst().getName(), WALSplitter.formatRecoveredEditsFileName(11));
  }
Example #25
0
  private Script parseScriptString(String string) throws Exception {
    String[] words = string.split("[ \\t\\n]");

    UnsafeByteArrayOutputStream out = new UnsafeByteArrayOutputStream();

    for (String w : words) {
      if (w.equals("")) continue;
      if (w.matches("^-?[0-9]*$")) {
        // Number
        long val = Long.parseLong(w);
        if (val >= -1 && val <= 16) out.write(Script.encodeToOpN((int) val));
        else
          Script.writeBytes(
              out, Utils.reverseBytes(Utils.encodeMPI(BigInteger.valueOf(val), false)));
      } else if (w.matches("^0x[0-9a-fA-F]*$")) {
        // Raw hex data, inserted NOT pushed onto stack:
        out.write(Hex.decode(w.substring(2)));
      } else if (w.length() >= 2 && w.startsWith("'") && w.endsWith("'")) {
        // Single-quoted string, pushed as data. NOTE: this is poor-man's
        // parsing, spaces/tabs/newlines in single-quoted strings won't work.
        Script.writeBytes(out, w.substring(1, w.length() - 1).getBytes(Charset.forName("UTF-8")));
      } else if (ScriptOpCodes.getOpCode(w) != OP_INVALIDOPCODE) {
        // opcode, e.g. OP_ADD or OP_1:
        out.write(ScriptOpCodes.getOpCode(w));
      } else if (w.startsWith("OP_")
          && ScriptOpCodes.getOpCode(w.substring(3)) != OP_INVALIDOPCODE) {
        // opcode, e.g. OP_ADD or OP_1:
        out.write(ScriptOpCodes.getOpCode(w.substring(3)));
      } else {
        throw new RuntimeException("Invalid Data");
      }
    }

    return new Script(out.toByteArray());
  }
Example #26
0
  @Test
  public void parallelDeserialization() throws InterruptedException {
    DataOutput out = serialize.getDataOutput(128, true);
    out.putLong(8);
    out.writeClassAndObject(Long.valueOf(8));
    TestClass c = new TestClass(5, 8, new short[] {1, 2, 3, 4, 5}, TestEnum.Two);
    out.writeObject(c, TestClass.class);
    final StaticBuffer b = out.getStaticBuffer();

    int numThreads = 100;
    Thread[] threads = new Thread[numThreads];
    for (int i = 0; i < numThreads; i++) {
      threads[i] =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  for (int j = 0; j < 100000; j++) {
                    ReadBuffer c = b.asReadBuffer();
                    assertEquals(8, c.getLong());
                    Long l = (Long) serialize.readClassAndObject(c);
                    assertEquals(8, l.longValue());
                    TestClass c2 = serialize.readObjectNotNull(c, TestClass.class);
                  }
                }
              });
      threads[i].start();
    }
    for (int i = 0; i < numThreads; i++) {
      threads[i].join();
    }
  }
 @Test
 public void testParseHexOrDefaultOk() throws Exception {
   long i = 0x12;
   String s = "0x" + Long.toHexString(i);
   int def = 14;
   assertEquals(i, ParseLong.parseHexOrDefault(s, def));
 }
  @Before
  public void setUp() throws Exception {
    try {
      FileReader reader = new FileReader("inventory.txt");
      BufferedReader br = new BufferedReader(reader);

      String row = br.readLine();
      while (row != null) {
        String articleinfo[] = row.split(":");

        char barcode[] = articleinfo[0].toCharArray();
        String name = articleinfo[1];
        int amount = Integer.parseInt(articleinfo[2]);
        double price = Double.parseDouble(articleinfo[3]);
        boolean food = Boolean.parseBoolean(articleinfo[4]);

        tempInventory.add(new cashRegisterSystem.inventoryArticle(barcode, name, amount, price));
        row = br.readLine();
      }

      br.close();
    } catch (IOException e) {
      System.out.println("Error" + e.getMessage());
      System.out.println("Error reading File");
    }

    CRS.newItem(Long.parseLong(sBarcode), sArticleName, dPrice, iAmountInventory, isFood);
    CRS.writeInventory();
  }
  @Test
  public void setMultiplierNegative() {
    Product product = new Product("test", "Test Product", owner);
    product.setMultiplier(-15L);

    assertEquals(Long.valueOf(1), product.getMultiplier());
  }
  @Test
  public void setMultiplierBasic() {
    Product product = new Product("test", "Test Product", owner);
    product.setMultiplier(4L);

    assertEquals(Long.valueOf(4), product.getMultiplier());
  }