Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Panel
borderColor#ccc
bgColor#FcFEFF
titleColorwhite
titleBGColor#00a400

 This topic is discussed in the "Grouper API - Part 2" training video.

GrouperShell (gsh)

gsh is a command line shell for administering and interacting with the Grouper API. See architectural diagram.  It can be used in both a batch and interactive manner.  For Grouper 2.3.0 patch 72+, it is built on GroovyShell.  For older versions of Grouper, it is built on Java BeanShell.  The legacy BeanShell version is now deprecated, but you can switch back to it by using one of the options:

  • Setting gsh.useLegacy = true in grouper.properties.
  • Using a command line argument  (gsh.sh -forceLegacyGsh)

GrouperShell is for Grouper admins.  End users can script with the grouper client command line utility

GSH operations

NOTE: Some classes were added a later 2.5.x releases. Not all are documented as to when they were initially added.

CategorySubtypeActionClass
AttestationFoldersinsert / update / deleteAttestationStemSave
Groupsinsert / update / deleteAttestationGroupSave
Attribute assignment

Attribute assignmentinsert / update / deleteAttributeAssignToAssignmentSave (2.5.48+)
Foldersinsert / update / deleteAttributeAssignToStemSave
Groupinsert / update / deleteAttributeAssignToGroupSave
Attribute definition
insert / update / deleteAttributeDefSave
Attribute name
insert / update / deleteAttributeDefNameSave
Attribute value
insert / update / deleteAttributeAssignValueSave
Composite
insert /update / deleteCompositeSave

finderCompositeFinder
Email SMTP

GrouperEmail
Gc db access
gc db accessGcDbAccess
Grouper session

GrouperSession
Group
insert / update / deleteGroupSave

finderGroupFinder

copyGroupCopy
gsh
gsh template execGshTemplateExec
Http

GrouperHttpClient
Ldap
ldap session utilsLdapSessionUtils
Member
finderMemberFinder
Membership
insert / update / deleteMembershipSave

finderMembershipFinder
Password
insert / update / deleteGrouperPasswordSave
Privilege inheritance

Attribute definitionsinsert / update / deletePrivilegeAttributeDefInheritanceSave
Foldersinsert / update / deletePrivilegeStemInheritanceSave
Groupsinsert / update / deletePrivilegeGroupInheritanceSave
Provisionable


FoldersfinderProvisionableStemFinder
insert / update / deleteProvisionableStemSave
Groups

finderProvisionableGroupFinder
insert / update / deleteProvisionableGroupSave
Stem
insert/update/deleteStemSave

finderStemFinder

copyStemCopy
Subject
finderSubjectFinder
Sync data to SQL table

GcTableSyncFromData
TypesFoldersfinderGdgTypeStemFinder
insert / update / deleteGdgTypeStemSave
GroupsfinderGdgTypeGroupFinder
insert / update / deleteGdgTypeGroupSave

GrouperShell (gsh)

gsh is a command line shell for administering and interacting with the Grouper API. See architectural diagram.  It can be used in both a batch and interactive manner.  For Grouper 2.3.0 patch 72+, it is built on GroovyShell.  For older versions of Grouper, it is built on Java BeanShell.  The legacy BeanShell version is now deprecated, but you can switch back to it by using one of the options:

  • Setting gsh.useLegacy = true in grouper.properties.
  • Using a command line argument  (gsh.sh -forceLegacyGsh)

GrouperShell is for Grouper admins.  End users can script with the grouper client command line utility

JEXL hints and tricks

Hints and tricks

Escape things in Escape things in groovysh with single backslash.  e.g.

...

Code Block
FROM
Object[] row = new Object[] {emailFromOutsystems, pennkeyPerhaps};

TO
Object[] row = new Object[2];
row[0] = emailFromOutsystems;
row[1] = pennkeyPerhaps;

API Compability

Reset the shell after an error: 

:c

Escape dollars, e.g. "${something}"

Code Block
'$' + "{something}"

Externalized text

Code Block
if you add to externalized text (config in ui), just make a key, e.g. mySchoolEmailKey, then refer to it like this
import edu.internet2.middleware.grouper.cfg.text.GrouperTextContainer;
String template = GrouperTextContainer.textOrNull("mySchoolEmailKey");


API Compability

gsh is now gsh is now a core part of the Grouper API and so is always compatible with the current release.

...

 For more information, see Bad Membership Finder Utility

Command

Description

findBadMemberships()

complete findBadMemberships run


Grouper export to GSH script

See page: Grouper export to a GSH script

XML legacy

Command

Description

xmlFromFile(filename)

Load registry from XML in file

xmlFromString(xml)

Load registry from XML in string

xmlFromURL(url)

Load registry from XML at URL

xmlToFile(filename)

Exports registry to file

xmlToString()

Exports registry to string.

xmlUpdateFromFile(filename)

Update registry from XML in file

xmlUpdateFromString(xml)

Update registry from XML in string

xmlUpdateFromURL(url)

Update registry from XML at URL

...

Code Block
GrouperSession.startRootSession();
edu.internet2.middleware.grouper.app.loader.GrouperLoader.scheduleJobs();

Loader

Enable a job (OTHER_JOB_grouperLoaderJexlScriptFullSync is the job name)

Code Block
edu.internet2.middleware.grouper.app.loader.GrouperLoader.schedulerFactory().getScheduler().resumeJob(new org.quartz.JobKey("OTHER_JOB_grouperLoaderJexlScriptFullSync"));


Loader

Above, it describes how you can kick off the loader in daemon mode.  You can also execute one job with:

...

You can also encrypt the password outside of GSH:

No Format
C:\mchyzer\isc\dev\grouper-qs-1.2.0\grouper>javajava -jarcp lib\morphString.jar
Enter the location of morphString.properties: conf/morphString.properties"lib/*:classes" edu.internet2.middleware.morphString.Encrypt
Type the string to encrypt (note: pasting might echo it back):               
The encrypted string is: ca8a15be4ad0fb45c6f1b3ca0cfd9c9e

...

See the WIKI for running the Grouper Report manually

Create a script from SQL

Here is an example to remove access from someone...  run a SQL to generate a GSH script, e.g. in oracle:

Code Block
set linesize 1000;
set pagesize 1000;
select 'delMember("' || gmlv.GROUP_NAME || '", "' || gmlv.SUBJECT_ID || '");' as script
from grouper_memberships_lw_v gmlv where subject_id = '12345678' and gmlv.LIST_NAME = 'members';

Put that script in a text editor and remove extra whitespace (probably optional), and add this to the beginning:

Code Block
grouperSession = GrouperSession.startRootSession();

Look at it and remove lines that dont apply...  then run in GSH

Code Block
[appadmin@lorenzo bin]$ ./gsh.sh remove.script

Here is a more complicated example.  I want all groups in a certain folder which do not have an ADMIN privilege assigned to my application service principal, to assign that privilege.  Here is the query for oracle:

Code Block
select 'grantPriv("' || gg.name || '", "someid/server.school.edu", AccessPrivilege.ADMIN);' as script 
from grouper_groups gg where gg.name like 'school:apps:appName:spaces:%' 
and not exists
(select (1) from grouper_memberships_lw_v gmlv where gg.name = gmlv.group_name and list_name = 'admins' 
and gmlv.subject_id = 'someid/server.school.edu');

Here is an example of deleting memberships for a user in oracle, dont forget at top of script to add grouperSession = GrouperSession.startRootSession():

