Remoting Specific Scripts

This page lists remoting scripts that are meant to be used in conjunction with the anthill3 dev-kit. These scripts were taken straight from the public JIRA site. Please note that some scripts may be snippets and probably WILL need modification to work properly for your situation. Treat these as templates that you can modify from.

List Contents of Specific Build Life Artifacts

Script Notes:

  • Treat this mostly as a snippet for doing something more interesting with.
  • This script requires the following packaging changes to the remoting library:
1. From the %SERVER_HOME%\lib directory:
  • Copy CommonsFileUtils.jar to the lib directory of the remoting client.
2. From the %SERVER_HOME%\opt\tomcat\webapps\ROOT\WEB-INF\lib directory:
  • Copy anthill3-web-ALA.jar to the lib directory of the remoting client.
3. From the %AGENT_HOME%\opt\ahptool directory:
  • Copy ahptool.jar to the lib directory of the remoting client.
4. Changes made to the %DEVKIT_HOME%\remoting\conf\spring-client\base.xml file:
  • <bean id="codestation-repo-file-helper" class="com.urbancode.codestation2.server.CodestationRepositoryFileHelperClient" scope="prototype"/>

AHPSCRIPTS-109

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.buildlife.*;
import com.urbancode.codestation2.server.*;

String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

// obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort, userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

BuildLife buildLife = BuildLifeFactory.getInstance().restore(2111L);

CodestationRepositoryFileHelper cs = CodestationRepositoryFileHelper.getInstance();

sets = cs.getPopulatedBuildLifeArtifactSetList(buildLife);

for (int s=0; s<sets.length; s++) {
    print("");
    print("Contents of '" + sets[s].getName() + "'");
    artifacts = cs.listBuildLifeArtifactSetFiles(buildLife, sets[s]);
    
    for (int a=0; a<artifacts.length; a++) {
        print(" " + artifacts[a]);
    }
}

uow.close();

A modified version that will work from an evaluate script step

import com.urbancode.anthill3.domain.buildlife.*;
import com.urbancode.codestation2.server.*;

//GRAB VALUE FROM WORKFLOW PROPERTY AND TURN IT INTO A LONG.
//targetbl IS A WORKFLOW PROPERTY WITH THE TARGET BUILDLIFE NUMBER.
String targetBuildLifeString = PropertyLookup.getValue("targetbl");
Long targetBuildLife = Long.parseLong(targetBuildLifeString, 10);

//GET THE BUILDLIFE
BuildLife buildLife = BuildLifeFactory.getInstance().restore(targetBuildLife);

//GET CLASS TO LIST ARTIFACTS
CodestationRepositoryFileHelper cs = CodestationRepositoryFileHelper.getInstance();

sets = cs.getPopulatedBuildLifeArtifactSetList(buildLife);

//PREPARE THE ah3server.out
//THE System.out LINES CAN BE REMOVED.  THEY ARE FOR DEBUGGING PURPOSES ONLY!
System.out.println("\n\n\n");

//LOOP THROUGH ARTIFACT SETS
for (int s=0; s<sets.length; s++) {
    //WRITE OUT EACH ARTIFACT SET NAME
	commandOutput.println("");
	System.out.println("");
    commandOutput.println("Contents of '" + sets[s].getName() + "'");
	System.out.println("Contents of '" + sets[s].getName() + "'");
    
	//GET ARTIFACTS
	artifacts = cs.listBuildLifeArtifactSetFiles(buildLife, sets[s]);
    
    for (int a=0; a<artifacts.length; a++) {
        //PRINT EACH ARTIFACT
		commandOutput.println(" " + artifacts[a]);
		System.out.println(" " + artifacts[a]);
    }//END ARTIFACTS FOR
}//END ARTIFACT SET FOR

Update Environment Properties for All Projects

The idea here is that you may have secure value that is the same for all projects that are in a particular environment. Especially for passwords which could change regularly, going into each project to enter this is lame. Here's a remote script to do it.

Something like:

ah3client updateProjectEnvrionmentProperty.bsh user password Production password secret

AHPSCRIPTS-14

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.project.*;
import com.urbancode.anthill3.domain.project.envprops.*;
import com.urbancode.anthill3.domain.servergroup.*;
import java.util.*;

String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

String environmentName = "Password";
String variableName = "my.var.name";
String newVariableValue = "new value";


//serverHost = bsh.args[0];
//serverPort = Integer.parseInt(bsh.args[1]);

if (bsh.args.length != 5) {
   print("");
   print("Invalid snyax. Please enter the command as: ");
   print("ah3client updateProjectEnvrionmentProperty.bsh [user name] [password] [environment name] [env property name] [new property value]");
   return 0;
}

userName = bsh.args[0];
password = bsh.args[1];
environmentName = bsh.args[2];
variableName = bsh.args[3];
newVariableValue = bsh.args[4];

// obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,
                                              userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

ServerGroup environment = ServerGroupFactory.getInstance().restoreForName(environmentName);
if (environment == null) {
   print("Unknown environment: " + environmentName);
   throw new IllegalArgumentException("Unknown environment: " + environmentName);
}



// Project
Project[] projects = ProjectFactory.getInstance().restoreAll();

// Loop through projects. If it has environment props for this, find the
// right one and change it as appropriate.
for (int i = 0; i < projects.length; i++) {
  print("Inspecting: " + projects[i].getName());
  
ProjectEnvironmentProperty[] envPropArray = environment.getEnvironmentPropertiesForProject(projects[i]);
  boolean foundVariable = false;
  for (int j = 0; j < envPropArray.length; j++) {
     if (envPropArray[j].getName().equals(variableName)) {
        foundVariable = true;
        envPropArray[j].setValue(newVariableValue);
        envPropArray[j].store();
     }
  }
  
if (!foundVariable) {
      ProjectEnvironmentProperty newProp = new ProjectEnvironmentProperty(true);
      
newProp.setProject(projects[i]);
      newProp.setServerGroup(environment);
      newProp.setName(variableName);
      newProp.setValue(newVariableValue);
      newProp.setSetAsEnvProp(false);
      newProp.setSecureValue(true);
      
newProp.store();
  }
  
}

print("Committing Changes");
uow.commitAndClose(); 

Create Workflow Property for Every Workflow Using Given Library Workflow

Use this script if you want have added a new property to the library workflow and want to add the property to every workflow using it.

AHPSCRIPTS-67

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.workflow.*;

String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

// obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,
                                              userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

workflowDef = WorkflowDefinitionFactory.getInstance().restore(150L);

propName = "new text property";

workflows = WorkflowFactory.getInstance().restoreAll();
for (int w=0; w<workflows.length; w++) {
    if (workflowDef.equals(workflows[w].getWorkflowDefinition())) {
        // add the property to the workflow
        if (workflows[w].hasProperty(propName)) {
            System.out.println("Property '" + propName + "' already exists on " +
                workflows[w].getProject().getName() + " - " + workflows[w].getName());
        } else {
            WorkflowProperty prop = new WorkflowProperty(WorkflowPropertyTypeEnum.TEXT);
            prop.setName(propName);
            prop.setLabel("label text");
            prop.setUserMayOverride(true);
            prop.setRequired(true);
            prop.setValue("default value");
            workflows[w].addProperty(prop);
            System.out.println("Property '" + propName + "' added on " +
                workflows[w].getProject().getName() + " - " + workflows[w].getName());
        }
    }
}

uow.commit();

Set Role Permissions For Workflow of Given Name in Every Project

This script takes the usual server port username password as well as a role name a workflow name and a string of up to 2 characters being xs for execute and security. This script will go through every project and if that project contains a workflow with the given name it will assign the requested permissions to the entered in role.

AHPSCRIPTS-78

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.project.*;
import com.urbancode.anthill3.domain.workflow.*;
import com.urbancode.anthill3.domain.security.*;

