Example usage for java.util Set toString

List of usage examples for java.util Set toString

Introduction

In this page you can find the example usage for java.util Set toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

@Test
public void testGrantCheckWithColumn() throws Exception {
    // 1. set local group mapping
    // user0->group0->role0
    // user1->group1->role1
    String grantor = "g1";
    String[] users = { "user0", "user1" };
    String[] roles = { "role0", "role1" };
    String[] groups = { "group0", "group1" };
    for (int i = 0; i < users.length; i++) {
        addGroupsToUser(users[i], groups[i]);
        sentryStore.createSentryRole(roles[i]);
        Set<TSentryGroup> tGroups = Sets.newHashSet();
        TSentryGroup tGroup = new TSentryGroup(groups[i]);
        tGroups.add(tGroup);/*from   w w  w.ja  va 2s.c  om*/
        sentryStore.alterSentryRoleAddGroups(grantor, roles[i], tGroups);
    }
    writePolicyFile();

    // 2. g1 grant select on table tb1 to role0, with grant option
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    String roleName = roles[0];
    grantor = "g1";
    TSentryPrivilege privilege1 = new TSentryPrivilege();
    privilege1.setPrivilegeScope("TABLE");
    privilege1.setServerName(server);
    privilege1.setDbName(db);
    privilege1.setTableName(table);
    privilege1.setAction(AccessConstants.SELECT);
    privilege1.setCreateTime(System.currentTimeMillis());
    privilege1.setGrantOption(TSentryGrantOption.TRUE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege1);
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());

    // 3. user0 grant select on column tb1.c1 to role1, with grant option
    roleName = roles[1];
    grantor = users[0];
    String column = "c1";
    TSentryPrivilege privilege2 = new TSentryPrivilege();
    privilege2.setPrivilegeScope("COLUMN");
    privilege2.setServerName(server);
    privilege2.setDbName(db);
    privilege2.setTableName(table);
    privilege2.setColumnName(column);
    privilege2.setAction(AccessConstants.SELECT);
    privilege2.setCreateTime(System.currentTimeMillis());
    privilege2.setGrantOption(TSentryGrantOption.TRUE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege2);

    // 4. user1 revoke table level privilege from user0, will throw grant denied exception
    roleName = roles[0];
    grantor = users[1];
    boolean isGrantOptionException = false;
    try {
        sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege1);
    } catch (SentryGrantDeniedException e) {
        isGrantOptionException = true;
        System.err.println(e.getMessage());
    }
    assertTrue(isGrantOptionException);

    // 5. user0 revoke column level privilege from user1
    roleName = roles[1];
    grantor = users[0];
    sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege2);
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(0, privileges.size());
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

/**
 * Regression test for SENTRY-552//from ww w  .  j a  v a  2  s  .co m
 */
@Test
public void testGrantRevokeTablePrivilegeDowngradeByDb() throws Exception {
    String roleName = "test-table-db-downgrade-privilege";
    String grantor = "g1";
    String server = "server1";
    String db = "db1";
    String table1 = "tbl1";
    String table2 = "tbl2";
    long seqId = sentryStore.createSentryRole(roleName).getSequenceId();
    TSentryPrivilege privilegeTable1 = new TSentryPrivilege();
    privilegeTable1.setPrivilegeScope("TABLE");
    privilegeTable1.setServerName(server);
    privilegeTable1.setDbName(db);
    privilegeTable1.setTableName(table1);
    privilegeTable1.setAction(AccessConstants.ALL);
    privilegeTable1.setCreateTime(System.currentTimeMillis());
    TSentryPrivilege privilegeTable2 = privilegeTable1.deepCopy();
    ;
    privilegeTable2.setTableName(table2);

    // Grant ALL on table1 and table2
    assertEquals(seqId + 1,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilegeTable1).getSequenceId());
    assertEquals(seqId + 2,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilegeTable2).getSequenceId());
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 2, privileges.size());

    // Revoke SELECT on table2
    privilegeTable2.setAction(AccessConstants.SELECT);
    assertEquals(seqId + 3,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilegeTable2).getSequenceId());
    // after having ALL and revoking SELECT, we should have INSERT
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 2, privileges.size());

    // At this point table1 has ALL privileges and table2 should have INSERT after revoking SELECT
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 2, privileges.size());
    for (MSentryPrivilege mPrivilege : privileges) {
        assertEquals(server, mPrivilege.getServerName());
        assertEquals(db, mPrivilege.getDbName());
        assertFalse(mPrivilege.getGrantOption());
        if (mPrivilege.getTableName().equals(table1)) {
            assertEquals(AccessConstants.ALL, mPrivilege.getAction());
        } else if (mPrivilege.getTableName().equals(table2)) {
            assertEquals(AccessConstants.INSERT, mPrivilege.getAction());
        } else {
            fail("Unexpected table name: " + mPrivilege.getTableName());
        }
    }

    // Revoke INSERT on Database
    privilegeTable2.setAction(AccessConstants.INSERT);
    privilegeTable2.setPrivilegeScope("DATABASE");
    privilegeTable2.unsetTableName();
    assertEquals(seqId + 4,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilegeTable2).getSequenceId());
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();

    // after revoking INSERT database level privilege will remove privileges from table2
    // and downgrade table1 to SELECT privileges.
    assertEquals(privileges.toString(), 1, privileges.size());
    MSentryPrivilege mPrivilege = Iterables.get(privileges, 0);
    assertEquals(server, mPrivilege.getServerName());
    assertEquals(db, mPrivilege.getDbName());
    assertEquals(table1, mPrivilege.getTableName());
    assertEquals(AccessConstants.SELECT, mPrivilege.getAction());
    assertFalse(mPrivilege.getGrantOption());
}

