Skip to content

Apache Ranger Java API User Guide

This section provides some examples of how to use the Apache Ranger Java API to interact with the Ranger service programmatically. Here are the Apache Ranger REST API reference and the Java API documentation.

Getting Started

Privacera host the customized Apache Ranger Java client libraries in a Maven repository. You can include these libraries in your project to interact with the Ranger service programmatically.

Ranger API version details:

Privacera Release Ranger API Release
9.2.39.1 d20b0b0eaa

Maven Repository:

Add the Privacera's Apache Ranger Maven repository to your project's build configuration file.

Maven Configuration

XML
1
2
3
4
5
6
<repositories>
    <repository>
        <id>privacera-repo</id>
        <url>https://s3.amazonaws.com/privacera-maven-repo-prod/</url>
    </repository>
</repositories>

Gradle Configuration

Text Only
1
2
3
4
5
repositories {
maven {
   url 'https://s3.amazonaws.com/privacera-maven-repo-prod/'
   }
}

Apache Ranger API Dependencies:

Include the following dependant libraries in your project's build configuration (e.g., Maven, Gradle).

Maven Dependency

XML
<dependency>
   <groupId>org.apache.ranger</groupId>
   <artifactId>ranger-intg</artifactId>
   <version>d20b0b0eaa</version><!-- Replace with the appropriate version -->
</dependency>
<dependency>
   <groupId>org.apache.ranger</groupId>
   <artifactId>ranger-plugins-common</artifactId>
   <version>d20b0b0eaa</version>
</dependency>
<dependency>
   <groupId>org.glassfish.jersey.media</groupId>
   <artifactId>jersey-media-json-jackson</artifactId>
   <version>4.0.0</version>
</dependency>
<dependency>
   <groupId>org.glassfish.jersey.inject</groupId>
   <artifactId>jersey-hk2</artifactId>
   <version>4.0.0</version>
</dependency>

Gradle Dependency

Text Only
1
2
3
4
5
6
dependencies {
    implementation 'org.apache.ranger:ranger-intg:d20b0b0eaa' // Replace with the appropriate version
    implementation 'org.apache.ranger:ranger-plugins-common:d20b0b0eaa'
    implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:4.0.0'
    implementation 'org.glassfish.jersey.inject:jersey-hk2:4.0.0'
}

Create a Ranger Admin Client:

Java
import org.apache.ranger.RangerClient;

public class RangerClientExample {
    public static void main(String[] args) {
        String rangerAdminUrl = "http://<ranger_admin_host>:<ranger_admin_port>"; // Replace with your Ranger Admin URL
        String username = "admin";
        String password = "_your_admin_password_";
        String authType = "BASIC";

      // For Apache Ranger with self-signed SSL enabled, refer to the SSL configuration example provided below.

        RangerClient rangerClient = new RangerClient(hostName, authType, userName, password, null);


    }
}

Sample SSL 'ssl-client.xml' configuration file for self-signed SSL enabled Apache Ranger :

Text Only
<configuration>
    <property>
        <name>xasecure.policymgr.clientssl.truststore</name>
        <value></value>
    </property>
    <property>
        <name>xasecure.policymgr.clientssl.truststore.credential.file</name>
        <value></value>
    </property>
    <property>
        <name>xasecure.policymgr.clientssl.truststore.type</name>
        <value></value>
    </property>
</configuration>

Search filters and pagination

Every find* method takes a Map<String, String> that the client sends to Ranger Admin as query parameters. Ranger Admin reads only the keys that the target endpoint supports and ignores the rest without reporting an error, so an unsupported or misspelled key does not fail — the search simply runs without that condition and returns every record the caller can see.

Because a wrong key is silently dropped, the key spelling matters. The examples below pass the keys as string literals.

Java
1
2
3
4
Map<String, String> filter = new HashMap<>();
filter.put("serviceName", "privacera_s3");
filter.put("role", "ROLE_1");        // "role" is the key that findPolicies matches against
// filter.put("roleName", "ROLE_1"); // ignored by findPolicies: every policy is returned

The tables below list the keys each method supports. A key that is not listed for a method is ignored by that method, even if another method accepts it.

Filter keys for findPolicies