final String EXECUTE = "execute";
final String SECURITY = "security";

String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

serverHost = bsh.args[0];
serverPort = Integer.parseInt(bsh.args[1]);
userName = bsh.args[2];
password = bsh.args[3];

if (serverHost == null || serverHost.length() == 0) {
throw new IllegalArgumentException("Must Specify a Server Host");
}

String roleName = bsh.args[4];
print("Role:" + roleName);

String workflowName = bsh.args[5];
print("Workflow:" + workflowName);

String permissions = bsh.args[6];
boolean settingExecute = false;
boolean settingSecurity = false;

if (permissions.contains("x")) {
print("Setting Execute");
settingExecute = true;
}
if (permissions.contains("s")) {
print("Setting Security");
settingSecurity = true;
}

// obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,
                                              userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

Role role = RoleFactory.getInstance().restoreForName(roleName);
if (role == null) {
    throw new Exception("Role " + roleName + " not found.");
}

// Project
Project[] projects = ProjectFactory.getInstance().restoreAllActive();
if (projects == null || projects.length == 0) {
    throw new IllegalStateException("No Projects found.");
}

for (Project project : projects) {
boolean hasExecute = false;
boolean hasSecurity = false;
boolean isDirty = false;

print("\tSetting permissions for Project:" + project.getName());

Workflow workflow = project.getWorkflow(workflowName);
if (workflow != null) {
Resource resource = ResourceFactory.getInstance().restoreForPersistent(workflow);
if (resource == null) {
throw new Exception("Workflow Resource not found. Please contact support.");
}

Permission[] permissions = PermissionFactory.getInstance().restoreAllForResource(resource);
for (Permission permission : permissions) {
if (permission.getRole().equals(role)) {
if (settingExecute && EXECUTE.equals(permission.getAction())) {
print("\t\tHas Execute");
hasExecute = true;
}
else if (settingSecurity && SECURITY.equals(permission.getAction())) {
print("\t\tHas Security");
hasSecurity = true;
}
}
}

if (settingExecute && !hasExecute) {
print("\tSetting Execute Permission");
Permission execute = new Permission(resource, EXECUTE, role);
execute.store();
isDirty = true;
}
if (settingSecurity && !hasSecurity) {
print("\tSetting Security Permission");
Permission security = new Permission(resource, SECURITY, role);
security.store();
isDirty = true;
}

// commit to database
if (isDirty) {
uow.commit();
}
}
else {
print("Workflow " + workflowName + " not found for Project " + project.getName());
}

}

//Close unit of work
uow.close(); 

Set Role Permissions For All Anthill Projects

This script will take the usual inputs server port username password as well as role name and a script of up to 3 characters being rws. It will then set those given permissions read write security for the given role on all Anthill3 Projects in the system.

AHPSCRIPTS-77

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.project.*;
import com.urbancode.anthill3.domain.security.*;

final String READ = "read";
final String WRITE = "write";
final String SECURITY = "security";

String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

serverHost = bsh.args[0];
serverPort = Integer.parseInt(bsh.args[1]);
userName = bsh.args[2];
password = bsh.args[3];

if (serverHost == null || serverHost.length() == 0) {
throw new IllegalArgumentException("Must Specify a Server Host");
}

String roleName = bsh.args[4];

print("Role:" + roleName);

String permissions = bsh.args[5];
boolean settingRead = false;
boolean settingWrite = false;
boolean settingSecurity = false;

if (permissions.contains("r")) {
print("Setting Read");
settingRead = true;
}
if (permissions.contains("w")) {
print("Setting Write");
settingWrite = true;
}
if (permissions.contains("s")) {
print("Setting Security");
settingSecurity = true;
}

// obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,
                                              userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

Role role = RoleFactory.getInstance().restoreForName(roleName);
if (role == null) {
    throw new Exception("Role " + roleName + " not found.");
}

// Project
Project[] projects = ProjectFactory.getInstance().restoreAllActive();
if (projects == null || projects.length == 0) {
    throw new Exception("No Projects found.");
}

for (Project project : projects) {
boolean hasRead = false;
boolean hasWrite = false;
boolean hasSecurity = false;
boolean isDirty = false;

print("\tSetting permissions for Project:" + project.getName());

Resource resource = ResourceFactory.getInstance().restoreForPersistent(project);
if (resource == null) {
throw new Exception("Project Resource not found. Please contact support.");
}

Permission[] permissions = PermissionFactory.getInstance().restoreAllForResource(resource);
for (Permission permission : permissions) {
if (permission.getRole().equals(role)) {
if (settingRead && READ.equals(permission.getAction())) {
print("\t\tHas Read");
hasRead = true;
}
else if (settingWrite && WRITE.equals(permission.getAction())) {
print("\t\tHas Write");
hasWrite = true;
}
else if (settingSecurity && SECURITY.equals(permission.getAction())) {
print("\t\tHas Security");
hasSecurity = true;
}
}
}

if (settingRead && !hasRead) {
print("\tSetting Read Permission");
Permission read = new Permission(resource, READ, role);
read.store();
isDirty = true;
}
if (settingWrite && !hasWrite) {
print("\tSetting Write Permission");
Permission write = new Permission(resource, WRITE, role);
write.store();
isDirty = true;
}
if (settingSecurity && !hasSecurity) {
print("\tSetting Security Permission");
Permission security = new Permission(resource, SECURITY, role);
security.store();
isDirty = true;
}

// commit to database
if (isDirty) {
uow.commit();
}

}

//Close unit of work
uow.close(); 

Assign Read, Write, Security Permissions to All Codestation Projects For Role

This script takes the usual arguments server port username password then it takes role and a string of up to 3 characters being rws read write security. Then for every CS project in the server it gives those permissions to the provided role.

AHPSCRIPTS-76

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.codestation2.domain.project.*;
import com.urbancode.anthill3.domain.security.*;

final String READ = "read";
final String WRITE = "write";
final String SECURITY = "security";

String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

serverHost = bsh.args[0];
serverPort = Integer.parseInt(bsh.args[1]);
userName = bsh.args[2];
password = bsh.args[3];

if (serverHost == null || serverHost.length() == 0) {
throw new IllegalArgumentException("Must Specify a Server Host");
}

String roleName = bsh.args[4];

print("Role:" + roleName);

String permissions = bsh.args[5];
boolean settingRead = false;
boolean settingWrite = false;
boolean settingSecurity = false;

if (permissions.contains("r")) {
print("Setting Read");
settingRead = true;
}
if (permissions.contains("w")) {
print("Setting Write");
settingWrite = true;
}
if (permissions.contains("s")) {
print("Setting Security");
settingSecurity = true;
}

// obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,
                                              userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

Role role = RoleFactory.getInstance().restoreForName(roleName);
if (role == null) {
    throw new Exception("Role " + roleName + " not found.");
}

// Project
CodestationProject[] projects = CodestationProjectFactory.getInstance().restoreAllCodestation();
if (projects == null || projects.length == 0) {
    throw new Exception("No Projects found.");
}