From source file:org.apache.lens.driver.jdbc.ColumnarSQLRewriter.java

/**
 * Builds the subqueries./*from ww w  .j  a va 2s  . co m*/
 *
 * @param node the node
 */
public void buildSubqueries(ASTNode node) {
    if (node == null) {
        log.debug("Join AST is null ");
        return;
    }

    String subquery = "";
    if (node.getToken().getType() == HiveParser.EQUAL) {
        if (node.getChild(0).getType() == HiveParser.DOT && node.getChild(1).getType() == HiveParser.DOT) {

            ASTNode left = (ASTNode) node.getChild(0);
            ASTNode right = (ASTNode) node.getChild(1);

            ASTNode parentNode = (ASTNode) node.getParent();

            // Skip the join conditions used as "and" while building subquery
            // eg. inner join fact.id1 = dim.id and fact.id2 = dim.id
            if (parentNode.getChild(0).getChild(0).getType() == HiveParser.DOT
                    && parentNode.getChild(0).getChild(1).getType() == HiveParser.DOT
                    && parentNode.getChild(1).getChild(0).getType() == HiveParser.DOT
                    && parentNode.getChild(1).getChild(1).getType() == HiveParser.DOT) {
                return;
            }

            // Get the fact and dimension columns in table_name.column_name format
            String factJoinKeys = HQLParser.getString(left).replaceAll("\\s+", "").replaceAll("[(,)]", "");
            String dimJoinKeys = HQLParser.getString(right).replaceAll("\\s+", "").replaceAll("[(,)]", "");
            int dimTableDelimIndex = dimJoinKeys.indexOf("__");
            String dimTableName = dimJoinKeys.substring(0, dimTableDelimIndex);
            String dimAlias = dimJoinKeys.substring(dimTableDelimIndex + 3, dimJoinKeys.indexOf('.')).trim();

            // Construct part of subquery by referring join condition
            // fact.fact_key = dim_table.dim_key
            // eg. "fact_key in ( select dim_key from dim_table where "
            String queryphase1 = factJoinKeys.concat(" in ").concat(" ( ").concat(" select ")
                    .concat(dimTableName).concat(" ")
                    .concat(dimJoinKeys.substring(dimJoinKeys.lastIndexOf("."))).concat(" from ")
                    .concat(dimTableName).concat(" where ");

            getAllFilters(whereAST);
            rightFilter.add(leftFilter);

            Set<String> setAllFilters = new LinkedHashSet<String>(rightFilter);

            // Check the occurrence of dimension table in the filter list and
            // combine all filters of same dimension table with and .
            // eg. "dim_table.key1 = 'abc' and dim_table.key2 = 'xyz'"
            if (setAllFilters.toString().replaceAll("\\s+", "").matches("(.*)" + dimAlias + "(.*)")) {

                factFilters.delete(0, factFilters.length());

                // All filters in where clause
                for (int i = 0; i < setAllFilters.toArray().length; i++) {

                    if (setAllFilters.toArray()[i].toString().replaceAll("\\s+", "")
                            .matches("(.*)" + dimAlias + ("(.*)"))) {
                        String filters2 = setAllFilters.toArray()[i].toString();
                        filters2 = filters2.replaceAll(getTableOrAlias(filters2, "alias"),
                                getTableOrAlias(filters2, "table")).concat(" and ");
                        factFilters.append(filters2);
                    }
                }
                // Merge fact subquery and dim subqury to construct the final subquery
                // eg. "fact_key in ( select dim_key from dim_table where
                // dim_table.key2 = 'abc' and dim_table.key3 = 'xyz'"
                subquery = queryphase1
                        .concat(factFilters.toString().substring(0, factFilters.toString().lastIndexOf("and")))
                        .concat(")");
                // include subqueries which are applicable only to filter records from fact
                if (subquery.matches("(.*)" + getFactAlias() + "(.*)")) {
                    allSubQueries.append(subquery).append(" and ");
                }
            }
        }
    }
    for (int i = 0; i < node.getChildCount(); i++) {
        ASTNode child = (ASTNode) node.getChild(i);
        buildSubqueries(child);
    }
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

/**
 * Regression test for SENTRY-74 and SENTRY-552
 *///ww  w .ja v a2s. c  om
@Test
public void testGrantRevokePrivilegeWithColumn() throws Exception {
    String roleName = "test-col-privilege";
    String grantor = "g1";
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    String column1 = "c1";
    String column2 = "c2";
    long seqId = sentryStore.createSentryRole(roleName).getSequenceId();
    TSentryPrivilege privilege = new TSentryPrivilege();
    privilege.setPrivilegeScope("COLUMN");
    privilege.setServerName(server);
    privilege.setDbName(db);
    privilege.setTableName(table);
    privilege.setColumnName(column1);
    privilege.setAction(AccessConstants.ALL);
    privilege.setCreateTime(System.currentTimeMillis());

    // Grant ALL on c1 and c2
    assertEquals(seqId + 1,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege).getSequenceId());
    privilege.setColumnName(column2);
    assertEquals(seqId + 2,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege).getSequenceId());
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 2, privileges.size());

    // Revoke SELECT on c2
    privilege.setAction(AccessConstants.SELECT);
    assertEquals(seqId + 3,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege).getSequenceId());

    // At this point c1 has ALL privileges and c2 should have INSERT after revoking SELECT
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 2, privileges.size());
    for (MSentryPrivilege mPrivilege : privileges) {
        assertEquals(server, mPrivilege.getServerName());
        assertEquals(db, mPrivilege.getDbName());
        assertEquals(table, mPrivilege.getTableName());
        assertFalse(mPrivilege.getGrantOption());
        if (mPrivilege.getColumnName().equals(column1)) {
            assertEquals(AccessConstants.ALL, mPrivilege.getAction());
        } else if (mPrivilege.getColumnName().equals(column2)) {
            assertEquals(AccessConstants.INSERT, mPrivilege.getAction());
        } else {
            fail("Unexpected column name: " + mPrivilege.getColumnName());
        }
    }

    // after revoking INSERT table level privilege will remove privileges from column2
    // and downgrade column1 to SELECT privileges.
    privilege = new TSentryPrivilege();
    privilege.setPrivilegeScope("TABLE");
    privilege.setServerName(server);
    privilege.setDbName(db);
    privilege.setTableName(table);
    privilege.setAction(AccessConstants.INSERT);
    privilege.setCreateTime(System.currentTimeMillis());
    assertEquals(seqId + 4,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege).getSequenceId());
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());
    assertEquals(column1, Iterables.get(privileges, 0).getColumnName());
    assertEquals(AccessConstants.SELECT, Iterables.get(privileges, 0).getAction());

    // Revoke ALL from the table should now remove all the column privileges.
    privilege.setAction(AccessConstants.ALL);
    privilege.setCreateTime(System.currentTimeMillis());
    assertEquals(seqId + 5,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege).getSequenceId());
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 0, privileges.size());
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

