public synchronized void renameInstance(String oldName, String newName) throws Exception {
if (instances.get(newName) != null) {
throw new IllegalArgumentException("Instance " + newName + " already exists");
}
Instance instance = instances.get(oldName);
if (instance == null) {
throw new IllegalArgumentException("Instance " + oldName + " not found");
}
if (instance.isRoot()) {
throw new IllegalArgumentException("Root instance cannot be renamed");
}
if (instance.getPid() != 0) {
throw new IllegalStateException("Instance not stopped");
}
println(Ansi.ansi().a("Renaming instance ")
.a(Ansi.Attribute.INTENSITY_BOLD).a(oldName).a(Ansi.Attribute.RESET)
.a(" to ")
.a(Ansi.Attribute.INTENSITY_BOLD).a(newName).a(Ansi.Attribute.RESET).toString());
// remove the old instance
instances.remove(oldName);
// update instance
instance.setName(newName);
// rename directory
String oldLocationPath = instance.getLocation();
File oldLocation = new File(oldLocationPath);
String basedir = oldLocation.getParent();
File newLocation = new File(basedir, newName);
oldLocation.renameTo(newLocation);
// update the instance location
instance.setLocation(newLocation.getPath());
// create the properties map including the instance name and instance location
HashMap<String, String> props = new HashMap<String, String>();
props.put(oldName, newName);
props.put(oldLocationPath, newLocation.getPath());
// replace all references to the "old" name by the new one in etc/system.properties