Code Block
set linesize 1000;
set pagesize 1000;
select 'delMember("' || gg.name || '", "' || gm.subject_id || '");'
  as script
from grouper_memberships_all_v gmav, grouper_fields gf, grouper_groups gg, grouper_members gm
where GMAV.FIELD_ID = GF.ID and gm.subject_id = '12345678' and GF.name = 'members'
and GMAV.OWNER_GROUP_ID = gg.ID and GMAV.MEMBER_ID = GM.ID and GMAV.DEPTH = 0

Here is an example of removing privileges from a user on groups in oracle, dont forget at top of script to add grouperSession = GrouperSession.startRootSession():

Code Block
set linesize 1000;
set pagesize 1000;
select 'revokePriv("' || gmlv.group_name || '", "' || gmlv.subject_id || '", AccessPrivilege.' ||
case
when gmlv.LIST_NAME = 'admins' then 'ADMIN'
when gmlv.LIST_NAME = 'readers' then 'READ'
when gmlv.LIST_NAME = 'viewers' then 'VIEW'
when gmlv.LIST_NAME = 'updaters' then 'UPDATE'
when gmlv.LIST_NAME = 'optins' then 'OPTIN'
when gmlv.LIST_NAME = 'optouts' then 'OPTOUT'
else gmlv.LIST_NAME
end  || ');'
  as script
from grouper_memberships_lw_v gmlv where subject_id = '12345678' and GMLV.LIST_TYPE = 'access'

External systems

Test all external systems

Code Block
import java.util.List;

import edu.internet2.middleware.grouper.app.externalSystem.GrouperExternalSystem;
import edu.internet2.middleware.grouper.app.gsh.template.GshTemplateOutput;
import edu.internet2.middleware.grouper.app.gsh.template.GshTemplateV2;
import edu.internet2.middleware.grouper.app.gsh.template.GshTemplateV2input;
import edu.internet2.middleware.grouper.app.gsh.template.GshTemplateV2output;
import edu.internet2.middleware.grouper.util.GrouperUtil;

public class Test77externalSystemTest extends GshTemplateV2 {

  @Override
  public void gshRunLogic(GshTemplateV2input gshTemplateV2input, GshTemplateV2output gshTemplateV2output) {

    GshTemplateOutput gsh_builtin_gshTemplateOutput = gshTemplateV2output.getGsh_builtin_gshTemplateOutput();

    gsh_builtin_gshTemplateOutput.assignRedirectToGrouperOperation("NONE");

    List<GrouperExternalSystem> grouperExternalSystems = GrouperExternalSystem.retrieveAllGrouperExternalSystems();
    
    for (GrouperExternalSystem grouperExternalSystem : grouperExternalSystems) {
      try {
        List<String> errors = grouperExternalSystem.test();
        if (GrouperUtil.length(errors) == 0) {
          gsh_builtin_gshTemplateOutput.addOutputLine("Success: extenal system '" + grouperExternalSystem.getConfigId() + "' passed its test");
          continue;
        }
        for (String error : errors) {
          gsh_builtin_gshTemplateOutput.addOutputLine("error", "Error: extenal system '" + grouperExternalSystem.getConfigId() + "': " + error);
        }
      } catch (Exception e) {
        gsh_builtin_gshTemplateOutput.addOutputLine("error", "Error: extenal system '" + grouperExternalSystem.getConfigId() + "' failed: " + e.getMessage());
      }
    }
    
  }

}
 


Create a script from SQL

Here is an example to remove access from someone...  run a SQL to generate a GSH script, e.g. in oracleThis oracle script will remove privileges on folders for a certain user, dont forget at top of script to add grouperSession = GrouperSession.startRootSession():

Code Block
set linesize 1000;
set pagesize 1000;
select 'revokePrivdelMember("' || gsgmlv.nameGROUP_NAME || '", "' || gmgmlv.subjectSUBJECT_idID || '", NamingPrivilege.' ||
case
when gf.NAME = 'stemmers' then 'STEM'
when gf.NAME = 'creators' then 'CREATE'
else gf.NAME
end  || ');'
  as script
from grouper_memberships_all_v gmav, grouper_fields gf, grouper_stems gs, grouper_members gm
where GMAV.FIELD_ID = GF.ID and gm.subject_id = '12345678' and GF.type = 'naming'
and GMAV.OWNER_STEM_ID = GS.ID and GMAV.MEMBER_ID = GM.ID

Example of copying memberships and enabled/disabled dates from one group to another (postgres/oracle)

);' as script
from grouper_memberships_lw_v gmlv where subject_id = '12345678' and gmlv.LIST_NAME = 'members';

Put that script in a text editor and remove extra whitespace (probably optional), and add this to the beginning:

Code Block
grouperSession = GrouperSession.startRootSession();

Look at it and remove lines that dont apply...  then run in GSH

Code Block
[appadmin@lorenzo bin]$ ./gsh.sh remove.script

Here is a more complicated example.  I want all groups in a certain folder which do not have an ADMIN privilege assigned to my application service principal, to assign that privilege.  Here is the query for oracle:

Code Block
select 'grantPriv
Code Block
select 'new MembershipSave().assignGroupName("test:testGroup2").assignMemberId("' || gmgg.member_idname || '", "someid/server.school.edu", AccessPrivilege.ADMIN);'
 as || (case when gm.enabled_timestamp is not null then '.assignImmediateMshipEnabledTime(' || cast(gm.enabled_timestamp as varchar) || 'L)' else '' end)
  || (case when gm.disabled_timestamp is not null then '.assignImmediateMshipDisabledTime(' || cast(gm.disabled_timestamp as varchar) || 'L)' else '' end)
  || '.save();' as script
  from grouper_memberships gmscript 
from grouper_groups gg where gg.name like 'school:apps:appName:spaces:%' 
and not exists
(select (1) from grouper_memberships_lw_v gmlv where gg.name = gmlv.group_name and list_name = 'admins' 
and gmlv.subject_id = 'someid/server.school.edu');

Here is an example of deleting memberships for a user in oracle, dont forget at top of script to add grouperSession = GrouperSession.startRootSession():

Code Block
set linesize 1000;
set pagesize 1000;
select 'delMember("' || gg.name || '", "' || gm.subject_id || '");'
  as script
from grouper_memberships_all_v gmav, grouper_fields gf, grouper_groups gg, grouper_fieldsmembers gfgm
where gmGMAV.fieldFIELD_idID = gfGF.idID and gm.ownersubject_group_id = gg.id 
'12345678' and gfGF.name = 'members'
and GMAV.OWNER_GROUP_ID = gg.ID and gg.name GMAV.MEMBER_ID = GM.ID and GMAV.DEPTH = 'test:testGroup1'

Attribute framework

Create a permission and configure action list:

...

0

Here is an example of removing privileges from a user on groups in oracle, dont forget at top of script to add grouperSession = GrouperSession.startRootSession():

Code Block
set linesize 1000;
attributeDefset = new AttributeDefSave(grouperSession).assignName("stem2:sub:c").assignToEffMembership(true).assignToGroup(true).assignAttributeDefType(AttributeDefType.perm).assignCreateParentStemsIfNotExist(true).save();
attributeDef.getAttributeDefActionDelegate().configureActionList("read,write");

Retrieve assignments for the attribute "school:attr:students:artsAndSciences"

Code Block
attributeDefName = AttributeDefNameFinder.findByName("school:attr:students:artsAndSciences", true);
group.getAttributeDelegate().retrieveAssignments(attributeDefName);