/**
 * Regression test for SENTRY-552/*from w  w w . ja v  a 2  s  .c  o m*/
 */
@Test
public void testGrantRevokeColumnPrivilegeDowngradeByDb() throws Exception {
    String roleName = "test-column-db-downgrade-privilege";
    String grantor = "g1";
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    String column1 = "c1";
    String column2 = "c2";
    long seqId = sentryStore.createSentryRole(roleName).getSequenceId();
    TSentryPrivilege privilegeCol1 = new TSentryPrivilege();
    privilegeCol1.setPrivilegeScope("COLUMN");
    privilegeCol1.setServerName(server);
    privilegeCol1.setDbName(db);
    privilegeCol1.setTableName(table);
    privilegeCol1.setColumnName(column1);
    privilegeCol1.setAction(AccessConstants.ALL);
    privilegeCol1.setCreateTime(System.currentTimeMillis());
    TSentryPrivilege privilegeCol2 = privilegeCol1.deepCopy();
    ;
    privilegeCol2.setColumnName(column2);

    // Grant ALL on column1 and column2
    assertEquals(seqId + 1,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilegeCol1).getSequenceId());
    assertEquals(seqId + 2,
            sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilegeCol2).getSequenceId());
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 2, privileges.size());

    // Revoke SELECT on column2
    privilegeCol2.setAction(AccessConstants.SELECT);
    assertEquals(seqId + 3,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilegeCol2).getSequenceId());
    // after having ALL and revoking SELECT, we should have INSERT
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 2, privileges.size());

    // At this point column1 has ALL privileges and column2 should have INSERT after revoking SELECT
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 2, privileges.size());
    for (MSentryPrivilege mPrivilege : privileges) {
        assertEquals(server, mPrivilege.getServerName());
        assertEquals(db, mPrivilege.getDbName());
        assertEquals(table, mPrivilege.getTableName());
        assertFalse(mPrivilege.getGrantOption());
        if (mPrivilege.getColumnName().equals(column1)) {
            assertEquals(AccessConstants.ALL, mPrivilege.getAction());
        } else if (mPrivilege.getColumnName().equals(column2)) {
            assertEquals(AccessConstants.INSERT, mPrivilege.getAction());
        } else {
            fail("Unexpected column name: " + mPrivilege.getColumnName());
        }
    }

    // Revoke INSERT on Database
    privilegeCol2.setAction(AccessConstants.INSERT);
    privilegeCol2.setPrivilegeScope("DATABASE");
    privilegeCol2.unsetTableName();
    privilegeCol2.unsetColumnName();
    assertEquals(seqId + 4,
            sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilegeCol2).getSequenceId());
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();

    // after revoking INSERT database level privilege will remove privileges from column2
    // and downgrade column1 to SELECT privileges.
    assertEquals(privileges.toString(), 1, privileges.size());
    MSentryPrivilege mPrivilege = Iterables.get(privileges, 0);
    assertEquals(server, mPrivilege.getServerName());
    assertEquals(db, mPrivilege.getDbName());
    assertEquals(table, mPrivilege.getTableName());
    assertEquals(column1, mPrivilege.getColumnName());
    assertEquals(AccessConstants.SELECT, mPrivilege.getAction());
    assertFalse(mPrivilege.getGrantOption());
}