for (CodestationProject project : projects) {
boolean hasRead = false;
boolean hasWrite = false;
boolean hasSecurity = false;
boolean isDirty = false;

print("\tSetting permissions for Project:" + project.getName());

Resource resource = ResourceFactory.getInstance().restoreForPersistent(project);
if (resource == null) {
throw new Exception("Project Resource not found. Please contact support.");
}

Permission[] permissions = PermissionFactory.getInstance().restoreAllForResource(resource);
for (Permission permission : permissions) {
if (permission.getRole().equals(role)) {
if (settingRead && READ.equals(permission.getAction())) {
print("\t\tHas Read");
hasRead = true;
}
else if (settingWrite && WRITE.equals(permission.getAction())) {
print("\t\tHas Write");
hasWrite = true;
}
else if (settingSecurity && SECURITY.equals(permission.getAction())) {
print("\t\tHas Security");
hasSecurity = true;
}
}
}

if (settingRead && !hasRead) {
print("\tSetting Read Permission");
Permission read = new Permission(resource, READ, role);
read.store();
isDirty = true;
}
if (settingWrite && !hasWrite) {
print("\tSetting Write Permission");
Permission write = new Permission(resource, WRITE, role);
write.store();
isDirty = true;
}
if (settingSecurity && !hasSecurity) {
print("\tSetting Security Permission");
Permission security = new Permission(resource, SECURITY, role);
security.store();
isDirty = true;
}

// commit to database
if (isDirty) {
uow.commit();
}

}

//Close unit of work
uow.close(); 

Create a New Originating Workflow For Mass Branching or Projects (CVS)

This script will go through all of the Projects and search for Projects Using an existing Branch and Create a new Originating Workflow which points to the new Branch. This script takes a listing of Projects and as well as a Branch Name and optionally a Workflow Name if you are not naming yours based on the BranchNameBuild convention.

AHPSCRIPTS-75

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.profile.*;
import com.urbancode.anthill3.domain.project.*;
import com.urbancode.anthill3.domain.workflow.*;
import com.urbancode.anthill3.domain.source.cvs.CvsSourceConfig;

import com.urbancode.codestation2.domain.project.*;

import java.util.*;

List getProjectsForNameList(String projectListStr) {
List result = new ArrayList();

String[] projectNames = projectListStr.split(",");
for (int i = 0; i < projectNames.length; i++) {
Project project = ProjectFactory.getInstance().restoreForName(projectNames[i].trim());

//Verify that the project exists
if (project == null) {
throw new IllegalStateException("No Project Found with name " + projectNames[i]);
}

//Verify project contains a proper workflow to copy
if (project.getWorkflow(workflowName) == null) {
throw new IllegalStateException("Project " + projectNames[i] + " had no workflow named " + workflowName);
}

//Verify the workflow is originating
if (!project.getWorkflow(workflowName).isOriginating()) {
throw new IllegalStateException("Project " + projectNames[i] + " workflow named " + workflowName + " is not originating");
}
result.add(project);
}

return result;
}

void modifyBranchOnSourceConfig(Workflow workflow) {
if (!(workflow.getBuildProfile().getSourceConfig() instanceof CvsSourceConfig)) {
throw new IllegalStateException("Workflow " + workflow.getName() + " for Project " + workflow.getProject().getName() + " does not contain a CvsSourceConfig");
}

CvsSourceConfig sourceConfig = workflow.getBuildProfile().getSourceConfig();
for (int i =0; i < sourceConfig.getModuleArray().length; i++) {
sourceConfig.getModuleArray()[i].setBranch(branchName);
}
}

Workflow getOrCreateBranchWorkflow(Project project, Workflow workflow) {
Workflow result = null;
String branchWorkflowName = strategicProjectName + "Build";

if (project.getWorkflow(branchWorkflowName) == null) {
print("Creating Branch Workflow for Project " + project.getName());
result = workflow.duplicate();
result.setName(branchWorkflowName);

if (result.getBuildProfile() == null) {
throw new IllegalStateException("Workflow " + result.getName() + " for Project " + workflow.getProject().getName() + " has no Build Profile");
}
result.getBuildProfile().setName(branchWorkflowName);
modifyBranchOnSourceConfig(result);
}
else {
print("Retrieving Existing Branch Workflow for Project " + project.getName());
result = project.getWorkflow(branchWorkflowName);
}

return result;
}

void migrateDependenciesToBranchedProfiles(BuildProfile buildProfile, Map tacticalProfileToBranchProfile) {
for (int i =0; i < buildProfile.getDependencyArray().length; i++) {
Dependency dep = buildProfile.getDependencyArray()[i];
if (dep.getDependency() instanceof AnthillProject) {
AnthillProject anthillProject = (AnthillProject) dep.getDependency();
if (tacticalProfileToBranchProfile.containsKey(anthillProject.getBuildProfile())) {
BuildProfile branchProfile = (BuildProfile) tacticalProfileToBranchProfile.get(anthillProject.getBuildProfile());
AnthillProject newDependency = new AnthillProject(branchProfile);
print("Changing Project " + buildProfile.getProject().getName() + " to depend on " + newDependency.getName());
dep.setDependency(newDependency);
}
}
}
}

String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

String strategicProjectName = null;
String projectListStr = null;
String branchName = null;

String workflowName = "TacticalBuild";

Map tacticalProfileToBranchProfile = new HashMap();
List branchProfiles = new ArrayList();

if (bsh.args.length <= 6) {
throw new IllegalStateException("createBranchwWorkflows.bsh <server> <port> <username> <password> <strat-proj-name> <proj-list> <branch-name> ?<workflow-name> ");
}

serverHost = bsh.args[0];
serverPort = Integer.parseInt(bsh.args[1]);
userName = bsh.args[2];
password = bsh.args[3];

strategicProjectName = bsh.args[4];
projectListStr = bsh.args[5];
branchName = bsh.args[6];

if (bsh.args.length == 8) {
workflowName = bsh.args[7];
}

// obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,
                                              userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

// Query up all the projects
List projects = getProjectsForNameList(projectListStr);
print("Found " + projects.size() + " projects to modify");

// Run through all of the projects creating any branch workflows that dont already exist
// This also builds up a list of the old workflows to the new workflows so we can change any dependencies
for (int i = 0; i < projects.size(); i++) {
Project project = (Project) projects.get(i);
Workflow workflow = project.getWorkflow(workflowName);
Workflow branchWorkflow = getOrCreateBranchWorkflow(project, workflow);
tacticalProfileToBranchProfile.put(workflow.getBuildProfile(), branchWorkflow.getBuildProfile());
branchProfiles.add(branchWorkflow.getBuildProfile());
}

for (int i =0; i < branchProfiles.size(); i++) {
BuildProfile buildProfile = (BuildProfile) branchProfiles.get(i);
migrateDependenciesToBranchedProfiles(buildProfile, tacticalProfileToBranchProfile);
}

uow.commitAndClose();

Erase ALL Dependencies For Project

This Script will remove all dependencies for a List of Project Names.

AHPSCRIPTS-74

import com.urbancode.anthill3.domain.*;
import com.urbancode.anthill3.domain.artifacts.*;
import com.urbancode.anthill3.domain.project.*;
import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;

/////////////////////////////////////////////////
String serverHost = "localhost";
int serverPort = 4567;
String username = "admin";
String password = "admin";
AnthillClient ac = AnthillClient.connect(serverHost, serverPort, username, password);
UnitOfWork uow = ac.createUnitOfWork();
/////////////////////////////////////////////////

for(p : bsh.args) {
projectName = p;
print("Libraries for project " + projectName);
print("----------------------------------------------------");



pdal = ProjectFactory.getInstance().restoreForName(projectName);
pdal_wf = pdal.getWorkflow("CommonModuleBuildWorkflow");
pdal_bf = pdal_wf.getBuildProfile();
deps = pdal_bf.getDependencyArray();

for(dep : deps) {
print("Deleting " + dep.getDependency().getName());
pdal_bf.removeDependency(dep);
dep.delete();
}
pdal_bf.store();

print("");
}

////////////////////////////////////////
uow.commitAndClose();
uow = null;
ac = null;
////////////////////////////////////////

Script to Add Dependencies to Projects Based on XML Input File

  • This script is pointed to an XML configuration file and it will take the file and configure the respective depencies in Anthill3.

AHPSCRIPTS-71