...

The following script will print to standard output (not saved as files) two scripts.

  • One to disable all loader jobs (AKA: "DISABLE ALL SCHEDULES").
  • A second one to re-enabled  them (AKA: "RESTORE OLD SCHEDULES") .

  Note: The disableLoaders.gsh script does not change the state of the loader jobs. Rather it only prints (outputs) GSH scripts that you can later execute to do disable/enable for the jobs on the system at the time.

  Note: After running either of the scripts that are output, you need to restart all grouper daemon instances to make the changes effective.( So you might choose to stop them before running the "DISABLE" or "RESTORE" script.That order is not strictly required.)

  Note well: The method used to "disable" the jobs is to alter the quartz schedule for the job to be a fixed time in the distant future. ( specifically: "0 0 0 1 1 ? 3000" ) So the "RESTORE OLD SCHEDULES" script is the only record of what the orginal scheduled values were. Don't lose it.

...

pagesize 1000;
select 'revokePriv("' || gmlv.group_name || '", "' || gmlv.subject_id || '", AccessPrivilege.' ||
case
when gmlv.LIST_NAME = 'admins' then 'ADMIN'
when gmlv.LIST_NAME = 'readers' then 'READ'
when gmlv.LIST_NAME = 'viewers' then 'VIEW'
when gmlv.LIST_NAME = 'updaters' then 'UPDATE'
when gmlv.LIST_NAME = 'optins' then 'OPTIN'
when gmlv.LIST_NAME = 'optouts' then 'OPTOUT'
else gmlv.LIST_NAME
end  || ');'
  as script
from grouper_memberships_lw_v gmlv where subject_id = '12345678' and GMLV.LIST_TYPE = 'access'

This oracle script will remove privileges on folders for a certain user, dont forget at top of script to add grouperSession = GrouperSession.startRootSession():

Code Block
set linesize 1000;
set pagesize 1000;
select 'revokePriv("' || gs.name || '", "' || gm.subject_id || '", NamingPrivilege.' ||
case
when gf.NAME = 'stemmers' then 'STEM'
when gf.NAME = 'creators' then 'CREATE'
else gf.NAME
end  || ');'
  as script
from grouper_memberships_all_v gmav, grouper_fields gf, grouper_stems gs, grouper_members gm
where GMAV.FIELD_ID = GF.ID and gm.subject_id = '12345678' and GF.type = 'naming'
and GMAV.OWNER_STEM_ID = GS.ID and GMAV.MEMBER_ID = GM.ID

Example of copying memberships and enabled/disabled dates from one group to another (postgres/oracle)

Code Block
select 'new MembershipSave().assignGroupName("test:testGroup2").assignMemberId("' || gm.member_id || '")'
  || (case when gm.enabled_timestamp is not null then '.assignImmediateMshipEnabledTime(' || cast(gm.enabled_timestamp as varchar) || 'L)' else '' end)
  || (case when gm.disabled_timestamp is not null then '.assignImmediateMshipDisabledTime(' || cast(gm.disabled_timestamp as varchar) || 'L)' else '' end)
  || '.save();' as script
  from grouper_memberships gm, grouper_groups gg, grouper_fields gf
where gm.field_id = gf.id and gm.owner_group_id = gg.id 
and gf.name = 'members' and gg.name = 'test:testGroup1'


Attribute framework

Create a permission and configure action list:

Code Block
grouperSession = GrouperSession.startRootSession();
attributeDef = new AttributeDefSave(grouperSession).assignName("stem2:sub:c").assignToEffMembership(true).assignToGroup(true).assignAttributeDefType(AttributeDefType.perm).assignCreateParentStemsIfNotExist(true).save();
attributeDef.getAttributeDefActionDelegate().configureActionList("read,write");

Retrieve assignments for the attribute "school:attr:students:artsAndSciences"

Code Block
attributeDefName = AttributeDefNameFinder.findByName("school:attr:students:artsAndSciences", true);
group.getAttributeDelegate().retrieveAssignments(attributeDefName);


Anchor
disableLoaders
disableLoaders
disableLoaders.gsh ( disableLoaders.gsh ) 

The following script will print to standard output (not saved as files) two scripts.

  • One to disable all loader jobs (AKA: "DISABLE ALL SCHEDULES").
  • A second one to re-enabled  them (AKA: "RESTORE OLD SCHEDULES") .

  Note: The disableLoaders.gsh script does not change the state of the loader jobs. Rather it only prints (outputs) GSH scripts that you can later execute to do disable/enable for the jobs on the system at the time.

  Note: After running either of the scripts that are output, you need to restart all grouper daemon instances to make the changes effective.( So you might choose to stop them before running the "DISABLE" or "RESTORE" script.That order is not strictly required.)

  Note well: The method used to "disable" the jobs is to alter the quartz schedule for the job to be a fixed time in the distant future. ( specifically: "0 0 0 1 1 ? 3000" ) So the "RESTORE OLD SCHEDULES" script is the only record of what the orginal scheduled values were. Don't lose it.


Note this works in the new GSH.  To use in legacy GSH, take the set verbosity away...