From source file:fr.landel.utils.assertor.predicate.PredicateAssertorIterableTest.java

/**
 * Test method for {@link AssertorIterable#contains}.
 * //www.j a  va  2 s.c om
 * @throws IOException
 *             On contain
 */
@Test
public void testDoesNotContainIterable() throws IOException {
    final String el1 = "element1";
    final String el2 = "element2";

    final Set<String> set = new HashSet<>();
    final Set<String> set2 = new HashSet<>();
    set.add(el1);
    set2.add(el1);
    set2.add(el2);

    Assertor.<Set<String>, String>ofIterable().not().containsAll(set2).that(set)
            .orElseThrow("iterable contains the list %s*");
    Assertor.<Set<String>, String>ofIterable(EnumAnalysisMode.STREAM).not().containsAll(set2).that(set)
            .orElseThrow("iterable contains the list %s*");
    Assertor.<Set<String>, String>ofIterable(EnumAnalysisMode.PARALLEL).not().containsAll(set2).that(set)
            .orElseThrow("iterable contains the list %s*");

    set2.remove(el1);

    assertException(() -> {
        Assertor.<Set<String>, String>ofIterable().not().containsAll(set2).that(set)
                .orElseThrow("iterable contains the list %2$s*");
        fail(ERROR);
    }, IllegalArgumentException.class, "iterable contains the list " + set2.toString());

    assertException(() -> {
        Assertor.<Set<String>, String>ofIterable().not().containsAll(set2).that(set)
                .orElseThrow(new IOException(), true);
        fail(ERROR);
    }, IOException.class);

    assertException(() -> {
        Assertor.<Set<String>, String>ofIterable().not().containsAll((Iterable<String>) null).that(set)
                .orElseThrow();
        fail(ERROR);
    }, IllegalArgumentException.class, "neither iterables can be null or empty");

    assertFalse(Assertor.<Set<String>, String>ofIterable().not().containsAll(set2).that(set).isOK());
    assertFalse(Assertor.<Set<String>, String>ofIterable().not().containsAll(set).that(set).isOK());
    assertTrue(Assertor.<Set<String>, String>ofIterable().not().containsAny(set2).that(set).isOK());
    assertFalse(Assertor.<Set<String>, String>ofIterable().not().containsAny(set).that(set).isOK());

    set.clear();

    assertException(() -> {
        Assertor.<Iterable<String>, String>ofIterable().not().containsAll(set2).that((Iterable<String>) null)
                .orElseThrow();
        fail(ERROR);
    }, IllegalArgumentException.class, "neither iterables can be null or empty");

    assertException(() -> {
        Assertor.<Set<String>, String>ofIterable().not().containsAll((Iterable<String>) null).that(set)
                .orElseThrow();
        fail(ERROR);
    }, IllegalArgumentException.class, "neither iterables can be null or empty");

    assertFalse(Assertor.<Set<String>, String>ofIterable().not().containsAll(set2).that(set).isOK());
    assertFalse(Assertor.<Set<String>, String>ofIterable().not().containsAll(set).that(set).isOK());
    assertFalse(Assertor.<Set<String>, String>ofIterable().not().containsAny(set2).that(set).isOK());
    assertFalse(Assertor.<Set<String>, String>ofIterable().not().containsAny(set).that(set).isOK());
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

@Test
public void testRevokeCheckWithGrantOption() throws Exception {
    // 1. set local group mapping
    // user0->group0->role0
    // user1->group1->role1
    // user2->group2->role2
    String grantor = "g1";
    String[] users = { "user0", "user1", "user2" };
    String[] roles = { "role0", "role1", "role2" };
    String[] groups = { "group0", "group1", "group2" };
    for (int i = 0; i < users.length; i++) {
        addGroupsToUser(users[i], groups[i]);
        sentryStore.createSentryRole(roles[i]);
        Set<TSentryGroup> tGroups = Sets.newHashSet();
        TSentryGroup tGroup = new TSentryGroup(groups[i]);
        tGroups.add(tGroup);/*from   w w w .jav a 2  s.c  o m*/
        sentryStore.alterSentryRoleAddGroups(grantor, roles[i], tGroups);
    }
    writePolicyFile();

    // 2. g1 grant select on database db1 to role0, with grant option
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    String roleName = roles[0];
    grantor = "g1";
    TSentryPrivilege privilege1 = new TSentryPrivilege();
    privilege1.setPrivilegeScope("DATABASE");
    privilege1.setServerName(server);
    privilege1.setDbName(db);
    privilege1.setAction(AccessConstants.SELECT);
    privilege1.setCreateTime(System.currentTimeMillis());
    privilege1.setGrantOption(TSentryGrantOption.TRUE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege1);
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());

    // 3. g1 grant all on table tb1 to role1, no grant option
    roleName = roles[1];
    grantor = "g1";
    TSentryPrivilege privilege2 = new TSentryPrivilege();
    privilege2.setPrivilegeScope("TABLE");
    privilege2.setServerName(server);
    privilege2.setDbName(db);
    privilege2.setTableName(table);
    privilege2.setAction(AccessConstants.ALL);
    privilege2.setCreateTime(System.currentTimeMillis());
    privilege2.setGrantOption(TSentryGrantOption.FALSE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege2);

    // 4. g1 grant select on table tb1 to role2, no grant option
    roleName = roles[2];
    grantor = "g1";
    TSentryPrivilege privilege3 = new TSentryPrivilege();
    privilege3.setPrivilegeScope("TABLE");
    privilege3.setServerName(server);
    privilege3.setDbName(db);
    privilege3.setTableName(table);
    privilege3.setAction(AccessConstants.SELECT);
    privilege3.setCreateTime(System.currentTimeMillis());
    privilege3.setGrantOption(TSentryGrantOption.FALSE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege3);

    // 5. user1 has role1, no grant option,
    // revoke from role2 will throw no grant exception
    roleName = roles[2];
    grantor = users[1];
    boolean isGrantOptionException = false;
    try {
        sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege3);
    } catch (SentryGrantDeniedException e) {
        isGrantOptionException = true;
        System.err.println(e.getMessage());
    }
    assertTrue(isGrantOptionException);

    // 6. user0 has role0, only have select,
    // revoke all from role1 will throw no grant exception
    roleName = roles[1];
    grantor = users[0];
    try {
        sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege2);
    } catch (SentryGrantDeniedException e) {
        isGrantOptionException = true;
        System.err.println(e.getMessage());
    }
    assertTrue(isGrantOptionException);

    // 7. user0 has role0, has select and grant option,
    // revoke select from role2
    roleName = roles[2];
    grantor = users[0];
    sentryStore.alterSentryRoleRevokePrivilege(grantor, roleName, privilege3);
    role = sentryStore.getMSentryRoleByName(roleName);
    privileges = role.getPrivileges();
    assertEquals(0, privileges.size());
}