import com.urbancode.anthill3.main.client.AnthillClient;
 import com.urbancode.anthill3.persistence.UnitOfWork;
 import com.urbancode.anthill3.domain.project.*;
 import com.urbancode.anthill3.domain.profile.*;
 import com.urbancode.anthill3.domain.workflow.*;
 import com.urbancode.anthill3.domain.status.*;
 import com.urbancode.anthill3.runtime.scripting.helpers.*;
 import com.urbancode.codestation2.domain.artifacts.*;
 import com.urbancode.codestation2.domain.project.*;

 import org.xml.sax.*;
 import org.w3c.dom.*;
 import java.io.*;
 import java.util.*;
 import javax.xml.parsers.*;

 class ParsedProject {
 String name = null;
 String workflow = null;
 List dependencies = new ArrayList();

 void addDependency(ParsedDependency dep) {
 dependencies.add(dep);
 }

 }

 class ParsedDependency {
 String name = null;
 String type = null;
 String workflow = null;
 String status = null;
 String stamp = null;
 List artifactSets = new ArrayList();

 void addArtifactSet(ParsedArtifactSet artifactSet) {
 artifactSets.add(artifactSet);
 }

 boolean isAnthill() {
 boolean result = false;

 if ("Anthill".equals(type)) {
 result = true;
 }

 return result;
 }

 boolean isCodestation() {
 boolean result = false;

 if ("Codestation".equals(type)) {
 result = true;
 }

 return result;
 }
 }

 class ParsedArtifactSet {
 String name = null;
 String destination = null;
 }

 Document loadDocument(InputStream in)
 throws ParserConfigurationException, SAXException, IOException {
 Document result = null;
 try {
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 result = builder.parse(new InputSource(in));
 }
 finally {
 if (in != null) {
 try {
 in.close();
 } catch (IOException e) {e.printStackTrace();}
 }
 }
 return result;
 }

 List getChildElementList(Element element, String name) {
 List result = new ArrayList();

 NodeList childList = element.getChildNodes();
 for (int i =0; i < childList.getLength(); i++) {
 if (childList.item(i).getNodeName().equals(name)) {
 result.add(childList.item(i));
 }
 }

 return result;
 }

 Element getFirstChild(Element element, String name) {
 Element result = null;

 List childList = getChildElementList(element, name);
 if (childList.size() >= 1) {
 result = (Element) childList.get(0);
 }

 return result;
 }

 void parseConnectionInfo(Element element) {
 if (element != null) {
 serverHost = element.getAttribute("hostname");
 String serverPortStr = element.getAttribute("port");
 serverPort = Integer.parseInt(serverPortStr);
 userName = element.getAttribute("username");
 password = element.getAttribute("password");
 }
 }

 ParsedArtifactSet parseArtifactSet(Element element) {
 ParsedArtifactSet result = null;

 if (element != null) {
 result = new ParsedArtifactSet();
 result.name = element.getAttribute("name");
 result.destination = element.getAttribute("destination");
 }

 return result;
 }

 ParsedDependency parseDependency(Element element) {
 ParsedDependency result = null;

 if (element != null) {
 result = new ParsedDependency();
 result.name = element.getAttribute("name");
 result.type = element.getAttribute("type");
 result.workflow = element.getAttribute("workflow");

 Element criteria = getFirstChild(element, "criteria");
 if (criteria != null) {
 result.status = criteria.getAttribute("status");
 result.stamp = criteria.getAttribute("stamp");
 }

 List artifactSetElements = getChildElementList(element, "artifact");
 for (int i =0; i < artifactSetElements.size(); i++) {
 Element artifactSetElement = (Element) artifactSetElements.get(i);
 result.addArtifactSet(parseArtifactSet(artifactSetElement));
 }
 }

 return result;
 }

 ParsedProject parseProject(Element element) {
 ParsedProject result = null;

 if (element != null) {
 result = new ParsedProject();
 result.name = element.getAttribute("name");
 result.workflow = element.getAttribute("workflow");

 List dependencyElements = getChildElementList(element, "dependency");
 for (int i =0; i < dependencyElements.size(); i++) {
 Element dependencyElement = (Element) dependencyElements.get(i);
 result.addDependency(parseDependency(dependencyElement));
 }
 } 

 return result;
 }

 ParsedProject[] parseProjects(List elements) {
 ParsedProject[] result = new ParsedProject[elements.size()];

 for (int i =0; i < elements.size(); i++) {
 Element element = (Element) elements.get(i);
 result[i] = parseProject(element);
 }

 return result;
 }

 String fileName = bsh.args[0];
 String serverHost = null;
 int serverPort = 0;
 String userName = null;
 String password = null;

 Element rootElement = loadDocument(new FileInputStream(fileName)).getDocumentElement();
 parseConnectionInfo(rootElement);

 ParsedProject[] parsedProjects = parseProjects(getChildElementList(rootElement, "project"));
 print("Found " + parsedProjects.length + " Projects to add dependencies to.");

 // obtain connection to the Anthill server
 AnthillClient anthill = AnthillClient.connect(serverHost, serverPort, 
                                               userName, password);

 // create a Unit of Work
 UnitOfWork uow = anthill.createUnitOfWork();

 for (int i =0; i < parsedProjects.length; i++) {
 ParsedProject parsedProject = parsedProjects[i];
 print("DependentProject:" + parsedProject.name + " DependentWorkflow:" + parsedProject.workflow);

 Project dependentProject = ProjectFactory.getInstance().restoreForName(parsedProject.name);
 if (dependentProject == null) {
 throw new IllegalStateException("Dependent Project " + parsedProject.name + " was not found");
 }
 Workflow dependentWorkflow = dependentProject.getWorkflow(parsedProject.workflow);
 if (dependentWorkflow == null) {
 throw new IllegalStateException("Dependent Wofklow " + parsedProject.workflow + " was not found");
 }
 BuildProfile dependentBuildProfile = dependentWorkflow.getBuildProfile();
 AnthillProject dependentAnthillProject = new AnthillProject(dependentBuildProfile);

 for (int j =0; j < parsedProject.dependencies.size(); j++) {
 ParsedDependency parsedDependency = (ParsedDependency) parsedProject.dependencies.get(j);
 if (parsedDependency.isCodestation()) {
 print("\tCodestation DependencyName:" + parsedDependency.name);
 } 
 else {
 print("\tAnthill DependencyName:" + parsedDependency.name + " DependencyWorkflow:" + parsedDependency.workflow);
 }
 if (parsedDependency.stamp != null &&
 parsedDependency.stamp.length() > 0) {
 print("\tStamp:" + parsedDependency.stamp);
 }
 if (parsedDependency.status != null &&
 parsedDependency.status.length() > 0) {
 print("\tStatus:" + parsedDependency.status);
 }

 Dependency dep = new Dependency();
 CodestationCompatableProject csProject = null;

 if (parsedDependency.isAnthill()) {
 Project dependencyProject = ProjectFactory.getInstance().restoreForName(parsedDependency.name);
 if (dependencyProject == null) {
 throw new IllegalStateException("Anthill Dependency Project " + parsedDependency.name + " was not found");
 }
 Workflow dependencyWorkflow = dependencyProject.getWorkflow(parsedDependency.workflow);
 if (dependencyWorkflow == null) {
 throw new IllegalStateException("Anthill Dependency Workflow " + parsedDependency.workflow + " was not found");
 }
 BuildProfile dependencyBuildProfile = dependencyProject.getWorkflow(parsedDependency.workflow).getBuildProfile();
 csProject = new AnthillProject(dependencyBuildProfile);
 dep.setBuildCondition(Dependency.PUSH_BUILD);
 Status status = csProject.getStatusGroup().getStatus("success");
 if (status == null) {
 throw new IllegalStateException("Anthill Dependency Project " + parsedDependency.name + " has no status success");
 }
 dep.setStatus(status);
 dep.setUsingExistingOnFail(false);
 dep.setAlwaysForce(false);
 dep.setCascadeForce(false);
 }
 else if (parsedDependency.isCodestation()) {
 csProject = CodestationProjectFactory.getInstance().restoreForName(parsedDependency.name);
 if (csProject == null) {
 throw new IllegalStateException("Codestaion Dependency Project " + parsedDependency.name + " was not found");
 }
 dep.setBuildCondition(Dependency.USE_EXISTING);
 if (parsedDependency.status != null &&
 parsedDependency.status.length() > 0) {
 Status status = csProject.getStatusGroup().getStatus(parsedDependency.status);
 if (status == null) {
 throw new IllegalStateException("Codestation Dependency Project " + parsedDependency.name + " has no status " + parsedDependency.status);
 }
 dep.setStatus(status);
 }
 else {
 dep.setStatus(null);
 }

 if (parsedDependency.stamp != null &&
 parsedDependency.stamp.length() > 0) {
 dep.setStampValue(parsedDependency.stamp);
 }
 else {
 dep.setStampValue(null);
 }
 }
 else {
 throw new IllegalArgumentException("No or invalid type specified. Anthill | Codestation");
 }

 if (csProject != null) {
 dep.setDependency(csProject);
 for (int k =0; k < parsedDependency.artifactSets.size(); k++) {
 ParsedArtifactSet parsedArtifactSet = (ParsedArtifactSet) parsedDependency.artifactSets.get(k);
 print("\t\t ArtifactSet:" + parsedArtifactSet.name + " Destinaion Dir:" + parsedArtifactSet.destination);
 String[] dirs = {parsedArtifactSet.destination};
 CodestationCompatableArtifactSet artifactSet = csProject.getArtifactSet(parsedArtifactSet.name);
 if (artifactSet == null) {
 throw new IllegalStateException("Dependency Project " + parsedDependency.name + " has no artifact set " + parsedArtifactSet.name);
 }
 dep.addSet2Dirs(artifactSet, dirs, false);
 }

 dependentBuildProfile.addDependency(dep);
 dep.setDependent(dependentAnthillProject);
 dep.store();
 }
 else {
 if (parsedDependency.isCodestation()) {
 print("\tCould Not Find Codestation DependencyName:" + parsedDependency.name);
 } 
 else {
 print("\tCould Not Find Anthill DependencyName:" + parsedDependency.name + " DependencyWorkflow:" + parsedDependency.workflow);
 }
 }
 }
 }

 uow.commitAndClose();