Code Block
languagegroovy
titledisableLoaders.gsh
:set verbosity QUIET
grouperSession = GrouperSession.startRootSession();
sqlLoaderDefName = AttributeDefNameFinder.findByName("etc:legacy:attribute:legacyGroupType_grouperLoader", true);
sqlLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron", true);
ldapLoaderDefName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdap", true);
ldapLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron", true);
result = new StringBuilder();
result.append("\n\n############  RESTORE OLD SCHEDULES, BOUNCE GROUPER DAEMONS AFTERWARDS  #############\n\ngrouperSession = GrouperSession.startRootSession();\n");
result.append("sqlLoaderDefName = AttributeDefNameFinder.findByName(\"etc:legacy:attribute:legacyGroupType_grouperLoader\", true);\n");
result.append("sqlLoaderDefScheduleName = AttributeDefNameFinder.findByName(\"etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron\", true);\n");
result.append("ldapLoaderDefName = AttributeDefNameFinder.findByName(\"etc:attribute:loaderLdap:grouperLoaderLdap\", true);\n");
result.append("ldapLoaderDefScheduleName = AttributeDefNameFinder.findByName(\"etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron\", true);\n");
attributeAssigns = GrouperDAOFactory.getFactory().getAttributeAssign().findAttributeAssignments(AttributeAssignType.group, null, sqlLoaderDefName.getId(), null, null, null, null, null, true, false);
for (AttributeAssign attributeAssign : attributeAssigns) {result.append("group = GroupFinder.findByName(grouperSession, \"" + attributeAssign.getOwnerGroup().getName() + "\");\nattributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, sqlLoaderDefName, false, false);\nattributeAssignOnAssign.getAttributeValueDelegate().assignValueString(\"" + sqlLoaderDefScheduleName.getName() + "\", \"" + attributeAssign.getAttributeValueDelegate().retrieveValueString(sqlLoaderDefScheduleName.getName()) + "\");\n"); }
attributeAssigns = GrouperDAOFactory.getFactory().getAttributeAssign().findAttributeAssignments(AttributeAssignType.group, null, ldapLoaderDefName.getId(), null, null, null, null, null, true, false);
for (AttributeAssign attributeAssign : attributeAssigns) {result.append("group = GroupFinder.findByName(grouperSession, \"" + attributeAssign.getOwnerGroup().getName() + "\");\nattributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, ldapLoaderDefName, false, false);\nattributeAssignOnAssign.getAttributeValueDelegate().assignValueString(\"" + ldapLoaderDefScheduleName.getName() + "\", \"" + attributeAssign.getAttributeValueDelegate().retrieveValueString(ldapLoaderDefScheduleName.getName()) + "\");\n"); }
Code Block
languagegroovy
titledisableLoaders.gsh
:set verbosity QUIET
grouperSession = GrouperSession.startRootSession();
sqlLoaderDefName = AttributeDefNameFinder.findByName("etc:legacy:attribute:legacyGroupType_grouperLoader", true);
sqlLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron", true);
ldapLoaderDefName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdap", true);
ldapLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron", true);
result = new StringBuilder();
result.append("\n\n############  RESTOREDISABLE OLDALL SCHEDULES, BOUNCE GROUPER DAEMONS AFTERWARDS  #############\n\ngrouperSession = GrouperSession.startRootSession();\n");
result.append("sqlLoaderDefName = AttributeDefNameFinder.findByName(\"etc:legacy:attribute:legacyGroupType_grouperLoader\", true);\n");
result.append("sqlLoaderDefScheduleName = AttributeDefNameFinder.findByName(\"etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron\", true);\n");
result.append("ldapLoaderDefName = AttributeDefNameFinder.findByName(\"etc:attribute:loaderLdap:grouperLoaderLdap\", true);\n");
result.append("ldapLoaderDefScheduleName = AttributeDefNameFinder.findByName(\"etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron\", true);\n");
attributeAssigns = GrouperDAOFactory.getFactory().getAttributeAssign().findAttributeAssignments(AttributeAssignType.group, null, sqlLoaderDefName.getId(), null, null, null, null, null, true, false);
for (AttributeAssign attributeAssign : attributeAssigns) {result.append("group = GroupFinder.findByName(grouperSession, \"" + attributeAssign.getOwnerGroup().getName() + "\");\nattributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, sqlLoaderDefName, false, false);\nattributeAssignOnAssign.getAttributeValueDelegate().assignValueString(\"" + sqlLoaderDefScheduleName.getName() + "\", \"" + attributeAssign.getAttributeValueDelegate().retrieveValueString(sqlLoaderDefScheduleName.getName()) + "0 0 0 1 1 ? 3000\");\n"); }
attributeAssigns = GrouperDAOFactory.getFactory().getAttributeAssign().findAttributeAssignments(AttributeAssignType.group, null, ldapLoaderDefName.getId(), null, null, null, null, null, true, false);
for (AttributeAssign attributeAssign : attributeAssigns) {result.append("group = GroupFinder.findByName(grouperSession, \"" + attributeAssign.getOwnerGroup().getName() + "\");\nattributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, ldapLoaderDefName, false, false);\nattributeAssignOnAssign.getAttributeValueDelegate().assignValueString(\"" + ldapLoaderDefScheduleName.getName() + "\", \"" + attributeAssign.getAttributeValueDelegate().retrieveValueString(ldapLoaderDefScheduleName.getName()) + "\");\n"); }
result.append("\n\n############  DISABLE ALL SCHEDULES, BOUNCE GROUPER DAEMONS AFTERWARDS  #############\n\ngrouperSession;\nattributeAssignOnAssign = GrouperSessiongroup.startRootSessiongetAttributeDelegate();\n");
result.append("sqlLoaderDefName = AttributeDefNameFinder.findByName(\"etc:legacy:attribute:legacyGroupType_grouperLoader\", true.retrieveAssignment(null, ldapLoaderDefName, false, false);\nattributeAssignOnAssign.getAttributeValueDelegate().assignValueString(\"" + ldapLoaderDefScheduleName.getName() + "\", \"0 0 0 1 1 ? 3000\");\n"); }
System.out.println(result.append("sqlLoaderDefScheduleName = AttributeDefNameFinder.findByName(\"etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron\", true);\n");
result.append("ldapLoaderDefName = AttributeDefNameFinder.findByName(\"etc:attribute:loaderLdap:grouperLoaderLdap\", true);\n");
result.append("ldapLoaderDefScheduleName);

Example: was run against a server with two jobs that are both scheduled to run at "0 0 * * * ?" .

Code Block
languagebash
titleExample of running disableLoaders.gsh
[appadmin@i2midev6 bin]$ ./gsh disableLoaders.gsh 

############  RESTORE OLD SCHEDULES, BOUNCE GROUPER DAEMONS AFTERWARDS  #############

grouperSession = GrouperSession.startRootSession();
sqlLoaderDefName = AttributeDefNameFinder.findByName(\"etc:legacy:attribute:loaderLdap:grouperLoaderLdapQuartzCron\", true);\n");
attributeAssigns = GrouperDAOFactory.getFactory().getAttributeAssign().findAttributeAssignments(AttributeAssignType.group, null, sqlLoaderDefName.getId(), null, null, null, null, null, true, false);
for (AttributeAssign attributeAssign : attributeAssigns) {result.append("group = GroupFinder.findByName(grouperSession, \"" + attributeAssign.getOwnerGroup().getName() + "\");\nattributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, sqlLoaderDefName, false, false);\nattributeAssignOnAssign.getAttributeValueDelegate().assignValueString(\"" + sqlLoaderDefScheduleName.getName() + "\", \"0 0 0 1 1 ? 3000\");\n"); }
attributeAssigns = GrouperDAOFactory.getFactory().getAttributeAssign().findAttributeAssignments(AttributeAssignType.group, null, ldapLoaderDefName.getId(), null, null, null, null, null, true, false);
for (AttributeAssign attributeAssign : attributeAssigns) {result.append("legacyGroupType_grouperLoader", true);
sqlLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron", true);
ldapLoaderDefName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdap", true);
ldapLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron", true);
group = GroupFinder.findByName(grouperSession, "nyu_apereo:presenter:allStevens3");
attributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, sqlLoaderDefName, false, false);
attributeAssignOnAssign.getAttributeValueDelegate().assignValueString("etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron", "0 0 * * * ?");
group = GroupFinder.findByName(grouperSession, \"" + attributeAssign.getOwnerGroup().getName() + "\");\nattributeAssignOnAssigntest:loader:testLdapGroupList");
attributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, ldapLoaderDefName, false, false);\nattributeAssignOnAssign
attributeAssignOnAssign.getAttributeValueDelegate().assignValueString(\"" + ldapLoaderDefScheduleName.getName() + "\", \"etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron", "0 0 0* 1* 1* ? 3000\");\n"); }
System.out.println(result);

Example: was run against a server with two jobs that are both scheduled to run at "0 0 * * * ?" .

Code Block
languagebash
titleExample of running disableLoaders.gsh
[appadmin@i2midev6 bin]$ ./gsh disableLoaders.gsh 

############  RESTOREDISABLE OLDALL SCHEDULES, BOUNCE GROUPER DAEMONS AFTERWARDS  #############

grouperSession = GrouperSession.startRootSession();
sqlLoaderDefName = AttributeDefNameFinder.findByName("etc:legacy:attribute:legacyGroupType_grouperLoader", true);
sqlLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron", true);
ldapLoaderDefName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdap", true);
ldapLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron", true);
group = GroupFinder.findByName(grouperSession, "nyu_apereo:presenter:allStevens3");
attributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, sqlLoaderDefName, false, false);
attributeAssignOnAssign.getAttributeValueDelegate().assignValueString("etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron", "0 0 *0 *1 *1 ? 3000");
group = GroupFinder.findByName(grouperSession, "test:loader:testLdapGroupList");
attributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, ldapLoaderDefName, false, false);
attributeAssignOnAssign.getAttributeValueDelegate().assignValueString("etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron", "0 0 *0 *1 *1 ? 3000");