From source file:org.apache.sentry.provider.db.service.persistent.TestSentryStore.java

@Test
public void testGrantCheckWithGrantOption() throws Exception {
    // 1. set local group mapping
    // user0->group0->role0
    // user1->group1->role1
    // user2->group2->role2
    // user3->group3->role3
    // user4->group4->role4
    String grantor = "g1";
    String[] users = { "user0", "user1", "user2", "user3", "user4" };
    String[] roles = { "role0", "role1", "role2", "role3", "role4" };
    String[] groups = { "group0", "group1", "group2", "group3", "group4" };
    for (int i = 0; i < users.length; i++) {
        addGroupsToUser(users[i], groups[i]);
        sentryStore.createSentryRole(roles[i]);
        Set<TSentryGroup> tGroups = Sets.newHashSet();
        TSentryGroup tGroup = new TSentryGroup(groups[i]);
        tGroups.add(tGroup);/*from   w w w  . j a  v  a  2s  .c  om*/
        sentryStore.alterSentryRoleAddGroups(grantor, roles[i], tGroups);
    }
    writePolicyFile();

    // 2. g1 grant all on database db1 to role0 with grant option
    String server = "server1";
    String db = "db1";
    String table = "tbl1";
    String roleName = roles[0];
    grantor = "g1";
    TSentryPrivilege privilege1 = new TSentryPrivilege();
    privilege1.setPrivilegeScope("DATABASE");
    privilege1.setServerName(server);
    privilege1.setDbName(db);
    privilege1.setAction(AccessConstants.ALL);
    privilege1.setCreateTime(System.currentTimeMillis());
    privilege1.setGrantOption(TSentryGrantOption.TRUE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege1);
    MSentryRole role = sentryStore.getMSentryRoleByName(roleName);
    Set<MSentryPrivilege> privileges = role.getPrivileges();
    assertEquals(privileges.toString(), 1, privileges.size());

    // 3. user0 grant select on database db1 to role1, with grant option
    roleName = roles[1];
    grantor = users[0];
    TSentryPrivilege privilege2 = new TSentryPrivilege();
    privilege2.setPrivilegeScope("DATABASE");
    privilege2.setServerName(server);
    privilege2.setDbName(db);
    privilege2.setAction(AccessConstants.SELECT);
    privilege2.setCreateTime(System.currentTimeMillis());
    privilege2.setGrantOption(TSentryGrantOption.TRUE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege2);

    // 4. user0 grant all on table tb1 to role2, no grant option
    roleName = roles[2];
    grantor = users[0];
    TSentryPrivilege privilege3 = new TSentryPrivilege();
    privilege3.setPrivilegeScope("TABLE");
    privilege3.setServerName(server);
    privilege3.setDbName(db);
    privilege3.setTableName(table);
    privilege3.setAction(AccessConstants.ALL);
    privilege3.setCreateTime(System.currentTimeMillis());
    privilege3.setGrantOption(TSentryGrantOption.FALSE);
    sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege3);

    // 5. user1 has role1, no insert privilege,
    // grant insert to role3, will throw no grant exception
    roleName = roles[3];
    grantor = users[1];
    TSentryPrivilege privilege4 = new TSentryPrivilege();
    privilege4.setPrivilegeScope("DATABASE");
    privilege4.setServerName(server);
    privilege4.setDbName(db);
    privilege4.setAction(AccessConstants.INSERT);
    privilege4.setCreateTime(System.currentTimeMillis());
    privilege4.setGrantOption(TSentryGrantOption.FALSE);
    boolean isGrantOptionException = false;
    try {
        sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege4);
    } catch (SentryGrantDeniedException e) {
        isGrantOptionException = true;
        System.err.println(e.getMessage());
    }
    assertTrue(isGrantOptionException);

    // 6. user2 has role2, no grant option,
    // grant insert to role4, will throw no grant exception
    roleName = roles[4];
    grantor = users[2];
    TSentryPrivilege privilege5 = new TSentryPrivilege();
    privilege5.setPrivilegeScope("TABLE");
    privilege5.setServerName(server);
    privilege5.setDbName(db);
    privilege5.setTableName(table);
    privilege5.setAction(AccessConstants.INSERT);
    privilege5.setCreateTime(System.currentTimeMillis());
    privilege5.setGrantOption(TSentryGrantOption.FALSE);
    isGrantOptionException = false;
    try {
        sentryStore.alterSentryRoleGrantPrivilege(grantor, roleName, privilege5);
    } catch (SentryGrantDeniedException e) {
        isGrantOptionException = true;
        System.err.println(e.getMessage());
    }
    assertTrue(isGrantOptionException);
}