Migrate All Workflows Using One Branch to Use Different Branch (CVS)

This script changes the branch that is being checked out from cvs to be a different branch. This helps teams that are using a release branching strategy where the branch their workflows are building changes with each release and this change effects every workflow in the stack.

AHPSCRIPTS-73

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.profile.*;
import com.urbancode.anthill3.domain.source.*;
import com.urbancode.anthill3.domain.source.cvs.*;
import com.urbancode.anthill3.domain.workflow.*;
import com.urbancode.anthill3.domain.repository.cvsrepo.*;

String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

if (bsh.args.length != 6) {
print("usage: <server> <port> <username> <password> <fromBranch> <toBranch>");
throw new IllegalArgumentException("Incorrect number of arguments specified");
}

serverHost = bsh.args[0];
serverPort = Integer.parseInt(bsh.args[1]);
userName = bsh.args[2];
password = bsh.args[3];

String fromBranch = bsh.args[4];
String toBranch = bsh.args[5];

print("Migrating " + fromBranch + " to " + toBranch);

// obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,
                                              userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

// Workflow
Workflow[] workflows = WorkflowFactory.getInstance().restoreAll();

for (int i = 0; i < workflows.length; i++) {
Workflow workflow = workflows[i];
if (workflow != null && workflow.isOriginating()) {
BuildProfile buildProfile = workflow.getBuildProfile();
SourceConfig sourceConfig = buildProfile.getSourceConfig();
if (sourceConfig instanceof CvsSourceConfig) {
CvsSourceConfig cvsSourceConfig = (CvsSourceConfig) sourceConfig;
CvsModule module = cvsSourceConfig.getModuleArray()[0];
if (module.getBranch() != null && module.getBranch().equals(fromBranch)) {
print("Changing Project:" + workflow.getProject().getName() + " Workflow:" + workflow.getName());
module.setBranch(toBranch);
}
}
}
}

uow.commitAndClose();

Check for Circular Dependencies in Workflow Configuration

This Script goes through all of the Workflow Dependency Configurations checking for any circular deps that may be configured. This can only really happen through remote scripting since our UI prevents it.

AHPSCRIPTS-72

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.profile.*;
import com.urbancode.anthill3.domain.project.*;
import com.urbancode.anthill3.domain.workflow.*;
import com.urbancode.codestation2.domain.project.*;

import java.util.*;

String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

serverHost = bsh.args[0];
serverPort = Integer.parseInt(bsh.args[1]);
userName = bsh.args[2];
password = bsh.args[3];

HashSet getAllDeps(CodestationCompatableProject depProject) {
HashSet allDeps = new HashSet();
addAllDeps(allDeps, depProject);
return allDeps;
}

addAllDeps(HashSet deps, CodestationCompatableProject depProject) {

if (deps.add(depProject)) {
Dependency[] trans = ((WithAnthillDependencies) depProject).getDependencyArray();
for (int i =0; i < trans.length; i++) {
addAllDeps(deps, trans[i].getDependency());
}
}
}

// obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,
                                              userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

// Project
Project[] projects = ProjectFactory.getInstance().restoreAll();

for (int i = 0; i < projects.length; i++) {
Workflow workflow = projects[i].getWorkflow("CommonModuleBuildWorkflow");
if (workflow != null) {
Dependency[] deps = workflow.getBuildProfile().getDependencyArray();
for (int j =0; j < deps.length; j++) {
if (getAllDeps(deps[j].getDependency()).contains(new AnthillProject(workflow.getBuildProfile()))) {
throw new IllegalStateException("Circular Dependency Found in project " + projects[i].getName() + " for dependency " + deps[j].getDependency().getName() + " with dependent " + deps[j].getDependent().getName());
}
}
}
}

uow.commitAndClose();

Give All Roles Read Permission to All Agents

  • Here's an example of how to use the remoting library to make mass security changes. Naturally, you'll need to run this script with permissions that can see every agent and every role. For teams that find the new agent security in 3.5 annoying, this can be a great way to open up the permissions to those agents. All roles get read permissions to every agent, the "Build Master" role also gets "write" permissions to every agent.

AHPSCRIPTS-86

