DECLARE
  acl_path VARCHAR2(4000);
  acl_id   RAW(16);
BEGIN
  dbms_output.put_line('Checking ACLs');
  -- Look for the ACL currently assigned to '*' and give FLOWS_030000
  -- the "connect" privilege if FLOWS_030000 does not have the privilege yet.

  SELECT acl
    INTO acl_path
    FROM dba_network_acls
   WHERE host = '*'
     AND lower_port IS NULL
     AND upper_port IS NULL;

  -- Before checking the privilege, make sure that the ACL is valid
  -- (for example, does not contain stale references to dropped users).
  -- If it does, the following exception will be raised:
  --
  -- ORA-44416: Invalid ACL: Unresolved principal 'FLOWS_030000'
  -- ORA-06512: at "XDB.DBMS_XDBZ", line ...
  --
  SELECT sys_op_r2o(extractvalue(p.res
                                ,'/Resource/XMLRef'))
    INTO acl_id
    FROM xdb.xdb$acl a
        ,path_view   p
   WHERE extractvalue(p.res
                     ,'/Resource/XMLRef') = REF(a)
     AND equals_path(p.res
                    ,acl_path) = 1;

  dbms_xdbz.validateacl(acl_id);
  IF dbms_network_acl_admin.check_privilege(acl_path
                                           ,'FLOWS_030000'
                                           ,'connect') IS NULL THEN
    dbms_network_acl_admin.add_privilege(acl_path
                                        ,'FLOWS_030000'
                                        ,TRUE
                                        ,'connect');
  END IF;

  dbms_output.put_line('Finished');

EXCEPTION
  -- When no ACL has been assigned to '*'.
  WHEN no_data_found THEN
    dbms_output.put_line('No ACL assigned to ''*''');
    dbms_network_acl_admin.create_acl('power_users.xml'
                                     ,'ACL that lets power users to connect to everywhere'
                                     ,'FLOWS_030000'
                                     ,TRUE
                                     ,'connect');
    dbms_network_acl_admin.assign_acl('power_users.xml'
                                     ,'*');
    dbms_output.put_line('ACL assigned to ''*''');
END;
/
COMMIT;