From source file:com.pari.nm.modules.jobs.VSEMImporter.java

private String addDeviceEntity(EntityData devData, Long discTime) throws Exception {
    PerDeviceImportStatus importDeviceStatus = new PerDeviceImportStatus();
    PerDeviceConfigBackupStatus deviceConfigBackupStatus = new PerDeviceConfigBackupStatus();
    long startTime = System.currentTimeMillis();
    importDeviceStatus.setStartTime(startTime);
    DSPNewDevice dev = new DSPNewDevice(devData);
    dev.setAttribute("DiscoveredTime", discTime);
    StringBuilder result = new StringBuilder();
    System.out.println("os = " + dev.getOsName());
    setOSTypeBasedOnSysDesc(dev);/* w w  w.j av  a 2s .c  om*/

    try {
        dspExecutor.execute(dev);
        Set<String> set = new HashSet<>();
        // Removing duplicates for SMUNames before storing in DB.
        String s = dev.getAttribute("SMUNames");
        if (s != null && !s.isEmpty()) {
            String[] al = s.split(",");
            for (String a : al) {
                set.add(a);
            }
            s = set.toString().replace("[", "").replace("]", "");
            dev.setAttribute("SMUNames", s);
        }
        // Executes system and user defined DSP scripts
        DSPMetadataHandler metadataHandler = new DSPMetadataHandler();
        dev.setMetadataHandler(metadataHandler);
        String sysObjId = dev.getSysObjectId();
        if (sysObjId != null && sysObjId.length() != 0) {
            List<ScriptInfo> sysScripts = DeviceScriptManagerImpl.getInstance()
                    .getSystemDevicePackages(sysObjId, customerId);
            if (!sysScripts.isEmpty()) {
                dspHandler.handlePackages(dev, sysScripts);
            }
            List<ScriptInfo> userScripts = DeviceScriptManagerImpl.getInstance().getUserDevicePackages(sysObjId,
                    customerId);
            if (!userScripts.isEmpty()) {
                dspHandler.handlePackages(dev, userScripts);
            }

            // added as part if DSP ICF Integration
            List<ScriptInfo> icfScripts = DeviceScriptManagerImpl.getInstance().getIcfDevicePackages(sysObjId,
                    customerId);
            if (!icfScripts.isEmpty()) {
                for (ScriptInfo ic : icfScripts) {
                    ICStatisticsManager.getInstance().populateICUsageStatisticsInfo(ic, 1);
                }
                dspHandler.handlePackages(dev, icfScripts);
            }
        } else {

            List<ScriptInfo> sysScripts = DeviceScriptManagerImpl.getInstance()
                    .getSystemDefinedZipPackages(PackageType.ZipInventory, "System");
            sysScripts = checkForApplicableScripts(sysScripts, dev);

            if (!sysScripts.isEmpty()) {
                dspHandler.handlePackages(dev, sysScripts);
            }

            List<ScriptInfo> userScripts = DeviceScriptManagerImpl.getInstance()
                    .getUserDefinedZipPackages(PackageType.ZipInventory, customerId, "User");
            userScripts = checkForApplicableScripts(userScripts, dev);
            if (!userScripts.isEmpty()) {
                dspHandler.handlePackages(dev, userScripts);
            }

            // added as part if DSP ICF Integration
            List<ScriptInfo> icfScripts = DeviceScriptManagerImpl.getInstance()
                    .getIcfDefinedZipPackages(PackageType.ZipInventory, customerId, "Icf");
            if (!icfScripts.isEmpty()) {
                for (ScriptInfo ic : icfScripts) {
                    ICStatisticsManager.getInstance().populateICUsageStatisticsInfo(ic, 1);
                }
                dspHandler.handlePackages(dev, icfScripts);
            }
        }

    } catch (Exception ex) {
        logger.error("Excetption while executing DSP for device: " + dev.getDeviceName(), ex);
        result.append("<B>Exception while executing Device Support Scripts. Continuing anyway.</B><BR>");
        // We will continue and import the device as much as possible.
    }

    // Device coming as GenericDevice from CSPC and having running-config command other than show running-config,
    // running-config needs to be populated after setting OSType in DSP script
    // if (dev.getRunningConfig() == null || dev.getRunningConfig().isEmpty())

    //If device has running-config command other than show running-config, then populating data again.
    String command = InventoryDBHelper.getCommandForRunningConfig(dev.getOsName());
    if (command != null) {
        dev.populateConfigs();
    }

    sanitizeProductModel(dev); // CSCug64696 - Moved it after dspExecutor which parses sh versoin to get
    // ProductModel.

    importDeviceStatus.setHostName(dev.getDeviceName());
    importDeviceStatus.setIpAddress(dev.getIpAddress());
    importDeviceStatus.setOsName(dev.getOsName());
    importDeviceStatus.setOsVersion(dev.getVersionStr());
    importDeviceStatus.setDeviceFamily(dev.getDeviceFamily());
    importDeviceStatus.setProductModel(dev.getProductId());

    if (!dev.getColectionErrorList().isEmpty()) {
        if (perDeviceConfigBackupStatus == null) {
            perDeviceConfigBackupStatus = new ConcurrentHashMap<String, PerDeviceConfigBackupStatus>();
        }
        deviceConfigBackupStatus.setHostName(dev.getDeviceName());
        deviceConfigBackupStatus.setIpAddress(dev.getIpAddress());
        deviceConfigBackupStatus.setStartTime(startTime);
        deviceConfigBackupStatus.setEndTime(System.currentTimeMillis());
        deviceConfigBackupStatus.setErrorCollectionList(dev.getColectionErrorList());
        deviceConfigBackupStatus.setSuccess(false);
        perDeviceConfigBackupStatus.put(dev.getIpAddress(), deviceConfigBackupStatus);
    }

    // CSCtx24489 - Added grpName (group name) to the DeviceAdder
    DeviceAdder adder = new DeviceAdder(dev, InsertMode.update, customerId, wingInstanceName, rowId, invoker,
            login, result, collInfo, grpName, jobId, jobParameters);
    String str = adder.addDevice(null);
    importDeviceStatus.setEndTime(System.currentTimeMillis());
    List<DAVStatus> davStatus = this.davStatusData.get(importDeviceStatus.getIpAddress());
    StringBuilder davStatusMessage = new StringBuilder();
    boolean isSuccess = false;
    if (davStatus != null) {
        for (DAVStatus deviceStatus : davStatus) {
            if (deviceStatus.getStatus().equalsIgnoreCase("Successful")) {
                importDeviceStatus.setDavStatus(deviceStatus.getStatus());
                isSuccess = true;
                continue;
            }
            davStatusMessage.append(deviceStatus.getProtocol() + " : " + deviceStatus.getStatus() + " <br>");
        }
        if (isSuccess) {
            importDeviceStatus.setDavStatusMessage(" - ");
        } else {
            importDeviceStatus.setDavStatus(" Failed ");
            importDeviceStatus.setDavStatusMessage(davStatusMessage.toString());
        }
    }

    if (str != null) {
        importDeviceStatus.setSuccess(false);
        importDeviceStatus.setMessage(str);
        perDeviceImportStatus.put(dev.getIpAddress(), importDeviceStatus);
        return str;
    }
    // adder.setConfigUpdated(true);
    DeviceStateChangeMessage sc = null;
    NetworkNode parent = adder.getNetworkNode();
    // If config updated for NXOS device, then we create checkpoint
    if (dev.getOsName().equalsIgnoreCase("nx-os") && adder.isConfigUpdated()) {
        nxosDevices.put(parent.getIpAddr().toString(), parent.getNodeId());
    }

    else if (dev.getOsName().equalsIgnoreCase("nxos") && adder.isConfigUpdated()) {
        nxosDevices.put(parent.getIpAddr().toString(), parent.getNodeId());
    }
    // If config updated for WLC device, then we collect 'transfer upload' config
    else if (dev.getOsName().equalsIgnoreCase("WLC") && adder.isConfigUpdated()) {
        wlcDevices = new ConcurrentHashMap<String, Integer>();
        wlcDevices.put(parent.getIpAddr().toString(), parent.getNodeId());
    } else if (dev.getOsName().equalsIgnoreCase("UCS")) {

        ucsDevices.put(parent.getIpAddr().toString(), parent.getNodeId());
    } else if (dev.getOsName().equalsIgnoreCase("ons")) {
        onsDevices.put("CPLoginUser", login);
        onsDevices.put(parent.getIpAddr().toString(), parent.getNodeId() + "");
    }

    else if (dev.getOsName().equalsIgnoreCase("JunOS") && adder.isConfigUpdated()) {

        junosDevices.put(parent.getIpAddr().toString(), parent.getNodeId());

    } else if (NmIfImpl.getInstance().isDeviceSupportedForResync(parent.getNodeId())
            && adder.isConfigUpdated()) {
        NetworkNode node = NetworkNodeCache.getInstance().getNodeByID(parent.getNodeId());

        DSPConfigData configData = executeConfigDSP(node);
        Map<String, String> details = new HashMap<String, String>();
        List<String> resyncConfigCmds = (List<String>) configData.getAttribute("resyncConfigCmds");
        if (resyncConfigCmds != null) {
            StringBuffer resyncCmd = new StringBuffer();
            for (String cmd : resyncConfigCmds) {
                resyncCmd.append(cmd);
                /**
                 * Added Space for handling file extensions in addon side
                 */
                resyncCmd.append(" \n");
            }
            details.put("resyncCmd", resyncCmd.toString());
            details.put("waitTime", configData.getAttribute("WaitTime").toString());
            details.put("fileType", configData.getAttribute("FileType").toString());
            Object regex = configData.getAttribute("FileNameRegex");
            if (regex != null) {
                details.put("regex", regex.toString());
            }
            otherDevices.put(parent.getIpAddr().toString(), details);
        }

    }
    importDeviceStatus.setSuccess(true);
    importDeviceStatus.setDeviceId(parent.getNodeId());
    perDeviceImportStatus.put(dev.getIpAddress(), importDeviceStatus);

    if (perDeviceConfigBackupStatus != null) {
        deviceConfigBackupStatus.setDeviceId(parent.getNodeId());
    }

    StringBuffer sb = new StringBuffer();

    Map<String, DSPNewDevice> modules = dev.getModules();
    deleteExistingModulesIfNecessary(modules, parent);
    int failedModules = addChildDevices(modules, parent, ModuleType.MODULE);

    Map<String, DSPNewDevice> newLogicalDevices = dev.getLogicalDevices();
    deleteExistingContextsIfNecessary(newLogicalDevices, parent, dev);
    int failedLogicalDevices = addChildDevices(newLogicalDevices, parent, ModuleType.CONTEXT);

    sc = new DeviceStateChangeMessage(parent.getNodeId(), true);
    ClientSessionManager.getInstance().sendMessageToAll(sc, parent.getNodeId(),
            ClientMessageType.NETWORK_NODE_RELATED);
    if (failedModules > 0) {
        // sb.append("Device successfully imported but " + failedModules + " Module" + ((failedModules > 1) ? "s" :
        // "") + " failed to import.");
        if (invoker != null) {
            invoker.logMsg(parent.getNodeName() + " imported successfully. But " + failedModules + " Module"
                    + ((failedModules > 1) ? "s" : "") + " failed to import.");
        }
    }
    if (failedLogicalDevices > 0) {
        // sb.append("Device successfully imported but " + failedLogicalDevices + " Context" +
        // ((failedLogicalDevices > 1) ? "s" : "") + " failed to import.");
        if (invoker != null) {
            invoker.logMsg(parent.getNodeName() + " imported successfully. But " + failedLogicalDevices
                    + " Context" + ((failedLogicalDevices > 1) ? "s" : "") + " failed to import.");
        }
    }
    if (sb.length() == 0) {
        return null;
    }
    return sb.toString();
}