import com.urbancode.anthill3.main.client.AnthillClient; 
 import com.urbancode.anthill3.persistence.UnitOfWork; 
 import com.urbancode.anthill3.domain.agent.*; 
 import com.urbancode.anthill3.domain.authentication.*; 
 import com.urbancode.anthill3.domain.security.*; 
 import java.util.*; 

 String serverHost = "myServerUrl"; 
 int serverPort = 4567; 
 String userName = "admin"; 
 String password = "enterThisOnCommandLine"; 

 //serverHost = bsh.args[0]; 
 //serverPort = Integer.parseInt(bsh.args[1]); 

 if (bsh.args.length != 2) { 
    print(""); 
    print("Invalid snyax. Please enter the command as: "); 
    print("ah3client createUser.bsh [user name] [password]"); 
    return 0; 
 } 

 userName = bsh.args[0]; 
 password = bsh.args[1]; 

 // obtain connection to the Anthill server 
 AnthillClient anthill = AnthillClient.connect(serverHost, serverPort, 
                                               userName, password); 

 // create a Unit of Work 
 UnitOfWork uow = anthill.createUnitOfWork(); 

 agentArray = AgentFactory.getInstance().restoreAllNotIgnored(); 
 allRolesArray = RoleFactory.getInstance().restoreAllActive(); 

 for (Agent agent: agentArray) { 
   boolean buildMasterHasWrite = false; 
   resource = ResourceFactory.getInstance().restoreForPersistent(agent); 
    
   // Determine roles don't have read access to an agent 
   HashSet roleWithoutReadPermSet = new HashSet(); 
   roleWithoutReadPermSet.addAll(Arrays.asList(allRolesArray)); 
   Permission[] permissions = PermissionFactory.getInstance().restoreAllForResource(resource); 
   for (Permission permission : permissions) { 
     Role role = permission.getRole(); 
     action = permission.getAction(); 
     if (!role.isUserRole() && role.isActive() && action.equals("read")) { 
         roleWithoutReadPermSet.remove(role); 
     } 
     else if (role.isUserRole() || !role.isActive()) { 
         roleWithoutReadPermSet.remove(role); 
     } 
     else if (role.getName().equals("Build Master") && action.equals("write")) { 
         buildMasterHasWrite = true; 
     } 
   } 
       
   // Create the missing Read Permissions 
   Iterator roleItr = roleWithoutReadPermSet.iterator(); 
   while (roleItr.hasNext()) { 
     Role role = roleItr.next(); 
     p = new Permission(true, resource, "read", role); 
     p.store(); 
   } 
    
   // Give Build Master Write Permission 
   if (!buildMasterHasWrite) { 
     Role bmRole = RoleFactory.getInstance().restoreForName("Build Master"); 
     p = new Permission(true, resource, "write", bmRole); 
     p.store(); 
   } 
 } 

 print("Committing Changes"); 
 uow.commitAndClose();

Give All Roles Read Permission to All Environments

  • Here's an example of how to use the remoting library to make mass security changes. Naturally, you'll need to run this script with permissions that can see every environment and every role (so admin would probably be the best user). For teams that find the new agent security in 3.5 annoying, this can be a great way to open up the permissions to those agents. All roles get read permissions to every agent, the "Build Master" role also gets "write" permissions to every agent.
  • Tested on 3.8.7
import com.urbancode.anthill3.main.client.AnthillClient; 
 import com.urbancode.anthill3.persistence.UnitOfWork; 
 import com.urbancode.anthill3.domain.authentication.*; 
 import com.urbancode.anthill3.domain.security.*; 
 import com.urbancode.anthill3.domain.servergroup.*; 
 import java.util.*; 

 String serverHost = "localhost"; 
 int serverPort = 4567; 
 String userName = "admin"; 
 String password = "admin"; 

 // obtain connection to the Anthill server 
 AnthillClient anthill = AnthillClient.connect(serverHost, serverPort, 
                                               userName, password); 

 // create a Unit of Work 
 UnitOfWork uow = anthill.createUnitOfWork(); 

 serverGroupArray = ServerGroupFactory.getInstance().restoreAll(); 
 allRolesArray = RoleFactory.getInstance().restoreAllActive(); 

 for (ServerGroup serverGroup: serverGroupArray) { 
   boolean buildMasterHasWrite = false; 
   resource = ResourceFactory.getInstance().restoreForPersistent(serverGroup); 
    
   // Determine roles don't have read access to serverGroup 
   HashSet roleWithoutReadPermSet = new HashSet(); 
   roleWithoutReadPermSet.addAll(Arrays.asList(allRolesArray)); 
   Permission[] permissions = PermissionFactory.getInstance().restoreAllForResource(resource); 
   for (Permission permission : permissions) { 
     Role role = permission.getRole(); 
     action = permission.getAction(); 
     if (!role.isUserRole() && role.isActive() && action.equals("read")) { 
         roleWithoutReadPermSet.remove(role); 
     } 
     else if (role.isUserRole() || !role.isActive()) { 
         roleWithoutReadPermSet.remove(role); 
     } 
     else if (role.getName().equals("Build Master") && action.equals("write")) { 
         buildMasterHasWrite = true; 
     } 
   } 
       
   // Create the missing Read Permissions 
   Iterator roleItr = roleWithoutReadPermSet.iterator(); 
   while (roleItr.hasNext()) { 
     Role role = roleItr.next(); 
     p = new Permission(resource, "read", role); 
     p.store(); 
   } 
    
   // Give Build Master Write Permission 
   if (!buildMasterHasWrite) { 
     Role bmRole = RoleFactory.getInstance().restoreForName("Build Master"); 
     p = new Permission(resource, "write", bmRole); 
     p.store(); 
   } 
 } 


 print("Committing Changes"); 
 uow.commitAndClose();

Give All Roles Read Permission to All Environment Groups

  • This is an example remoting script for giving all roles read permission to all Env Groups. This is an example of using the API to do mass updates of security and might be handy after upgrading to AnthillPro 3.5.

AHPSCRIPTS-87

import com.urbancode.anthill3.main.client.AnthillClient; 
 import com.urbancode.anthill3.persistence.UnitOfWork; 
 import com.urbancode.anthill3.domain.authentication.*; 
 import com.urbancode.anthill3.domain.security.*; 
 import com.urbancode.anthill3.domain.environmentgroup.*; 
 import java.util.*; 

 String serverHost = "youServerUrl"; 
 int serverPort = 4567; 
 String userName = "admin"; 
 String password = "thisIsSetAtTheCommandLine"; 

 //serverHost = bsh.args[0]; 
 //serverPort = Integer.parseInt(bsh.args[1]); 

 if (bsh.args.length != 2) { 
    print(""); 
    print("Invalid snyax. Please enter the command as: "); 
    print("ah3client createUser.bsh [user name] [password]"); 
    return 0; 
 } 

 userName = bsh.args[0]; 
 password = bsh.args[1]; 

 // obtain connection to the Anthill server 
 AnthillClient anthill = AnthillClient.connect(serverHost, serverPort, 
                                               userName, password); 

 // create a Unit of Work 
 UnitOfWork uow = anthill.createUnitOfWork(); 

 envGroupArray = EnvironmentGroupFactory.getInstance().restoreAll(); 
 allRolesArray = RoleFactory.getInstance().restoreAllActive(); 

 for (EnvironmentGroup envGroup: envGroupArray) { 
   boolean buildMasterHasWrite = false; 
   resource = ResourceFactory.getInstance().restoreForPersistent(envGroup); 
    
   // Determine roles don't have read access to envGroup 
   HashSet roleWithoutReadPermSet = new HashSet(); 
   roleWithoutReadPermSet.addAll(Arrays.asList(allRolesArray)); 
   Permission[] permissions = PermissionFactory.getInstance().restoreAllForResource(resource); 
   for (Permission permission : permissions) { 
     Role role = permission.getRole(); 
     action = permission.getAction(); 
     if (!role.isUserRole() && role.isActive() && action.equals("read")) { 
         roleWithoutReadPermSet.remove(role); 
     } 
     else if (role.isUserRole() || !role.isActive()) { 
         roleWithoutReadPermSet.remove(role); 
     } 
     else if (role.getName().equals("Build Master") && action.equals("write")) { 
         buildMasterHasWrite = true; 
     } 
   } 
       
   // Create the missing Read Permissions 
   Iterator roleItr = roleWithoutReadPermSet.iterator(); 
   while (roleItr.hasNext()) { 
     Role role = roleItr.next(); 
     p = new Permission(true, resource, "read", role); 
     p.store(); 
   } 
    
   // Give Build Master Write Permission 
   if (!buildMasterHasWrite) { 
     Role bmRole = RoleFactory.getInstance().restoreForName("Build Master"); 
     p = new Permission(true, resource, "write", bmRole); 
     p.store(); 
   } 
 } 


 print("Committing Changes"); 
 uow.commitAndClose();