############  DISABLE ALL SCHEDULES, BOUNCE GROUPER DAEMONS AFTERWARDS  #############


Rules

In Grouper 2.3 the UI can delete inherited privileges rules.

To delete a rule, find it in the database in grouper_rules_v.  Get the attributeAssignId

Code Block
GrouperSession grouperSession = GrouperSession.startRootSession();
sqlLoaderDefNameAttributeAssign attributeAssign = AttributeDefNameFinderAttributeAssignFinder.findByNamefindById("etc:legacy:attribute:legacyGroupType_grouperLoaderb629bd8170964663be507968752f4f17", true);
sqlLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron", true);
ldapLoaderDefName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdap", true);
ldapLoaderDefScheduleName = AttributeDefNameFinder.findByName("etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron", true);
group = GroupFinder.findByName(grouperSession, "nyu_apereo:presenter:allStevens3");
attributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, sqlLoaderDefName, false, false);
attributeAssignOnAssign.getAttributeValueDelegate().assignValueString("etc:legacy:attribute:legacyAttribute_grouperLoaderQuartzCron", "0 0 0 1 1 ? 3000");
group = GroupFinder.findByName(grouperSession, "test:loader:testLdapGroupList");
attributeAssignOnAssign = group.getAttributeDelegate().retrieveAssignment(null, ldapLoaderDefName, false, false);
attributeAssignOnAssign.getAttributeValueDelegate().assignValueString("etc:attribute:loaderLdap:grouperLoaderLdapQuartzCron", "0 0 0 1 1 ? 3000");


Rules

In Grouper 2.3 the UI can delete inherited privileges rules.

To delete a rule, find it in the database in grouper_rules_v.  Get the attributeAssignId

Code Block
GrouperSession grouperSession = GrouperSession.startRootSession();
AttributeAssign attributeAssign = AttributeAssignFinder.findById("b629bd8170964663be507968752f4f17", true);
attributeAssign.delete();

NOTE: You can also use the AttributeAssignFinder.findById(String id, boolean exceptionIfNull)  to find attribute assignments from the logs too.
Example log "ERROR RuleEngine$3.callback(560) - - Error with daemon on rule: attributeAssignTypeId: 3d6ccb6c5a584f32919682ae154c0523". id="3d6ccb6c5a584f32919682ae154c0523". The returned AttributeAssign object will show you the stem/group that the attribute is attached to. (smile)

Grouper Builtin Messaging

attributeAssign.delete();

NOTE: You can also use the AttributeAssignFinder.findById( String id, boolean exceptionIfNull)  to find attribute assignments from the logs too.
Example log "ERROR RuleEngine$3.callback(560) - - Error with daemon on rule: attributeAssignTypeId: 3d6ccb6c5a584f32919682ae154c0523". id="3d6ccb6c5a584f32919682ae154c0523". The returned AttributeAssign object will show you the stem/group that the attribute is attached to. (smile)

Grouper Builtin Messaging

Create queues / topics, assign privileges for Grouper builtin messaging (not activemq, rabbitmq, AWS, etc) (Grouper 2.3+)

Code Block
grouperSession = GrouperSession.startRootSession();
 
// create objects
GrouperBuiltinMessagingSystem.createQueue("abc");
GrouperBuiltinMessagingSystem.createTopic("def");


// delete objects
GrouperBuiltinMessagingSystem.deleteQueue("abc");
GrouperBuiltinMessagingSystem.deleteTopic("def"); 

// permissions on objects
GrouperBuiltinMessagingSystem.allowSendToQueue("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.allowSendToTopic("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.allowReceiveFromQueue("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.disallowSendToQueue("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.disallowSendToTopic("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.disallowReceiveFromQueue("abc", SubjectTestHelper.SUBJ0);

// topics send to queues
GrouperBuiltinMessagingSystem.topicAddSendToQueue("def", "abc");
Collection<String> queues = GrouperBuiltinMessagingSystem.queuesTopicSendsTo("def");
GrouperBuiltinMessagingSystem.topicRemoveSendToQueue("def", "abc");


Grouper messaging 

Send, receive, acknowledge messages in any message system (Grouper builtin, activeMQ, rabbitmq, AWS, etc) Create queues / topics, assign privileges for Grouper builtin messaging (not activemq, rabbitmq, AWS, etc)  (Grouper 2.3+)

Code Block
//note, or whatever user should be sending the messages
grouperSession = GrouperSession.startRootSession();
 
//send createmessage to objects
GrouperBuiltinMessagingSystem.createQueue("abc");
GrouperBuiltinMessagingSystem.createTopic("def")queue
GrouperMessagingEngine.send(new GrouperMessageSendParam().assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME).assignQueueType(GrouperMessageQueueType.queue).assignQueueOrTopicName("queueName").addMessageBody("Some message body"));


// delete objects
GrouperBuiltinMessagingSystem.deleteQueue("abc");
GrouperBuiltinMessagingSystem.deleteTopic("def"); send message to topic
GrouperMessagingEngine.send(new GrouperMessageSendParam().assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME).assignQueueType(GrouperMessageQueueType.topic).assignQueueOrTopicName("queueName").addMessageBody("Some message body"));


//receive permissions on objects
GrouperBuiltinMessagingSystem.allowSendToQueue("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.allowSendToTopic("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.allowReceiveFromQueue("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.disallowSendToQueue("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.disallowSendToTopic("abc", SubjectTestHelper.SUBJ0);
GrouperBuiltinMessagingSystem.disallowReceiveFromQueue("abc", SubjectTestHelper.SUBJ0);

// topics send to queues
GrouperBuiltinMessagingSystem.topicAddSendToQueue("def", "abc");
Collection<String> queues = GrouperBuiltinMessagingSystem.queuesTopicSendsTo("def");
GrouperBuiltinMessagingSystem.topicRemoveSendToQueue("def", "abc");


Grouper messaging 

Send, receive, acknowledge messages in any message system (Grouper builtin, activeMQ, rabbitmq, AWS, etc) (Grouper 2.3+)

Code Block
//note, or whatever user should be sending the messages
grouperSession = GrouperSession.startRootSession();
 
//send message to queue
GrouperMessagingEngine.send(new GrouperMessageSendParam().assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME).assignQueueType(GrouperMessageQueueType.queue).assignQueueOrTopicName("queueName").addMessageBody("Some message body"));


//send message to topic
GrouperMessagingEngine.send(new GrouperMessageSendParam(messages
GrouperMessageReceiveResult grouperMessageReceiveResult = GrouperMessagingEngine.receive(new GrouperMessageReceiveParam().assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME).assignQueueName(queueName));


Collection<GrouperMessage> grouperMessages = grouperMessageReceiveResult.getGrouperMessages();


//acknowledge message as processed
GrouperMessagingEngine.acknowledge(new GrouperMessageAcknowledgeParam().assignAcknowledgeType(GrouperMessageAcknowledgeType.mark_as_processed).assignQueueName("abc").addGrouperMessage(grouperMessage).assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME));
 
//acknowledge message as return to queue (receive next time ask for messages)
GrouperMessagingEngine.acknowledge(new GrouperMessageAcknowledgeParam().assignAcknowledgeType(GrouperMessageAcknowledgeType.return_to_queue).assignQueueName("abc").addGrouperMessage(grouperMessage).assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME));

//acknowledge message as return to queue (receive after other messages on the queue)
GrouperMessagingEngine.acknowledge(new GrouperMessageAcknowledgeParam().assignAcknowledgeType(GrouperMessageAcknowledgeType.return_to_end_of_queue).assignQueueName("abc").addGrouperMessage(grouperMessage).assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME));
 