Key Match Accepted values and notes
serviceName Exact Service name, for example privacera_s3. Set it whenever you use the resource, label, priority, or recursion keys below, because those are evaluated one service at a time.
serviceType Exact Service def name, for example s3, hive.
serviceId Exact Numeric service ID.
policyId Exact Numeric policy ID.
policyName Exact Full policy name.
policyNamePartial Substring Case-insensitive substring of the policy name.
policyType Exact 0 access policy, 1 masking policy, 2 row-filter policy.
policyPriority Exact NORMAL or OVERRIDE, or the equivalent 0 and 1. Set serviceName as well.
policyLabelsPartial Substring Substring of a policy label. Set serviceName as well.
guid Exact Policy GUID.
isEnabled Exact true or false.
user Exact Username referenced by a policy item. Also returns policies that grant access through the user's groups and through the {USER} macro.
group Exact Group name referenced by a policy item.
role Exact Role name referenced by a policy item. This is the key to use when searching policies by role.
userNamePartial Substring Substring of a referenced username.
groupNamePartial Substring Substring of a referenced group name.
roleNamePartial Substring Substring of a referenced role name.
zoneName Exact Security zone name.
zoneId Exact Numeric security zone ID.
resource:<resource-name> Resource match One entry per resource level defined by the service def, for example resource:bucketname, resource:database. Set serviceName as well.
resourceMatchScope self, ancestor, or self_or_ancestor. Only applies together with resource: keys.
polResource Substring Substring match against any resource value. Set serviceName as well.
isRecursive Exact true or false. Set serviceName as well.

Filter keys for findServices

Key Match Accepted values and notes
serviceName Exact Service name.
serviceNamePartial Substring Substring of the service name.
serviceDisplayName Exact Display name shown in the UI.
serviceDisplayNamePartial Substring Substring of the display name.
serviceType Exact Service def name, for example s3.
serviceTypeId Exact Numeric service def ID.
serviceId Exact Numeric service ID.
isEnabled Exact true or false.
tagServiceName Exact Name of the linked tag service.
tagServiceId Exact Numeric ID of the linked tag service.

Filter keys for findServiceDefs

Key Match Accepted values and notes
serviceType Exact Service def name, for example s3.
serviceTypeDisplayName Exact Display name of the service def.
serviceTypeId Exact Numeric service def ID.
isEnabled Exact true or false.

Filter keys for findRoles

Key Match Accepted values and notes
roleId Exact Numeric role ID.
roleName Exact Full role name.
roleNamePartial Substring Substring of the role name.
userName Exact Returns roles that have this user as a member.
userNamePartial Substring Substring of a member username.
groupName Exact Returns roles that have this group as a member.
groupNamePartial Substring Substring of a member group name.

Filter keys for findSecurityZones

Key Match Accepted values and notes
zoneId Exact Numeric zone ID.
zoneName Exact Full zone name.
zoneNamePartial Substring Substring of the zone name.
serviceName Exact Returns zones that contain resources of this service.
createdBy Exact Login ID of the user who created the zone.

Filter keys for findUsers and findGroups

findUsers:

Key Match Accepted values and notes
name Substring Substring of the username.
userName Exact Full username.
emailAddress Substring Substring of the email address.
userSource Exact 0 internal user, 1 external user.
userRoleList Exact One of ROLE_USER, ROLE_SYS_ADMIN, ROLE_KEY_ADMIN, ROLE_ADMIN_AUDITOR, ROLE_KEY_ADMIN_AUDITOR. The filter map carries a single value, so search one role at a time.
status Exact 0 disabled, 1 enabled.
isVisible Exact 0 hidden, 1 visible.
syncSource Substring Sync source recorded by UserSync, for example LDAP/AD.

findGroups:

Key Match Accepted values and notes
name Substring Substring of the group name.
groupSource Exact 0 internal group, 1 external group.
isVisible Exact 0 hidden, 1 visible.
syncSource Substring Sync source recorded by UserSync.

Pagination

startIndex and pageSize are accepted by findServiceDefs, findServices, findPolicies, findRoles, findUsers, and findGroups.

Key Default Description
startIndex 0 Zero-based index of the first record to return.
pageSize ranger.db.maxrows.default, which ships as 100 Maximum number of records returned in one call.