Return List of All Build Lives in Particular Environment

  • This script is intended to be used a remote script, which means in order to use it, you must download the remoting API package from the "Tools" link in the UI.
    • Click on the Tools link the UI, and download the remoting package.
    • Copy the attached script, save it in a file named "environment.bsh"
    • Edit the script so that the serverHost, username, password match your login credentials.
    • Edit the script so that it is searching for the correct environment name (the example uses "Build-Farm")
    • From your command line, go to the /bin directory of the anthill3-remoting directory (created when you unzipped the download from step one)
    • Run the following on linux: ./ah3client.sh environment.bsh or if you are using windows: ah3client.cmd environment.bsh

AHPSCRIPTS-100

import com.urbancode.anthill3.domain.workflow.*; 
 import com.urbancode.anthill3.main.client.*; 
 import com.urbancode.anthill3.persistence.*; 
 import com.urbancode.anthill3.domain.servergroup.*; 


 String serverHost = "localhost"; 
 int serverPort = 4567; 
 String userName = "admin"; 
 String password = "admin"; 

 // obtain connection to the Anthill server 
 AnthillClient anthill = AnthillClient.connect(serverHost, serverPort, userName, password); 

 // create a Unit of Work 
 UnitOfWork uow = anthill.createUnitOfWork(); 

 WorkflowCase[] workflowCases = WorkflowCaseFactory.getInstance().restoreAll(); 

 String EnvironmentName = "Build-Farm"; 

 for (int x=0; x<workflowCases.length; x++) { 
    ServerGroup serverGroup = workflowCases[x].getServerGroup(); 
    if (EnvironmentName.equals(serverGroup.getName())){ 
     int ID = workflowCases[x].getBuildLife().getId(); 
        System.out.println("BuildLife id = " + ID + " exists in " + EnvironmentName ); 
    }//end if 
 }//end for 

 uow.close();

Change All SVN Populate Workspace Steps to Use Export Instead of Checkout

  • Anthill 3.7.0 introduced the ability to do a svn export instead of a checkout which can offer a space and time savings. A remote script can find and change all the existing steps to use this.

AHPSCRIPTS-106

import com.urbancode.anthill3.main.client.AnthillClient; 
 import com.urbancode.anthill3.persistence.UnitOfWork; 
 import com.urbancode.anthill3.domain.jobconfig.*; 
 import com.urbancode.anthill3.domain.source.svn.*; 
 import com.urbancode.anthill3.domain.step.*; 

 String serverHost = "anthill3.mycompany.com"; 
 int serverPort = 4567; 
 String userName = "admin"; 
 String password = "admin"; 

 // obtain connection to the Anthill server 
 AnthillClient anthill = AnthillClient.connect(serverHost, serverPort, userName, password); 

 // create a Unit of Work 
 UnitOfWork uow = anthill.createUnitOfWork(); 

 for (JobConfig jobConfig : JobConfigFactory.getInstance().restoreAll()) { 
     for (StepConfig stepConfig : jobConfig.getStepConfigArray()) { 
         if (stepConfig instanceof SvnPopulateWorkspaceStepConfig) { 
             SvnPopulateWorkspaceStepConfig svnPopulate = (SvnPopulateWorkspaceStepConfig) stepConfig; 
             System.out.println("SVN Populate found on job " + jobConfig.getName() + " (" + jobConfig.getId() + 
                 ") as step " + stepConfig.getName()); 
             svnPopulate.setUseExport(true); 
         } 
     } 
 } 

 uow.commitAndClose();

Find All Agents With Incompatible Version

  • This script will return which agents the server is reporting as to having an invalid version associated with them.

AHPSCRIPTS-135

import com.urbancode.anthill3.main.client.AnthillClient; 
 import com.urbancode.anthill3.persistence.UnitOfWork; 
 import com.urbancode.anthill3.domain.agent.*; 
 import com.urbancode.anthill3.services.agent.*; 

 //The following settings are for establishing a connection to the anthill server 
 //Please change accordingly to your anthillpro server configuration 
 String serverHost = "localhost"; 
 int serverPort = 4567; 
 String userName = "admin"; 
 String password = "admin"; 
 //---------------------------------------------------------------------------------------------------------------------- 

 // obtain connection to the Anthill server 
 AnthillClient anthill = AnthillClient.connect(serverHost, serverPort, userName, password); 

 // create a Unit of Work 
 UnitOfWork uow = anthill.createUnitOfWork(); 

 // get an instance of the AgentManager 
 AgentManager manager = AgentManager.getInstance(); 
 String[] invalidAgents = null; 

 // get the list of Agents 
 Agent[] agentArray = AgentFactory.getInstance().restoreAll(); 

 // get Agents that have an incorrect version associated with them 
 invalidAgents = manager.getVersionMismatchAgentNameArray(); 

 // this will be used to store total mismatches 
 invalidTotal = 0; 

 print("\n"); 
 print("|===AGENTS REPORTING INVALID STATUS===|\n"); 

 for (entry : invalidAgents){ // get each invalid Agent 
 for (thisAgent : agentArray){ // get each Agent 
 if(thisAgent.getName().equals(entry)){ 
 print(thisAgent); 
 print(manager.getAgentStatus(thisAgent)); 
 invalidTotal++; 
 } 
 } 
 } 

 print("\n"); 
 print("|===MISMATCHES===|"); 
 print(" TOTAL: " + invalidTotal); 

 uow.commitAndClose();

Create a Folder and Append Name if One Already Exists

AHPSCRIPTS-134

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.folder.*;
import com.urbancode.anthill3.domain.persistent.PersistenceException;

//The following settings are for establishing a connection to the anthill server
String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

//obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,
                                              userName, password);

// create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();




String fname = "ZNAME"; //Folder name to create
String parent = "/"; //Parent folder
String copy = " (New)";
boolean notdone = true;




print("Now attempting to create a folder with name: " + fname);
Thread.sleep(750);
print("");
Folder parentFolder = FolderFactory.getInstance().restoreForName(parent);

while (notdone == true) {
	if (FolderFactory.getInstance().restoreForName(fname) !=null) {
		print(FolderFactory.getInstance().restoreForName(fname) + " already exists!");
		fname = fname+copy;
	}
	else notdone = false;
}
print("Folder with name '" + fname + " is being created . . .");


Folder creationFolder = new Folder(true);
creationFolder.setName(fname);
creationFolder.setParent(parentFolder);
creationFolder.setActive(true);
creationFolder.store();
Thread.sleep(400);

try{
	uow.commit();
	print(FolderFactory.getInstance().restoreForName(fname) + " has been created.");
	uow.close();
}
catch (Exception e){
	print("Does the folder '" + fname + "' already exist under '" + parent + "'?\n\n");
	print("---STACKTRACE BEGAN---");
	e.printStackTrace();
	print("---STACKTRACE ENDED---");
}


//BMG


Find All Agents Online And Offline

  • This can be heavily modified for practical uses in other applications (such as finding agents online in each environment versus offline, return just a list of online agents, return just a list of offline agents, etc.). The following script will return the status of all agents that the server is aware of:

AHPSCRIPTS-128

/***********************************************************************/
/*                                                                     */
/* This script will retrieve all online agents across all environments */
/* and print this information out                                      */
/*                                                                     */
/* @author BMG                                                         */
/* @date 02/22/2011                                                    */
/*                                                                     */
/***********************************************************************/

import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.agent.*;
import com.urbancode.anthill3.services.agent.AgentManager;

//The following settings are for establishing a connection to the
//anthill server
String username  = "admin";
String password  = "admin";
String host      = "localhost";
int remotingPort = 4567;

//obtain connection to the Anthill server
AnthillClient anthill = AnthillClient.connect(host, remotingPort, username, password);