//acknowledge message send to another queue or topic (e.g. dead letter queue, dlq)
GrouperMessagingEngine.acknowledge(new GrouperMessageAcknowledgeParam().assignAcknowledgeType(GrouperMessageAcknowledgeType.send_to_another_queue).assignQueueName("abc").addGrouperMessage(grouperMessage).assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME).assignQueueType(GrouperMessageQueueType.topicassignAnotherQueueParam(new GrouperMessageQueueParam().assignQueueOrTopicName("queueNamedlq").addMessageBody("Some message body"assignQueueType(GrouperMessageQueueType.queue));


//receive messages
GrouperMessageReceiveResult grouperMessageReceiveResult = GrouperMessagingEngine.receive(new GrouperMessageReceiveParam().assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME).assignQueueName(queueName));


Collection<GrouperMessage> grouperMessages = grouperMessageReceiveResult.getGrouperMessages();


//acknowledge message as processed
GrouperMessagingEngine.acknowledge(new GrouperMessageAcknowledgeParam().assignAcknowledgeType(GrouperMessageAcknowledgeType.mark_as_processed).assignQueueName("abc").addGrouperMessage(grouperMessage).assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME));
 
//acknowledge message as return to queue (receive next time ask for messages)
GrouperMessagingEngine.acknowledge(new GrouperMessageAcknowledgeParam().assignAcknowledgeType(GrouperMessageAcknowledgeType.return_to_queue).assignQueueName("abc").addGrouperMessage(grouperMessage).assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME));

//acknowledge message as return to queue (receive after other messages on the queue)
GrouperMessagingEngine.acknowledge(new GrouperMessageAcknowledgeParam().assignAcknowledgeType(GrouperMessageAcknowledgeType.return_to_end_of_queue).assignQueueName("abc").addGrouperMessage(grouperMessage).assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME));
 