If you omit pageSize, the response is capped at the Ranger Admin default of 100 records and nothing in the response indicates that more records exist. Page explicitly whenever the result set can grow beyond that:

Java
        int pageSize = 100;
        int startIndex = 0;
        List<RangerPolicy> allPolicies = new ArrayList<>();

        while (true) {
            Map<String, String> filter = new HashMap<>();
            filter.put("serviceName", "privacera_s3");
            filter.put("startIndex", String.valueOf(startIndex));
            filter.put("pageSize", String.valueOf(pageSize));

            List<RangerPolicy> page = rangerClient.findPolicies(filter);
            if (page.isEmpty()) {
                break;
            }

            allPolicies.addAll(page);
            if (page.size() < pageSize) {
                break;   // last page
            }
            startIndex += pageSize;
        }

Examples:

Fetch Policies

To retrieve policies for a specific service:

Java
import org.apache.ranger.plugin.model.RangerPolicy;
import java.util.List;

public class FetchPoliciesExample {
    public static void main(String[] args) {
        String serviceName = "privacera_s3"; // Replace with your service name
        String rangerAdminUrl = "http://<ranger_admin_host>:<ranger_admin_port>"; // Replace with your Ranger Admin URL
        String username = "admin";
        String password = "_your_admin_password_";
        String authType = "BASIC";
        String cfg = "ssl-client.xml"; // Path to the SSL configuration file

      RangerClient rangerClient = new RangerClient(hostName, authType, userName, password, cfg);

        try {
            List<RangerPolicy> policies = rangerClient.getPoliciesInService(serviceName);
            for (RangerPolicy policy : policies) {
                System.out.println("Policy Name: " + policy.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

To search policies by user, role, or resource. See Filter keys for findPolicies for the full list of supported keys and their values:

Java
        /*
        Search policies by user
         */
        Map<String, String> userFilter = new HashMap<>();
        userFilter.put("user", "user1");
        userFilter.put("serviceName", "privacera_s3");
        List<RangerPolicy> userPolicyList = rangerClient.findPolicies(userFilter);

        /*
        Search policies by role
         */
        Map<String, String> roleFilter = new HashMap<>();
        roleFilter.put("role", "ROLE_1");
        roleFilter.put("serviceName", "privacera_s3");
        List<RangerPolicy> rolePolicyList = rangerClient.findPolicies(roleFilter);

        /*
        Search policies by resource
         */
        Map<String, String> resourceFilter = new HashMap<>();
        resourceFilter.put("policyType", "0"); // 0 = Access, 1 = Masking, 2 = Row filter
        resourceFilter.put("resource:bucketname", "bucket2025");
        resourceFilter.put("resource:objectpath", "dir1");
        resourceFilter.put("serviceName", "privacera_s3"); // required for resource: keys
        resourceFilter.put("resourceMatchScope", "self_or_ancestor"); // self, ancestor, or self_or_ancestor
        List<RangerPolicy> resourcePolicyList = rangerClient.findPolicies(resourceFilter);

        // The returned lists contain policies matching the respective filters

Create, get, update, and delete a Policy

To create a new policy for a service:

Java
        /*
        Create a new Policy
         */
        Map<String, RangerPolicy.RangerPolicyResource> resource = Collections.singletonMap(
                "root", new RangerPolicy.RangerPolicyResource(Collections.singletonList("/path/to/sample/resource"),false,false));
        RangerPolicy policy = new RangerPolicy();
        policy.setService(serviceName);
        policy.setZoneName(zoneName);
        policy.setName(policyName);
        policy.setResources(resource);

        RangerPolicy createdPolicy = rangerClient.createPolicy(policy);

To get, update, and delete a policy:

Java
        /*
        Get, update, and delete a Policy
         */
        RangerPolicy policyById = rangerClient.getPolicy(policyId);
        RangerPolicy policyByName = rangerClient.getPolicy("privacera_s3", policyName);

        policyByName.setDescription("Updated description");
        RangerPolicy updatedPolicy = rangerClient.updatePolicy(policyId, policyByName);

        rangerClient.deletePolicy(policyId);

        // The returned updatedPolicy object contains the updated policy details

Update Policy to give access to a user

To update an existing policy to grant read access to a user:

Java
        /*
        Update an existing Policy to give access to a user
         */
        RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
        policyItem.setDelegateAdmin(false);
        policyItem.setUsers(Arrays.asList("johndoe"));
        policyItem.setAccesses(Arrays.asList(new RangerPolicy.RangerPolicyItemAccess("read", true)));
        boolean isAllowException = false; // Set to true if you want to update allow exceptions
        RangerPolicy updatedPolicy = rangerClient.grantAccess(policy.getId(), Arrays.asList(policyItem), isAllowException);

        // The returned updatedPolicy object contains the updated policy details 

Update Policy to give additional access to a user

To update an existing policy to grant additional 'write' access to a user:

Java
        /*
        Update an existing Policy to give access to a user
         */
        RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
        policyItem.setDelegateAdmin(false);
        policyItem.setUsers(Arrays.asList("johndoe"));
        policyItem.setAccesses(Arrays.asList(new RangerPolicy.RangerPolicyItemAccess("write", true)));
        boolean isAllowException = false; // Set to true if you want to update allow exceptions
        RangerPolicy updatedPolicy = rangerClient.grantAccess(policy.getId(), Arrays.asList(policyItem), isAllowException);

        // The returned updatedPolicy object contains the updated policy details with "read" and "write" access to user 'johndoe'

Update policy to remove access for a user

Java
1
2
3
4
5
6
      Map<RangerPrincipal.PrincipalType, List<String>> principalsToDelete = new HashMap<>();
      principalsToDelete.put(RangerPrincipal.PrincipalType.USER, Arrays.asList("johndoe"));
      boolean isAllowException = false; // Set to true if you want to delete allow exceptions
      RangerPolicy policy = rangerClient.deleteAccess(policy.getId(), principalsToDelete, new ArrayList<>(), isAllowException);

      // The returned policy object contains the updated policy details without the user 'johndoe'

Update policy to remove permission for a given user e.g remove 'select' permission

Java
      import java.util.Arrays;

Map<RangerPrincipal.PrincipalType, List<String>> principalsToDelete = new HashMap<>();
      principalsToDelete.

put(RangerPrincipal.PrincipalType.USER, Arrays.asList("johndoe"));
List<String> permissions = Arrays.asList("select");
boolean isAllowException = false; // Set to true if you want to delete allow exceptions
RangerPolicy policy = rangerClient.deleteAccess(policy.getId(), principalsToDelete, permissions, isAllowException);

// The returned policy object contains the updated policy details without the 'select' permission for user 'johndoe'

Add a deny access policy

Java
1
2
3
4
5
6
7
8
9
        /*
        Add a deny access policy
         */
        RangerPolicy.RangerPolicyItem denyPolicyItem = new RangerPolicy.RangerPolicyItem();
        denyPolicyItem.setDelegateAdmin(false);
        denyPolicyItem.setUsers(Arrays.asList("johndoe"));
        denyPolicyItem.setAccesses(Arrays.asList(new RangerPolicy.RangerPolicyItemAccess("write", false)));
        boolean isDenyException = false; // Set to true if you want to add deny exceptions
        RangerPolicy updatedPolicy = rangerClient.denyAccess(policy.getId(), Arrays.asList(denyPolicyItem), isDenyException);

Search and get services

To search services and retrieve a service by name or ID. See Filter keys for findServices for the supported keys:

Java
        /*
        Search and get services
         */
        Map<String, String> serviceFilter = new HashMap<>();
        serviceFilter.put("serviceNamePartial", "privacera");
        serviceFilter.put("serviceType", "s3");
        serviceFilter.put("startIndex", "0");
        serviceFilter.put("pageSize", "100");

        List<RangerService> services = rangerClient.findServices(serviceFilter);

        RangerService serviceByName = rangerClient.getService("privacera_s3");
        RangerService serviceById = rangerClient.getService(serviceByName.getId());

        // The returned serviceById object contains the same service details as serviceByName

Manage roles

To create a role, search roles, grant a role to a user, and delete a role. See Filter keys for findRoles for the supported search keys:

Java
        /*
        Create a new Role
         */
        RangerRole roleToCreate = new RangerRole();
        roleToCreate.setName("EXAMPLE_DEMO_ROLE");
        roleToCreate.setDescription("Example role");
        roleToCreate.setUsers(Collections.emptyList());
        roleToCreate.setGroups(Collections.emptyList());
        roleToCreate.setRoles(Collections.emptyList());

        RangerRole createdRole = rangerClient.createRole("privacera_s3", roleToCreate);

        /*
        Search roles by partial name
         */
        Map<String, String> roleFilter = new HashMap<>();
        roleFilter.put("roleNamePartial", "EXAMPLE_DEMO_ROLE");
        roleFilter.put("startIndex", "0");
        roleFilter.put("pageSize", "100");
        List<RangerRole> matchingRoles = rangerClient.findRoles(roleFilter);

        /*
        Grant a user to a role
         */
        GrantRevokeRoleRequest grantRequest = new GrantRevokeRoleRequest();
        grantRequest.setGrantor(userName);
        grantRequest.setTargetRoles(Collections.singleton("EXAMPLE_DEMO_ROLE"));
        grantRequest.setUsers(Collections.singleton("user1"));
        RESTResponse grantResponse = rangerClient.grantRole("privacera_s3", grantRequest);

        rangerClient.deleteRole("EXAMPLE_DEMO_ROLE", userName, "privacera_s3");

        // The returned grantResponse object contains the status of the grant operation

Search users and groups

To search users and groups. See Filter keys for findUsers and findGroups for the supported keys:

Java
        /*
        Search users by name
         */
        Map<String, String> userQuery = new HashMap<>();
        userQuery.put("startIndex", "0");
        userQuery.put("pageSize", "25");
        userQuery.put("name", "user1");
        String usersJson = rangerClient.findUsers(userQuery);

        /*
        Search groups by name
         */
        Map<String, String> groupQuery = new HashMap<>();
        groupQuery.put("startIndex", "0");
        groupQuery.put("pageSize", "25");
        groupQuery.put("name", "public");
        String groupsJson = rangerClient.findGroups(groupQuery);

        // The returned JSON strings contain matching users and groups

Add a resource to Security Zone identified by zone ID

Java
   // Create a resource map for e.g s3 bucket name 'bucket-1'
   Map<String, List<String>> resourceMap = new HashMap<>();
       resourceMap.put("bucketname", Arrays.asList("bucket-1"));
           resourceMap.put("objectpath", Arrays.asList("*"));

   // Create a security zone resource using the resource map
   RangerSecurityZoneV2.RangerSecurityZoneResource securityZoneResource = new RangerSecurityZoneV2.RangerSecurityZoneResource(resourceMap);

   // Create a security zone service using the security zone resource
   RangerSecurityZoneV2.RangerSecurityZoneServiceV2 securityZoneServiceV2 = new RangerSecurityZoneV2.RangerSecurityZoneServiceV2();
       securityZoneServiceV2.setResources(Arrays.asList(securityZoneResource));

   // Create a security zone service map using the security zone service
   Map<String, RangerSecurityZoneV2.RangerSecurityZoneServiceV2> serviceMap = new HashMap<>();
       serviceMap.put("privacera_s3", securityZoneServiceV2);

   // Create a security zone change request to add the resource to the security zone 
   RangerSecurityZoneV2.RangerSecurityZoneChangeRequest securityZoneChangeRequest = new RangerSecurityZoneV2.RangerSecurityZoneChangeRequest();
       securityZoneChangeRequest.setResourcesToUpdate(serviceMap);

   boolean result = rangerClient.updateSecurityZoneV2Partially(175l, securityZoneChangeRequest);
    if (result) {
        LOG.info("Security Zone updated successfully");
    } else {
            LOG.info("Security Zone update failed");
    }

Update a resource in a policy identified by Policy id

Java
1
2
3
4
5
6
7
       RangerPolicy.RangerPolicyResource bucketResource = new RangerPolicy.RangerPolicyResource("bucket1", false, false);
        RangerPolicy.RangerPolicyResource objectPathResource = new RangerPolicy.RangerPolicyResource("path1", false, false);
        Map<String, RangerPolicy.RangerPolicyResource> newResourceMap = new HashMap<>();
        newResourceMap.put("bucketname", bucketResource);
        newResourceMap.put("objectpath", objectPathResource);

        rangerClient.updatePolicyResources(15937l, newResource );