From source file:org.apache.hawq.ranger.service.HawqClient.java

private List<String> queryHawqPerDbAndSchema(String userInput, Map<String, List<String>> resources,
        String schemaColumnName, String resultColumnName, String query) throws SQLException {
    Set<String> uniqueResults = new HashSet<>();
    List<String> databases = resources.get("database");
    List<String> schemas = resources.get("schema");

    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;/*from  ww  w .  j  a v  a2s .c  om*/
    Connection conn = null;

    if (databases.contains(WILDCARD)) {
        databases = getDatabaseList(WILDCARD);
    }

    for (String db : databases) {

        if (LOG.isDebugEnabled()) {
            LOG.debug("<== HawqClient.queryHawqPerDbAndSchema: Connecting to db: " + db);
        }

        try {
            conn = getConnection(connectionProperties, db);
            preparedStatement = handleWildcardPreparedStatement(userInput, query, conn);

            if (LOG.isDebugEnabled()) {
                LOG.debug("<== HawqClient.queryHawqPerDbAndSchema Starting query: "
                        + preparedStatement.toString());
            }

            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                if (schemas.contains(resultSet.getString(schemaColumnName)) || schemas.contains(WILDCARD)) {
                    uniqueResults.add(resultSet.getString(resultColumnName));
                }
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("<== HawqClient.queryHawqPerDbAndSchema Query result: " + uniqueResults.toString());
            }

        } catch (SQLException e) {
            LOG.error("<== HawqClient.queryHawqPerDbAndSchema Error: Failed to get results for query: " + query
                    + ", Error: " + e);
        } finally {
            closeResultSet(resultSet);
            closeStatement(preparedStatement);
            closeConnection(conn);
        }

    }
    return new ArrayList<>(uniqueResults);
}