//acknowledge message send to another queue or topic (e.g. dead letter queue, dlq)
GrouperMessagingEngine.acknowledge(new GrouperMessageAcknowledgeParam().assignAcknowledgeType(GrouperMessageAcknowledgeType.send_to_another_queue).assignQueueName("abc").addGrouperMessage(grouperMessage).assignGrouperMessageSystemName(GrouperBuiltinMessagingSystem.BUILTIN_NAME).assignAnotherQueueParam(new GrouperMessageQueueParam().assignQueueOrTopicName("dlq").assignQueueType(GrouperMessageQueueType.queue));


Expression language testing

Code Block
Set this in log4j.properties


log4j.logger.edu.internet2.middleware.grouper.util.GrouperUtil = DEBUG


Run GSH:


gsh 0% GrouperSession grouperSession = GrouperSession.startRootSession();
gsh 1% Group group = GroupFinder.findByName(grouperSession, "apps:loader");
gsh 2% Map variableMap =  new HashMap();
gsh 3% variableMap.put("theGroup", group);
gsh 4% String result = GrouperUtil.substituteExpressionLanguage("Name: ${theGroup.name}", variableMap);
gsh 5% result
Name: apps:loader

This is the log entry:

2018-06-04 22:32:58,197: [main] DEBUG GrouperUtil.substituteExpressionLanguage(9416) -  - Subsituting EL: 'Name: ${theGroup.name}', and with env vars: theGroup, grouperUtil with result: 'Name: apps:loader'


Example of attribute value assign to group and SQL query


Expression language testing


Code Block
Set this in log4j.properties


log4j.logger.edu.internet2.middleware.grouper.util.GrouperUtil = DEBUG


Run GSH:


gsh 0% GrouperSession grouperSession = GrouperSession.startRootSession();
gsh 1% Group group = GroupFinder.findByName(grouperSession, "apps:loader");
gsh 2% Map variableMap =  new HashMap();
gsh 3% variableMap.put("theGroup", group);
gsh 4% String result = GrouperUtil.substituteExpressionLanguage("Name: ${theGroup.name}", variableMap);
gsh 5% result
Name: apps:loader

This is the log entry:

2018-06-04 22:32:58,197: [main] DEBUG GrouperUtil.substituteExpressionLanguage(9416) -  - Subsituting EL: 'Name: ${theGroup.name}', and with env vars: theGroup, grouperUtil with result: 'Name: apps:loader'



Example of attribute value assign to group and SQL query

Code Block
gsh 0% GrouperSession grouperSession = GrouperSession.startRootSession();
gsh 1% AttributeDef attributeDef = new AttributeDefSave(grouperSession).assignName("test:testAttribute:someAttrDef").assignCreateParentStemsIfNotExist(true).assignToGroup(true).assignAttributeDefType(AttributeDefType.attr).assignMultiAssignable(false).assignMultiValued(false).assignValueType(AttributeDefValueType.string).save();
gsh 2% AttributeDefName attributeDefName = new AttributeDefNameSave(grouperSession, attributeDef).assignName("test:testAttribute:someAttr").assignCreateParentStemsIfNotExist(true).save();
gsh 3% Group group = new GroupSave(grouperSession).assignName("test:testAttribute:group").assignCreateParentStemsIfNotExist(true).save()
gsh 4% group.getAttributeValueDelegate().assignValueString(attributeDefName.getName(), "someValue");
edu.internet2.middleware.grouper.attr.value.AttributeValueResult: edu.internet2.middleware.grouper.attr.value.AttributeValueResult@2f08e6d3
gsh 5% HibernateSession.bySqlStatic().select(String.class, "SELECT value_string FROM grouper_aval_asn_group_v WHERE group_name = 'test:testAttribute:group' AND attribute_def_name_name = 'test:testAttribute:someAttr'");
someValue
gsh 6% 


Example of finding groups with a certain attribute value

Code Block
Code Block
gsh 0% GrouperSession grouperSession = GrouperSession.startRootSession();
gsh 1% AttributeDef attributeDefSet<Group> groups = new AttributeDefSaveGroupFinder(grouperSession).assignNameassignNameOfAttributeDefName("testbath:testAttribute:someAttrDefprovisionClass").assignCreateParentStemsIfNotExist(true).assignToGroup(true).assignAttributeDefType(AttributeDefType.attr).assignMultiAssignable(false).assignMultiValued(false).assignValueType(AttributeDefValueType.string).save();
gsh 2% AttributeDefName attributeDefName = new AttributeDefNameSave(grouperSession, attributeDef).assignName("test:testAttribute:someAttr").assignCreateParentStemsIfNotExist(true).save();
gsh 3% Group group = new GroupSave(grouperSession).assignName("test:testAttribute:group").assignCreateParentStemsIfNotExist(true).save()
gsh 4% group.getAttributeValueDelegate().assignValueString(attributeDefName.getName(), "someValue");
assignAttributeValue("groupmanager-groups")
       .assignPrivileges(AccessPrivilege.ATTRIBUTE_READ_PRIVILEGES).findGroups();


Example of finding groups with a certain attribute value on metadata assignments

This is useful for attestation and loader metadata, for example.

Code Block
//groups loaded by a particular group
def attrDef = AttributeDefNameFinder.findByName(GrouperCheckConfig.loaderMetadataStemName() + ":" + GrouperLoader.ATTRIBUTE_GROUPER_LOADER_METADATA_GROUP_ID, true)            
def groups = new GroupFinder().assignIdOfAttributeDefName(attrDef.id).assignAttributeValuesOnAssignment(GrouperUtil.toSetObjectType("3779b51223804784b4a02ee238b73079")).findGroups()

//    OR, without the extra attributeDef, look up the name directly in GroupFinder
def groups = new GroupFinder().assignNameOfAttributeDefName("etc:attribute:loaderMetadata:grouperLoaderMetadataGroupId").assignAttributeValuesOnAssignment(GrouperUtil.toSetObjectType("3779b51223804784b4a02ee238b73079")).findGroups()


//attestations that are due
import edu.internet2.middleware.grouper.attrapp.value.AttributeValueResult: edu.internet2.middleware.grouper.attr.value.AttributeValueResult@2f08e6d3
gsh 5%attestation.GrouperAttestationJob
def groups = new GroupFinder().assignIdOfAttributeDefName(GrouperAttestationJob.retrieveAttributeDefNameCalculatedDaysLeft().id).assignAttributeValuesOnAssignment(GrouperUtil.toSetObjectType("0")).findGroups()



Example of finding provisioning targets for PSPNG

Example of finding provisioning targets for PSPNG

Code Block
gsh 0% HibernateSession.bySqlStatic().selectlistSelect(String.class, "SELECT DISTINCT gaaa.value_string FROM grouper_avalattribute_asnassign_group_v WHERE group_name = 'test:testAttribute:group' AND value gaaa, grouper_attribute_assign gaa, grouper_attribute_def_name_name = 'test:testAttribute:someAttr'");
someValue
gsh 6% 

Example of finding groups with a certain attribute value

Code Block
GrouperSession grouperSession = GrouperSession.startRootSession();
Set<Group> groups = new GroupFinder().assignNameOfAttributeDefName("bath:provisionClass").assignAttributeValue("groupmanager-groups")
       .assignPrivileges(AccessPrivilege.ATTRIBUTE_READ_PRIVILEGES).findGroups();

Example of finding groups with a certain attribute value on metadata assignments

This is useful for attestation and loader metadata, for example.

Code Block
//groups loaded by a particular group
def attrDef = AttributeDefNameFinder.findByName(GrouperCheckConfig.loaderMetadataStemName() + ":" + GrouperLoader.ATTRIBUTE_GROUPER_LOADER_METADATA_GROUP_ID, true)            
def groups = new GroupFinder().assignIdOfAttributeDefName(attrDef.id).assignAttributeValuesOnAssignment(GrouperUtil.toSetObjectType("3779b51223804784b4a02ee238b73079")).findGroups()

//    OR, without the extra attributeDef, look up the name directly in GroupFinder
def groups = new GroupFinder().assignNameOfAttributeDefName("etc:attribute:loaderMetadata:grouperLoaderMetadataGroupId").assignAttributeValuesOnAssignment(GrouperUtil.toSetObjectType("3779b51223804784b4a02ee238b73079")).findGroups()


//attestations that are due
import edu.internet2.middleware.grouper.app.attestation.GrouperAttestationJob
def groups = new GroupFinder().assignIdOfAttributeDefName(GrouperAttestationJob.retrieveAttributeDefNameCalculatedDaysLeft().id).assignAttributeValuesOnAssignment(GrouperUtil.toSetObjectType("0")).findGroups()

Example of finding provisioning targets for PSPNG

Example of finding provisioning targets for PSPNG

Code Block
gsh 0% HibernateSession.bySqlStatic().listSelect(String.class, "SELECT DISTINCT gaaa.value_string FROM grouper_attribute_assign_value gaaa, grouper_attribute_assign gaa, grouper_attribute_def_name gadn WHERE gaaa.attribute_assign_id = gaa.id AND gaa.attribute_def_name_id = gadn.id AND gadn.extension IN ('provision_to', 'do_not_provision_to')", null, null);
java.util.ArrayList: [ad, ldap]

Example of finding which groups are provisioned to a certain target (from daemon where PSPNG is installed)

Code Block
provisioner_name="xyz"; // Whatever your provisioner is called in grouper_loader.properties
gs=GrouperSession.startRootSession();
provisioner=edu.internet2.middleware.grouper.pspng.ProvisionerFactory.createProvisioner(provisioner_name,false);
provisioner.getAllGroupsForProvisioner();

Long hand example of which groups are provisioned to a certain target

gadn WHERE gaaa.attribute_assign_id = gaa.id AND gaa.attribute_def_name_id = gadn.id AND gadn.extension IN ('provision_to', 'do_not_provision_to')", null, null);
java.util.ArrayList: [ad, ldap]

Example of finding which groups are provisioned to a certain target (from daemon where PSPNG is installed)

Code Block
provisioner_name="xyz"; // Whatever your provisioner is called in grouper_loader.properties
gs=GrouperSession.startRootSession();
provisioner=edu.internet2.middleware.grouper.pspng.ProvisionerFactory.createProvisioner(provisioner_name,false);
provisioner.getAllGroupsForProvisioner();

Long hand example of which groups are provisioned to a certain target

Code Block
    String provisionTarget = "ad";
    GrouperSession grouperSession = GrouperSession.startRootSession();
    
    Set stemsToProvisionToSet = HibernateSession.byHqlStatic().createQuery("select s from Stem s, AttributeAssign aa, AttributeDefName adn, AttributeAssignValue aav where s.id = aa.ownerStemId and aav.attributeAssignId = aa.id and aa.attributeDefNameId = adn.id and aa.attributeAssignTypeDb = 'stem' and aa.enabledDb = 'T' and adn.extensionDb = 'provision_to' and aav.valueString = '" + provisionTarget + "'").listSet(Stem.class);
    for (Object stemObject : stemsToProvisionToSet) { Stem stem = (Stem)stemObject; System.out.println("provision_to assigned to stem: " + stem.getName());  }
    Set stemsToNotProvisionToSet
Code Block
    String provisionTarget = "ad";
    GrouperSession grouperSession = GrouperSession.startRootSession();
    
    Set stemsToProvisionToSet = HibernateSession.byHqlStatic().createQuery("select s from Stem s, AttributeAssign aa, AttributeDefName adn, AttributeAssignValue aav where s.id = aa.ownerStemId and aav.attributeAssignId = aa.id and aa.attributeDefNameId = adn.id and aa.attributeAssignTypeDb = 'stem' and aa.enabledDb = 'T' and adn.extensionDb = 'do_not_provision_to' and aav.valueString = '" + provisionTarget + "'").listSet(Stem.class);
    for (Object stemObject : stemsToProvisionToSetstemsToNotProvisionToSet) { Stem stem = (Stem)stemObject; System.out.println("do_not_provision_to assigned to stem: " + stem.getName());  }
    Set stemsToNotProvisionToSetgroupsToProvisionToSet = HibernateSession.byHqlStatic().createQuery("select sg from StemGroup sg, AttributeAssign aa, AttributeDefName adn, AttributeAssignValue aav where sg.id = aa.ownerStemIdownerGroupId and aav.attributeAssignId = aa.id and aa.attributeDefNameId = adn.id and aa.attributeAssignTypeDb = 'stemgroup' and aa.enabledDb = 'T' and adn.extensionDb = 'do_not_provision_to' and aav.valueString = '" + provisionTarget + "'").listSet(Stem.class);
    for (Object stemObjectgroupObject : stemsToNotProvisionToSetgroupsToProvisionToSet) { StemGroup stemgroup = (StemGroup)stemObjectgroupObject; System.out.println("do_not_provision_to assigned to stemgroup: " + stemgroup.getName());  }
    Set groupsToProvisionToSetgroupsToNotProvisionToSet = HibernateSession.byHqlStatic().createQuery("select g from Group g, AttributeAssign aa, AttributeDefName adn, AttributeAssignValue aav where g.id = aa.ownerGroupId and aav.attributeAssignId = aa.id and aa.attributeDefNameId = adn.id and aa.attributeAssignTypeDb = 'group' and aa.enabledDb = 'T' and adn.extensionDb = 'do_not_provision_to' and aav.valueString = '" + provisionTarget + "'").listSet(Stem.class").listSet(Stem.class);
    for (Object groupObject : groupsToNotProvisionToSet) { Group group = (Group)groupObject; System.out.println("do_not_provision_to assigned to group: " + group.getName());  }
    Set allGroups = new LinkedHashSet();
    for (Object groupObject : groupsToProvisionToSet) { Group group = (Group)groupObject; System.out.println("provision_to assigned to group: " + group.getName());  }
    Set groupsToNotProvisionToSet = HibernateSession.byHqlStatic().createQuery("select g from Group g, AttributeAssign aa, AttributeDefName adn, AttributeAssignValue aav where g.id = aa.ownerGroupId and aav.attributeAssignId = aa.id and aa.attributeDefNameId = adn.id and aa.attributeAssignTypeDb = 'group' and aa.enabledDb = 'T' and adn.extensionDb = 'do_not_provision_to' and aav.valueString = '" + provisionTarget + "'").listSet(Stem.classSet allGroupsToProvision = new TreeSet();
    allGroupsToProvision.addAll(groupsToProvisionToSet);

    Set stemNamesToNotProvisionTo = new HashSet();
    Set stemNamesToProvisionTo = new HashSet();
    
    for (Object stemToProvision : stemsToProvisionToSet) { stemNamesToProvisionTo.add(((Stem)stemToProvision).getName()); }
    for (Object stemNotToProvision : stemsToNotProvisionToSet) { stemNamesToNotProvisionTo.add(((Stem)stemNotToProvision).getName()); }

    for (Object stemToProvision : stemsToProvisionToSet) { allGroups.addAll(((Stem)stemToProvision).getChildGroups(edu.internet2.middleware.grouper.Stem.Scope.SUB)); }
    
    Map groupToPaths = new HashMap();
    for (Object groupObject : groupsToNotProvisionToSetallGroups) { Group group = (Group)groupObject; System.out.println("do_not_provision_to assigned to group: " + group.getName());  }
    Set allGroups; if (allGroupsToProvision.contains(group)) {continue;} if (groupsToNotProvisionToSet.contains(group)) {continue;} List paths = new LinkedHashSetArrayList();
 groupToPaths.put(group, paths); String SetcurrentName allGroupsToProvision = new TreeSetgroup.getName();
    allGroupsToProvision.addAll(groupsToProvisionToSetpaths.add(currentName);

  while(true) { SetcurrentName stemNamesToNotProvisionTo = new HashSet(GrouperUtil.parentStemNameFromName(currentName);
  if  Set stemNamesToProvisionTo = new HashSet();(GrouperUtil.isBlank(currentName)) {break;} paths.add(currentName);  }   }
    
    for (Object stemToProvisiongroupObject : stemsToProvisionToSet) { stemNamesToProvisionTo.add(((Stem)stemToProvision).getNamegroupToPaths.keySet()); }
    for (Object stemNotToProvision : stemsToNotProvisionToSet) { stemNamesToNotProvisionTo.add(((Stem)stemNotToProvision).getName()); }

    {Group group = (Group)groupObject; List paths = (List)groupToPaths.get(group); for (Object stemToProvisionpathObject : stemsToProvisionToSetpaths) { allGroups.addAll(((Stem)stemToProvision).getChildGroups(edu.internet2.middleware.grouper.Stem.Scope.SUB)); }
    
    Map groupToPaths = new HashMap(); String path = (String)pathObject; if (stemNamesToProvisionTo.contains(path)) { allGroupsToProvision.add(group); break; } if (stemNamesToNotProvisionTo.contains(path)) { break; } } }
    
    for (Object groupObject : allGroupsallGroupsToProvision) { Group group = (Group)groupObject; if (allGroupsToProvision.contains(group)) {continue;} if (groupsToNotProvisionToSet.contains(group)) {continue;} List paths = new ArrayList(); groupToPaths.put(group, paths); String currentName =System.out.println("configured to provision to: " + provisionTarget + ": " + group.getName()); paths.add(currentName);  while(true) { currentName = GrouperUtil.parentStemNameFromName(currentName);  if (GrouperUtil.isBlank(currentName)) {break;} paths.add(currentName);  }   }
   }


Include a common GSH file

If this is the file in the container:

Code Block
def  addNewGroup(pathName, dispName,groupType, gsh_builtin_gshTemplateOutput,grouperSession ) {
    //Verify if allowgroup exist or not and provide appropriate messages
   groupVerify = GroupFinder.findByName(grouperSession, pathName,false);
   if (groupVerify != null) 
    for (Object groupObject : groupToPaths.keySet()) {Groupgsh_builtin_gshTemplateOutput.addOutputLine( pathName + " group = (Group)groupObject; List paths = (List)groupToPaths.get(group); for (Object pathObject : paths) { String path = (String)pathObject; if (stemNamesToProvisionTo.contains(path)) { allGroupsToProvision.add(group); break; } if (stemNamesToNotProvisionTo.contains(path)) { break; } } }
    
    for (Object groupObject : allGroupsToProvision) { Group group = (Group)groupObject; System.out.println("configured to provision to: " + provisionTarget + ": " + group.getName()); }

already exists!");
    else 
    {
        productGroup = new GroupSave(grouperSession).assignCreateParentStemsIfNotExist(true).assignName(pathName).assignDisplayName(dispName).save();
        gsh_builtin_gshTemplateOutput.addOutputLine("Created "+ groupType +" group : "  +pathName);
        gsh_builtin_gshTemplateOutput.addOutputLine("Added Group types: "+groupType+" for group : " + pathName);
    }

GdgTypeGroupSave gdgTypeGroupSave = new GdgTypeGroupSave().assignGroup(productGroup).assignType(groupType);
gdgTypeGroupSave.save();
return productGroup;

} 

Include that in a GSH template or other script

Code Block
GroovyShell shell = new GroovyShell();
def external = shell.parse(new File('/opt/grouper/gsh/commonFunction.gsh'));

newGroup=external.addNewGroup


Stem move

try this:

Code Block
GrouperSession.startRootSession();
stemFrom = StemFinder.findByName(grouperSession, "a:b", true);
stemTo = StemFinder.findByName(grouperSession, "a:c", true);
new edu.internet2.middleware.grouper.StemMove(stemFrom, stemTo).assignAlternateName(false).save();

...