@Test
  public void testDDLExport() throws Exception {
    String vdbName = "test";
    String testVDB =
        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<vdb name=\"test\" version=\"1\">\n"
            + "    <property name=\"UseConnectorMetadata\" value=\"cached\" />\n"
            + "    <model name=\"loopy\">\n"
            + "        <source name=\"loop\" translator-name=\"loopy\" />\n"
            + "    </model>\n"
            + "</vdb>";

    Collection<?> vdbs = admin.getVDBs();
    assertTrue(vdbs.isEmpty());

    JavaArchive jar = getLoopyArchive();
    admin.deploy("loopy.jar", jar.as(ZipExporter.class).exportAsInputStream());

    // normal load
    admin.deploy("test-vdb.xml", new ByteArrayInputStream(testVDB.getBytes()));
    AdminUtil.waitForVDBLoad(admin, vdbName, 1, 3);

    String ddl = admin.getSchema(vdbName, 1, "loopy", null, null);

    String expected = "CREATE FOREIGN TABLE Matadata (\n" + "	execCount integer\n" + ");";
    assertEquals(expected, ddl);

    admin.undeploy("loopy.jar");
  }
    @Override
    void perform() throws IOException {
      NamespaceDescriptor selected = selectNamespace(namespaceMap);
      if (selected == null) {
        return;
      }

      Admin admin = connection.getAdmin();
      try {
        String namespaceName = selected.getName();
        LOG.info("Deleting namespace :" + selected);
        admin.deleteNamespace(namespaceName);
        try {
          if (admin.getNamespaceDescriptor(namespaceName) != null) {
            // the namespace still exists.
            Assert.assertTrue("Namespace: " + selected + " was not deleted", false);
          } else {
            LOG.info("Deleted namespace :" + selected);
          }
        } catch (NamespaceNotFoundException nsnfe) {
          // This is expected result
          LOG.info("Deleted namespace :" + selected);
        }
      } catch (Exception e) {
        LOG.warn("Caught exception in action: " + this.getClass());
        throw e;
      } finally {
        admin.close();
      }
      verifyNamespaces();
    }
    @Override
    void perform() throws IOException {
      NamespaceDescriptor selected = selectNamespace(namespaceMap);
      if (selected == null) {
        return;
      }

      Admin admin = connection.getAdmin();
      try {
        String namespaceName = selected.getName();
        LOG.info("Modifying namespace :" + selected);
        NamespaceDescriptor modifiedNsd = NamespaceDescriptor.create(namespaceName).build();
        String nsValueNew;
        do {
          nsValueNew = String.format("%010d", RandomUtils.nextInt(Integer.MAX_VALUE));
        } while (selected.getConfigurationValue(nsTestConfigKey).equals(nsValueNew));
        modifiedNsd.setConfiguration(nsTestConfigKey, nsValueNew);
        admin.modifyNamespace(modifiedNsd);
        NamespaceDescriptor freshNamespaceDesc = admin.getNamespaceDescriptor(namespaceName);
        Assert.assertTrue(
            "Namespace: " + selected + " was not modified",
            freshNamespaceDesc.getConfigurationValue(nsTestConfigKey).equals(nsValueNew));
        LOG.info("Modified namespace :" + freshNamespaceDesc);
        namespaceMap.put(namespaceName, freshNamespaceDesc);
      } catch (Exception e) {
        LOG.warn("Caught exception in action: " + this.getClass());
        throw e;
      } finally {
        admin.close();
      }
      verifyNamespaces();
    }
    @Override
    void perform() throws IOException {
      HTableDescriptor selected = selectTable(disabledTables);
      if (selected == null) {
        return;
      }

      Admin admin = connection.getAdmin();
      try {
        HColumnDescriptor cfd = createFamilyDesc();
        if (selected.hasFamily(cfd.getName())) {
          LOG.info(
              new String(cfd.getName()) + " already exists in table " + selected.getTableName());
          return;
        }
        TableName tableName = selected.getTableName();
        LOG.info("Adding column family: " + cfd + " to table: " + tableName);
        admin.addColumn(tableName, cfd);
        // assertion
        HTableDescriptor freshTableDesc = admin.getTableDescriptor(tableName);
        Assert.assertTrue(
            "Column family: " + cfd + " was not added", freshTableDesc.hasFamily(cfd.getName()));
        LOG.info("Added column family: " + cfd + " to table: " + tableName);
        disabledTables.put(tableName, freshTableDesc);
      } catch (Exception e) {
        LOG.warn("Caught exception in action: " + this.getClass());
        throw e;
      } finally {
        admin.close();
      }
      verifyTables();
    }
    @Override
    void perform() throws IOException {
      HTableDescriptor selected = selectTable(disabledTables);
      HColumnDescriptor cfd = selectFamily(selected);
      if (selected == null || cfd == null) {
        return;
      }

      Admin admin = connection.getAdmin();
      try {
        if (selected.getColumnFamilies().length < 2) {
          LOG.info("No enough column families to delete in table " + selected.getTableName());
          return;
        }
        TableName tableName = selected.getTableName();
        LOG.info("Deleting column family: " + cfd + " from table: " + tableName);
        admin.deleteColumnFamily(tableName, cfd.getName());
        // assertion
        HTableDescriptor freshTableDesc = admin.getTableDescriptor(tableName);
        Assert.assertFalse(
            "Column family: " + cfd + " was not added", freshTableDesc.hasFamily(cfd.getName()));
        LOG.info("Deleted column family: " + cfd + " from table: " + tableName);
        disabledTables.put(tableName, freshTableDesc);
      } catch (Exception e) {
        LOG.warn("Caught exception in action: " + this.getClass());
        throw e;
      } finally {
        admin.close();
      }
      verifyTables();
    }
  public static void authenticate(String username, String password) {
    Logger.info("Attempting to authenticate with " + username + ":" + password);
    Admin admin = Admin.findByUsername(username);
    if ((admin != null) && (admin.checkPassword(password) == true)) {
      Logger.info("Successfull authentication of " + admin.username);

      /**
       * wanted to put an extra value in session - logged_in_adminid to distinguish an admin, as a
       * user could be logged in and type the route for admin URLs and get into the restricted
       * access areas. By putting a new value in session, it can only be set if an admin is logged
       * in.
       */
      session.put("logged_in_adminid", admin.id);

      /**
       * if login successful, communicate back to AJAX call in adminlogin.js and that will handle
       * the next screen
       */
      JSONObject obj = new JSONObject();
      String value = "correct";
      obj.put("inputdata", value);
      renderJSON(obj);

    } else {
      /**
       * if login unsuccessful, communicate back to AJAX call in adminlogin.js and that will
       * redisplay login.html with error
       */
      Logger.info("Authentication failed");
      JSONObject obj = new JSONObject();
      String value = "Error: Incorrect Email/Password entered.";
      obj.put("inputdata", value);
      renderJSON(obj);
    }
  }
  public void testGetDatasourceProperties() throws Exception {
    Properties props = new Properties();
    props.setProperty("connection-url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    props.setProperty("user-name", "sa");
    props.setProperty("password", "sa");
    props.setProperty("connection-properties", "foo=bar,blah=blah");
    props.setProperty("max-pool-size", "4");

    admin.createDataSource("Oracle11_PushDS", "h2", props);

    Properties p = admin.getDataSource("Oracle11_PushDS");
    assertEquals("4", p.getProperty("max-pool-size"));
    assertEquals("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", p.getProperty("connection-url"));

    admin.deleteDataSource("Oracle11_PushDS");

    p = new Properties();
    p.setProperty("class-name", "org.teiid.resource.adapter.ws.WSManagedConnectionFactory");
    p.setProperty("EndPoint", "{endpoint}");
    props.setProperty("max-pool-size", "4");
    admin.createDataSource("nowhere", "teiid-connector-ws.rar", p);

    assertEquals(
        "org.teiid.resource.adapter.ws.WSManagedConnectionFactory", p.getProperty("class-name"));
    assertEquals("4", p.getProperty("max-pool-size"));
    assertEquals("{endpoint}", p.getProperty("EndPoint"));

    admin.deleteDataSource("nowhere");
  }
  private static void createTable() throws Exception {
    try {
      Configuration configuration = HBaseConfiguration.create();
      HBaseAdmin.checkHBaseAvailable(configuration);
      Connection connection = ConnectionFactory.createConnection(configuration);

      // Instantiating HbaseAdmin class
      Admin admin = connection.getAdmin();

      // Instantiating table descriptor class
      HTableDescriptor stockTableDesc =
          new HTableDescriptor(TableName.valueOf(Constants.STOCK_DATES_TABLE));

      // Adding column families to table descriptor
      HColumnDescriptor stock_0414 = new HColumnDescriptor(Constants.STOCK_DATES_CF);
      stockTableDesc.addFamily(stock_0414);

      // Execute the table through admin
      if (!admin.tableExists(stockTableDesc.getTableName())) {
        admin.createTable(stockTableDesc);
        System.out.println("Stock table created !!!");
      }

      // Load hbase-site.xml
      HBaseConfiguration.addHbaseResources(configuration);
    } catch (ServiceException e) {
      log.error("Error occurred while creating HBase tables", e);
      throw new Exception("Error occurred while creating HBase tables", e);
    }
  }
  @Test
  public void getTemplatePropertyDefinitions() throws Exception {
    HashSet<String> props = new HashSet<String>();

    deployVdb();

    Collection<? extends PropertyDefinition> pds = admin.getTemplatePropertyDefinitions("h2");
    for (PropertyDefinition pd : pds) {
      props.add(pd.getName());
    }
    assertTrue(props.contains("connection-url"));
    assertTrue(props.contains("user-name"));
    assertTrue(props.contains("password"));
    assertTrue(props.contains("check-valid-connection-sql"));
    assertTrue(props.contains("max-pool-size"));
    assertTrue(props.contains("connection-properties"));
    assertTrue(props.contains("max-pool-size"));

    HashSet<String> rar_props = new HashSet<String>();
    pds = admin.getTemplatePropertyDefinitions("file");
    for (PropertyDefinition pd : pds) {
      rar_props.add(pd.getName());
    }

    assertTrue(rar_props.contains("ParentDirectory"));
    assertTrue(rar_props.contains("FileMapping"));
    assertTrue(rar_props.contains("AllowParentPaths"));
    assertTrue(rar_props.contains("resourceadapter-class"));
    assertTrue(rar_props.contains("managedconnectionfactory-class"));
    assertTrue(rar_props.contains("max-pool-size"));
  }
Exemplo n.º 10
0
  @Test(timeout = 120000)
  public void testChangeTable() throws Exception {
    HTableDescriptor hdt = HTU.createTableDescriptor("testChangeTable");
    hdt.setRegionReplication(NB_SERVERS);
    hdt.addCoprocessor(SlowMeCopro.class.getName());
    Table table = HTU.createTable(hdt, new byte[][] {f}, HTU.getConfiguration());

    // basic test: it should work.
    Put p = new Put(row);
    p.add(f, row, row);
    table.put(p);

    Get g = new Get(row);
    Result r = table.get(g);
    Assert.assertFalse(r.isStale());

    // Add a CF, it should work.
    HTableDescriptor bHdt = HTU.getHBaseAdmin().getTableDescriptor(hdt.getTableName());
    HColumnDescriptor hcd = new HColumnDescriptor(row);
    hdt.addFamily(hcd);
    HTU.getHBaseAdmin().disableTable(hdt.getTableName());
    HTU.getHBaseAdmin().modifyTable(hdt.getTableName(), hdt);
    HTU.getHBaseAdmin().enableTable(hdt.getTableName());
    HTableDescriptor nHdt = HTU.getHBaseAdmin().getTableDescriptor(hdt.getTableName());
    Assert.assertEquals(
        "fams=" + Arrays.toString(nHdt.getColumnFamilies()),
        bHdt.getColumnFamilies().length + 1,
        nHdt.getColumnFamilies().length);

    p = new Put(row);
    p.add(row, row, row);
    table.put(p);

    g = new Get(row);
    r = table.get(g);
    Assert.assertFalse(r.isStale());

    try {
      SlowMeCopro.cdl.set(new CountDownLatch(1));
      g = new Get(row);
      g.setConsistency(Consistency.TIMELINE);
      r = table.get(g);
      Assert.assertTrue(r.isStale());
    } finally {
      SlowMeCopro.cdl.get().countDown();
      SlowMeCopro.sleepTime.set(0);
    }

    Admin admin = HTU.getHBaseAdmin();
    nHdt = admin.getTableDescriptor(hdt.getTableName());
    Assert.assertEquals(
        "fams=" + Arrays.toString(nHdt.getColumnFamilies()),
        bHdt.getColumnFamilies().length + 1,
        nHdt.getColumnFamilies().length);

    admin.disableTable(hdt.getTableName());
    admin.deleteTable(hdt.getTableName());
    admin.close();
  }
 public static Admin validateCredentials(RequestContext request) {
   String username = request.getRequestUsername();
   Admin admin = AdminMapper.retrieveAdmin(username);
   if (admin != null && admin.getPassword().equals(request.getRequestPassword())) {
     return admin;
   } else {
     return null;
   }
 }
Exemplo n.º 12
0
 public boolean tableExists(String tableName) {
   try {
     Admin admin = connection.getAdmin();
     return admin.tableExists(TableName.valueOf(tableName));
   } catch (IOException e) {
     e.printStackTrace();
   }
   return false;
 }
Exemplo n.º 13
0
 public void testXQuery() throws RemoteException {
   admin.removeCollection(sessionId, testColl);
   admin.createCollection(sessionId, testColl);
   String data =
       "<test>"
           + "  <fruit name='apple'/>"
           + "  <fruit name='orange'/>"
           + "  <fruit name='pear'/>"
           + "  <fruit name='grape'/>"
           + "  <fruit name='banana'/>"
           + "  <fruit name='mango'/>"
           + "</test>";
   String data1 =
       "<test>"
           + "  <fruit name='guava'/>"
           + "  <fruit name='quince'/>"
           + "  <fruit name='pineapple'/>"
           + "  <fruit name='mandarine'/>"
           + "  <fruit name='persimmon'/>"
           + "  <fruit name='pomegranate'/>"
           + "</test>";
   System.out.println("====> Creating test documents");
   admin.store(sessionId, data.getBytes(), "UTF-8", testColl + "/docA", true);
   admin.store(sessionId, data1.getBytes(), "UTF-8", testColl + "/docB", true);
   System.out.println("====> getResource");
   String rd = query.getResource(sessionId, testColl + "/docA", true, false);
   System.out.println(rd);
   System.out.println("====> listCollection");
   Collection coll = query.listCollection(sessionId, testColl);
   String[] colls = coll.getCollections().getElements();
   if (colls != null)
     for (int i = 0; i < colls.length; i++) {
       System.out.println("  collection " + colls[i]);
     }
   String[] ress = coll.getResources().getElements();
   assertEquals(ress.length, 2);
   if (ress != null)
     for (int i = 0; i < ress.length; i++) {
       System.out.println("  resources " + ress[i]);
     }
   System.out.println("====> getResourceData");
   byte[] rd1 = query.getResourceData(sessionId, testColl + "/docB", true, false, false);
   System.out.println(new String(rd1));
   System.out.println("====> performing xquery with retrieve");
   String qry = "for $a in collection('" + testColl + "')/test/fruit return $a";
   assertEquals(doXQuery(qry), 12);
   System.out.println("====> performing xquery with retrieveData");
   assertEquals(doXQueryB(qry), 12);
   System.out.println("====> performing xquery with retrieveByDocument");
   assertEquals(doXQueryC(qry), 6);
   System.out.println("====> performing xquery, expecting 0 hits");
   String qry1 = "for $a in collection('" + testColl + "')/test/nuts return $a";
   assertEquals(doXQuery(qry1), 0);
   String qry2 = "for $a in collection('" + testColl + "')/test/fruit[@name &= 'apple'] return $a";
   assertEquals(doXQuery(qry2), 1);
 }
Exemplo n.º 14
0
 public void createTable(String tableName, List<String> columnFamilies) {
   try {
     Admin admin = connection.getAdmin();
     HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(tableName));
     for (String family : columnFamilies) {
       descriptor.addFamily(new HColumnDescriptor(family));
     }
     admin.createTable(descriptor);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  private boolean deployVdb() throws AdminException, FileNotFoundException {
    boolean vdbOneDeployed;
    admin.deploy("bqt.vdb", new FileInputStream(UnitTestUtil.getTestDataFile("bqt.vdb")));
    AdminUtil.waitForVDBLoad(admin, "bqt", 1, 3);
    vdbOneDeployed = true;

    VDB vdb = admin.getVDB("bqt", 1);
    Model model = vdb.getModels().get(0);
    admin.assignToModel(
        "bqt", 1, model.getName(), "Source", "h2", "java:jboss/datasources/ExampleDS");
    return vdbOneDeployed;
  }
  @Test
  public void testErrorDeployment() throws Exception {
    Collection<?> vdbs = admin.getVDBs();
    assertTrue(vdbs.isEmpty());

    admin.deploy(
        "error-vdb.xml", new FileInputStream(UnitTestUtil.getTestDataFile("error-vdb.xml")));

    AdminUtil.waitForVDBLoad(admin, "error", 1, 3);
    VDB vdb = admin.getVDB("error", 1);
    assertEquals(Status.FAILED, vdb.getStatus());
  }
    @Override
    void perform() throws IOException {
      HTableDescriptor selected = selectTable(disabledTables);
      if (selected == null) {
        return;
      }
      HColumnDescriptor columnDesc = selectFamily(selected);
      if (columnDesc == null) {
        return;
      }

      Admin admin = connection.getAdmin();
      int versions = RandomUtils.nextInt(10) + 3;
      try {
        TableName tableName = selected.getTableName();
        LOG.info(
            "Altering versions of column family: "
                + columnDesc
                + " to: "
                + versions
                + " in table: "
                + tableName);
        columnDesc.setMinVersions(versions);
        columnDesc.setMaxVersions(versions);
        admin.modifyTable(tableName, selected);
        // assertion
        HTableDescriptor freshTableDesc = admin.getTableDescriptor(tableName);
        HColumnDescriptor freshColumnDesc = freshTableDesc.getFamily(columnDesc.getName());
        Assert.assertEquals(
            "Column family: " + columnDesc + " was not altered",
            freshColumnDesc.getMaxVersions(),
            versions);
        Assert.assertEquals(
            "Column family: " + freshColumnDesc + " was not altered",
            freshColumnDesc.getMinVersions(),
            versions);
        LOG.info(
            "Altered versions of column family: "
                + columnDesc
                + " to: "
                + versions
                + " in table: "
                + tableName);
        disabledTables.put(tableName, freshTableDesc);
      } catch (Exception e) {
        LOG.warn("Caught exception in action: " + this.getClass());
        throw e;
      } finally {
        admin.close();
      }
      verifyTables();
    }
Exemplo n.º 18
0
  final void init(Admin admin, String name, String password) {
    if (this.admin != null) {
      throw new IllegalStateException("already initialized");
    }
    this.admin = admin;
    this.name = name;
    this.userID = admin.loginAgentChannel(this, password);

    // Do not allow delivery of messages until correctly logged in
    // which is when this point has been reached.
    isClosed = false;

    admin.agentChannelAvailable(this);
  }
Exemplo n.º 19
0
 public boolean removeTable(String tableName) {
   try {
     Admin admin = connection.getAdmin();
     TableName t = TableName.valueOf(tableName);
     if (admin.tableExists(t)) {
       admin.disableTable(t);
       admin.deleteTable(t);
       return true;
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return false;
 }
    @Override
    void perform() throws IOException {
      HTableDescriptor selected = selectTable(disabledTables);
      if (selected == null) {
        return;
      }
      HColumnDescriptor columnDesc = selectFamily(selected);
      if (columnDesc == null) {
        return;
      }

      Admin admin = connection.getAdmin();
      try {
        TableName tableName = selected.getTableName();
        // possible DataBlockEncoding ids
        int[] possibleIds = {0, 2, 3, 4, 6};
        short id = (short) possibleIds[RandomUtils.nextInt(possibleIds.length)];
        LOG.info(
            "Altering encoding of column family: "
                + columnDesc
                + " to: "
                + id
                + " in table: "
                + tableName);
        columnDesc.setDataBlockEncoding(DataBlockEncoding.getEncodingById(id));
        admin.modifyTable(tableName, selected);
        // assertion
        HTableDescriptor freshTableDesc = admin.getTableDescriptor(tableName);
        HColumnDescriptor freshColumnDesc = freshTableDesc.getFamily(columnDesc.getName());
        Assert.assertEquals(
            "Encoding of column family: " + columnDesc + " was not altered",
            freshColumnDesc.getDataBlockEncoding().getId(),
            id);
        LOG.info(
            "Altered encoding of column family: "
                + freshColumnDesc
                + " to: "
                + id
                + " in table: "
                + tableName);
        disabledTables.put(tableName, freshTableDesc);
      } catch (Exception e) {
        LOG.warn("Caught exception in action: " + this.getClass());
        throw e;
      } finally {
        admin.close();
      }
      verifyTables();
    }
  @Test
  public void testDataRoleMapping() throws Exception {
    admin.deploy("bqt2.vdb", new FileInputStream(UnitTestUtil.getTestDataFile("bqt2.vdb")));

    VDB vdb = admin.getVDB("bqt", 2);
    Model model = vdb.getModels().get(0);
    admin.assignToModel(
        "bqt", 2, model.getName(), "Source", "h2", "java:jboss/datasources/ExampleDS");

    vdb = admin.getVDB("bqt", 2);
    assertTrue(vdb.isValid());
    List<DataPolicy> policies = vdb.getDataPolicies();
    assertEquals(1, policies.size());

    DataPolicy dp = policies.get(0);
    assertEquals("roleOne", dp.getName());
    assertEquals(2, dp.getPermissions().size());
    assertTrue(dp.isAllowCreateTemporaryTables());
    assertTrue(dp.isAnyAuthenticated());

    List<String> roleNames = dp.getMappedRoleNames();
    assertArrayEquals(new String[] {"ROLE1", "ROLE2"}, roleNames.toArray());

    admin.removeDataRoleMapping("bqt", 2, "roleOne", "ROLE1");

    vdb = admin.getVDB("bqt", 2);
    policies = vdb.getDataPolicies();
    dp = policies.get(0);

    roleNames = dp.getMappedRoleNames();
    assertArrayEquals(new String[] {"ROLE2"}, roleNames.toArray());

    admin.addDataRoleMapping("bqt", 2, "roleOne", "ROLE3");

    vdb = admin.getVDB("bqt", 2);
    policies = vdb.getDataPolicies();
    dp = policies.get(0);

    roleNames = dp.getMappedRoleNames();
    assertArrayEquals(new String[] {"ROLE2", "ROLE3"}, roleNames.toArray());

    admin.setAnyAuthenticatedForDataRole("bqt", 2, "roleOne", false);

    vdb = admin.getVDB("bqt", 2);
    policies = vdb.getDataPolicies();
    dp = policies.get(0);

    assertFalse(dp.isAnyAuthenticated());
  }
Exemplo n.º 22
0
 @Test(timeout = 300000)
 public void testTableAvailableWithRandomSplitKeys() throws Exception {
   TableName tableName = TableName.valueOf("testTableAvailableWithRandomSplitKeys");
   HTableDescriptor desc = new HTableDescriptor(tableName);
   desc.addFamily(new HColumnDescriptor("col"));
   byte[][] splitKeys = new byte[1][];
   splitKeys =
       new byte[][] {
         new byte[] {1, 1, 1},
         new byte[] {2, 2, 2}
       };
   admin.createTable(desc);
   boolean tableAvailable = admin.isTableAvailable(tableName, splitKeys);
   assertFalse("Table should be created with 1 row in META", tableAvailable);
 }
Exemplo n.º 23
0
  @Test(timeout = 300000)
  public void testCreateTableNumberOfRegions() throws IOException, InterruptedException {
    TableName tableName = TableName.valueOf("testCreateTableNumberOfRegions");
    HTableDescriptor desc = new HTableDescriptor(tableName);
    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    admin.createTable(desc);
    HTable ht = new HTable(TEST_UTIL.getConfiguration(), tableName);
    Map<HRegionInfo, ServerName> regions = ht.getRegionLocations();
    assertEquals("Table should have only 1 region", 1, regions.size());
    ht.close();

    TableName TABLE_2 = TableName.valueOf(tableName.getNameAsString() + "_2");
    desc = new HTableDescriptor(TABLE_2);
    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    admin.createTable(desc, new byte[][] {new byte[] {42}});
    HTable ht2 = new HTable(TEST_UTIL.getConfiguration(), TABLE_2);
    regions = ht2.getRegionLocations();
    assertEquals("Table should have only 2 region", 2, regions.size());
    ht2.close();

    TableName TABLE_3 = TableName.valueOf(tableName.getNameAsString() + "_3");
    desc = new HTableDescriptor(TABLE_3);
    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    admin.createTable(desc, "a".getBytes(), "z".getBytes(), 3);
    HTable ht3 = new HTable(TEST_UTIL.getConfiguration(), TABLE_3);
    regions = ht3.getRegionLocations();
    assertEquals("Table should have only 3 region", 3, regions.size());
    ht3.close();

    TableName TABLE_4 = TableName.valueOf(tableName.getNameAsString() + "_4");
    desc = new HTableDescriptor(TABLE_4);
    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    try {
      admin.createTable(desc, "a".getBytes(), "z".getBytes(), 2);
      fail("Should not be able to create a table with only 2 regions using this API.");
    } catch (IllegalArgumentException eae) {
      // Expected
    }

    TableName TABLE_5 = TableName.valueOf(tableName.getNameAsString() + "_5");
    desc = new HTableDescriptor(TABLE_5);
    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    admin.createTable(desc, new byte[] {1}, new byte[] {127}, 16);
    HTable ht5 = new HTable(TEST_UTIL.getConfiguration(), TABLE_5);
    regions = ht5.getRegionLocations();
    assertEquals("Table should have 16 region", 16, regions.size());
    ht5.close();
  }
  @Test
  public void testVDBConnectionType() throws Exception {
    admin.deploy("bqt.vdb", new FileInputStream(UnitTestUtil.getTestDataFile("bqt.vdb")));

    VDB vdb = admin.getVDB("bqt", 1);
    Model model = vdb.getModels().get(0);
    admin.updateSource("bqt", 1, "Source", "h2", "java:jboss/datasources/ExampleDS");

    try {
      // should not be able to remove from non-multisource
      admin.removeSource("bqt", 1, model.getName(), "Source");
      fail();
    } catch (AdminException e) {

    }

    assertEquals(ConnectionType.BY_VERSION, vdb.getConnectionType());

    Connection conn =
        TeiidDriver.getInstance()
            .connect("jdbc:teiid:bqt@mm://localhost:31000;user=user;password=user", null);
    conn.close();

    admin.changeVDBConnectionType("bqt", 1, ConnectionType.NONE);

    try {
      TeiidDriver.getInstance()
          .connect("jdbc:teiid:bqt@mm://localhost:31000;user=user;password=user", null);
      fail("should have failed to connect as no new connections allowed");
    } catch (Exception e) {
      // pass
    }

    admin.deploy("bqt2.vdb", new FileInputStream(UnitTestUtil.getTestDataFile("bqt2.vdb")));
    admin.updateSource("bqt", 2, "Source", "h2", "java:jboss/datasources/ExampleDS");

    conn =
        TeiidDriver.getInstance()
            .connect("jdbc:teiid:bqt@mm://localhost:31000;user=user;password=user", null);
    conn.close();

    admin.changeVDBConnectionType("bqt", 2, ConnectionType.ANY);
    conn =
        TeiidDriver.getInstance()
            .connect("jdbc:teiid:bqt@mm://localhost:31000;user=user;password=user", null);
    conn.close();

    vdb = admin.getVDB("bqt", 2);
    model = vdb.getModels().get(0);
    assertEquals(model.getSourceConnectionJndiName("Source"), "java:jboss/datasources/ExampleDS");
    assertEquals(model.getSourceTranslatorName("Source"), "h2");
    assertEquals(ConnectionType.ANY, vdb.getConnectionType());
  }
Exemplo n.º 25
0
  protected void deliverFromAgent(Message message) {
    // Deliver to admin or simulation (when simulation exists)
    String receiver = message.getReceiver();
    SimulationAgent proxy;
    if (isClosed) {
      // closed channel
    } else if (Admin.ADMIN.equals(receiver)) {
      Transportable content = message.getContent();
      if (message.getSender() == null) {
        message.setSender(name);
      }
      if ((content instanceof AdminContent)
          && (((AdminContent) content).getType() == AdminContent.QUIT)) {
        // Time to close this connection
        deliverToAgent(message.createReply(new AdminContent(AdminContent.QUIT)));
        close();

      } else {
        admin.deliverMessageFromAgent(this, message);
      }

    } else if ((proxy = this.proxy) != null) {
      proxy.deliverFromAgent(message);

    } else {
      // not a valid receiver because the agent is not in a game
    }
  }
 @Test
 public void getDatasourceTemplateNames() throws Exception {
   Set<String> vals =
       new HashSet<String>(
           Arrays.asList(
               new String[] {
                 "teiid-local",
                 "google",
                 "teiid",
                 "ldap",
                 "accumulo",
                 "infinispan",
                 "file",
                 "cassandra",
                 "salesforce",
                 "mongodb",
                 "solr",
                 "webservice",
                 "simpledb",
                 "h2"
               }));
   deployVdb();
   Set<String> templates = admin.getDataSourceTemplateNames();
   assertEquals(vals, templates);
 }
  @Test
  public void getTranslatorPropertyDefinitions() throws Exception {
    HashSet<String> props = new HashSet<String>();

    Collection<? extends PropertyDefinition> pds = admin.getTranslatorPropertyDefinitions("ws");
    for (PropertyDefinition pd : pds) {
      props.add(pd.getName());
    }
    assertTrue(props.contains("DefaultBinding"));
    assertTrue(props.contains("DefaultServiceMode"));
    assertTrue(props.contains("MaxDependentInPredicates"));

    for (PropertyDefinition pd : pds) {
      if (pd.getName().equals("DefaultBinding")) {
        assertEquals("java.lang.String", pd.getPropertyTypeClassName());
        assertFalse(pd.isRequired());
        assertEquals(
            "Contols what SOAP or HTTP type of invocation will be used if none is specified.",
            pd.getDescription());
        assertEquals("Default Binding", pd.getDisplayName());
        assertTrue(pd.isModifiable());
        assertFalse(pd.isAdvanced());
        assertFalse(pd.isMasked());
        assertEquals("SOAP12", pd.getDefaultValue());
        assertNotNull(pd.getAllowedValues());
      }
    }
  }
 protected void verifyNamespaces() throws IOException {
   Connection connection = getConnection();
   Admin admin = connection.getAdmin();
   // iterating concurrent map
   for (String nsName : namespaceMap.keySet()) {
     try {
       Assert.assertTrue(
           "Namespace: " + nsName + " in namespaceMap does not exist",
           admin.getNamespaceDescriptor(nsName) != null);
     } catch (NamespaceNotFoundException nsnfe) {
       Assert.fail(
           "Namespace: " + nsName + " in namespaceMap does not exist: " + nsnfe.getMessage());
     }
   }
   admin.close();
 }
  @Test
  public void testChainedDelegates() throws Exception {
    Properties props = new Properties();
    props.setProperty("connection-url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    props.setProperty("user-name", "sa");
    props.setProperty("password", "sa");

    AdminUtil.createDataSource(admin, "Oracle11_PushDS", "h2", props);
    admin.deploy("fake.jar", new FileInputStream(UnitTestUtil.getTestDataFile("fake.jar")));
    try {
      admin.deploy(
          "chained-vdb.xml", new FileInputStream(UnitTestUtil.getTestDataFile("chained-vdb.xml")));
    } finally {
      admin.undeploy("fake.jar");
    }
  }
  @Test
  public void testGetRequests() throws Exception {
    JavaArchive jar = getLoopyArchive();

    try {
      admin.deploy("loopy.jar", jar.as(ZipExporter.class).exportAsInputStream());
      deployVdb();
      Translator t = admin.getTranslator("loopy");
      assertNotNull(t);

      admin.updateSource("bqt", 1, "Source", "loopy", "java:jboss/datasources/ExampleDS");
      Connection conn =
          TeiidDriver.getInstance()
              .connect("jdbc:teiid:bqt@mm://localhost:31000;user=user;password=user", null);
      Collection<? extends Session> sessions = admin.getSessions();
      assertEquals(1, sessions.size());
      Session s = sessions.iterator().next();

      Statement stmt = conn.createStatement();

      Collection<? extends Request> requests = admin.getRequests();

      assertEquals(0, requests.size());

      stmt.execute("select * from source.smalla");

      requests = admin.getRequests();
      assertEquals(1, requests.size());

      Request r = requests.iterator().next();
      assertEquals("select * from source.smalla", r.getCommand());
      assertNotNull(r.getExecutionId());
      assertNotNull(r.getSessionId());

      stmt.execute("select * from source.smalla");
      Collection<? extends Request> requests2 = admin.getRequestsForSession(s.getSessionId());
      assertEquals(1, requests2.size());

      Request r2 = requests.iterator().next();
      assertEquals("select * from source.smalla", r2.getCommand());
      assertEquals(s.getSessionId(), r2.getSessionId());

      stmt.close();
      conn.close();

      requests = admin.getRequests();
      assertEquals(0, requests.size());

    } finally {
      admin.undeploy("loopy.jar");
    }
  }