//create a Unit of Work
UnitOfWork uow = anthill.createUnitOfWork();

//Make room for debug info
print("\n\n");

//quick description
Thread.sleep(333);
print("Now attempting to query all agents, and return status of each.  PLEASE WAIT. . .");
Thread.sleep(500);

//main script
String agentName;
String environmentName;
int online  = 0;
int offline = 0;
int total   = 0;
int none = 0;
boolean others = false;
AgentFactory agentFactory = AgentFactory.getInstance();
Agent[] agentArray = agentFactory.restoreAll();

print("");
for (index : agentArray){
    status = AgentManager.getInstance().getAgentStatus(index);
    if (status != null && status.isOnline()){
        agentName = index.getName();
	    print("[     ] - Agent '" + agentName + "' is returning ONLINE.");
		online++;
    }
	else if (status != null && !status.isOnline()){
	    agentName = index.getName();
		print("[ERROR] - Agent '" + agentName + "' is returning OFFLINE.");
		offline++;
	}
	else{
	    print(status);
		others = true;
	}
	total++;
}
Thread.sleep(1000);
print("");
print("");
print("+------------------------+ ");
print("+ TOTAL ONLINE AGENTS    : " + online);
print("+ TOTAL OFFLINE AGENTS   : " + offline);
if (others==true){
    print("+ TOTAL UNKNOWN AGENTS   : " + none);
}
print("+ TOTAL AGENTS           : " + total);
print("+------------------------+ ");

uow.commitAndClose();
print("\n\n");

//BMG

Change Environments of an Agent

AHPSCRIPTS-126

Script to change environments on ONE AGENT:

/********************************************************************************************/
/*                                                                                          */
/* CHANGEAGENTENVIRONMENTS.BSH                                                              */
/*                                                                                          */
/* Anthill Remoting API Script to add all agents in anthillpro to the specified environment */
/*                                                                                          */
/* Author: Brad M. Galla                                                                    */
/* Date: 02/11/2011 @ 12:18                                                                 */
/*                                                                                          */
/********************************************************************************************/

/*===============================*/
/*                               */
/* IMPORTS                       */
/*                               */
/*===============================*/
import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.servergroup.*;
import com.urbancode.anthill3.domain.agent.*;

/*===============================*/
/*                               */
/* CLIENT PARAMETERS             */
/*                               */
/*===============================*/
String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

/*===============================*/
/*                               */
/* CLIENT CONNECTION             */
/*                               */
/*===============================*/
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,userName, password);
UnitOfWork uow = anthill.createUnitOfWork();
print("\n");
print("===========================");
print(" AGENT CONFIG DEBUG SCREEN");
print("===========================");

/*===============================*/
/*                               */
/* SCRIPT                        */
/*                               */
/*===============================*/
ServerGroupFactory servergroupfactory = ServerGroupFactory.getInstance();
ServerGroup environment = servergroupfactory.restoreForName("Build-Farm");  //Replace with Environment Name
AgentFactory agentfactory = AgentFactory.getInstance();
Agent[] agentArray = agentfactory.restoreAllNotIgnored();
String agentName;
int subtotal=0;
int total=0;
int warnings=0;

    for (Agent index : agentArray){
	    agentName = index.getName();
		total++;
		print("[INFO] Attempting to configure " + agentName + " in " + environment.getName());
	    
		if (environment.containsServer(index)){
			print("[WARN] Agent " + agentName + " already in environment " + environment.getName() + "!!! Skipping. . .");
			warnings++;
		}
		
		else{
            environment.addServer(index);
            index.setConfigured(true);
		    agentName = index.getName();
		    print("[SUCC] Agent " + agentName + " configured successfully.");
			subtotal++;
    }
}

//Count successes, warnings, and total agents returned
print("");
print("++++++++++++++++|");
print(" TOTAL SUCCESS: | " + subtotal);
print(" TOTAL WARNING: | " + warnings);
print(" TOTAL AGENTS:  | " + total);
print("++++++++++++++++|");

uow.commitAndClose();

//BMG

Change environments on ALL AGENTS:

/********************************************************************************************/
/*                                                                                          */
/* CHANGEAGENTALLENVIRONMENTS.BSH                                                           */
/*                                                                                          */
/* Anthill Remoting API Script to add all agents in anthillpro to all environments          */
/*                                                                                          */
/* Author: Brad M. Galla                                                                    */
/* Date: 02/17/2011 @ 15:06                                                                 */
/*                                                                                          */
/********************************************************************************************/

/*===============================*/
/*                               */
/* IMPORTS                       */
/*                               */
/*===============================*/
import com.urbancode.anthill3.main.client.AnthillClient;
import com.urbancode.anthill3.persistence.UnitOfWork;
import com.urbancode.anthill3.domain.servergroup.*;
import com.urbancode.anthill3.domain.agent.*;

/*===============================*/
/*                               */
/* CLIENT PARAMETERS             */
/*                               */
/*===============================*/
String serverHost = "localhost";
int serverPort = 4567;
String userName = "admin";
String password = "admin";

/*===============================*/
/*                               */
/* CLIENT CONNECTION             */
/*                               */
/*===============================*/
AnthillClient anthill = AnthillClient.connect(serverHost, serverPort,userName, password);
UnitOfWork uow = anthill.createUnitOfWork();
print("\n");
print("===========================");
print(" AGENT CONFIG DEBUG SCREEN");
print("===========================");

/*===============================*/
/*                               */
/* SCRIPT                        */
/*                               */
/*===============================*/
ServerGroupFactory servergroupfactory = ServerGroupFactory.getInstance();
ServerGroup[] environments = servergroupfactory.restoreAll();
AgentFactory agentfactory = AgentFactory.getInstance();
Agent[] agentArray = agentfactory.restoreAllNotIgnored();
String agentName;
int subtotal=0;
int total=0;
int warnings=0;
int environmentcount=0;

for(ServerGroup environmentindex : environments)
{
	print("");
	print("********************************************************");
	print("  CONFIGURING:  " + environmentindex.getName());
	print("********************************************************");
	for (Agent index : agentArray)
	{
		agentName = index.getName();
		total++;
		print("[INFO] Configuring " + agentName);
    
		if (environmentindex.containsServer(index))
		{
			print("[WARN] Configuring " + agentName + " failed...already exists!");
			warnings++;
		}
	
		else
		{
			environmentindex.addServer(index);
			index.setConfigured(true);
			agentName = index.getName();
			print("[SUCC] Configuring " + agentName + " was successful.");
			subtotal++;
		}
	}
	environmentcount++;
}

//Count successes, warnings, and total agents returned
print("");
print("+++++++++++++++++++++| ");
print(" TOTAL SUCCESSES:    | " + subtotal);
print(" TOTAL WARNINGS:     | " + warnings);
print(" TOTAL AGENTS:       | " + total/environmentcount);
print(" TOTAL ENVIRONMENTS: | " + environmentcount);
print("+++++++++++++++++++++| ");

uow.commitAndClose();

//BMG

Copy Project

AHPSCRIPTS-125

import com.urbancode.anthill3.main.client.AnthillClient; 
 import com.urbancode.anthill3.persistence.UnitOfWork; 
 import com.urbancode.anthill3.domain.project.*; 

 String serverHost = "localhost"; 
 int serverPort = 4567; 
 String userName = "admin"; 
 String password = "admin"; 

 // obtain connection to the Anthill server 
 anthill = AnthillClient.connect(serverHost, serverPort, userName, password); 

 // create a Unit of Work 
 uow = anthill.createUnitOfWork(); 

 project = ProjectFactory.getInstance().restoreForName("My Project"); 

 dupe = project.duplicate(); 
 dupe.setName("My Copied Project"); 
 dupe.store(); 

 uow.commitAndClose();