String portName = castPort.getName();
Iterator entities = entityList().iterator();
if (entities.hasNext()) {
Entity insideEntity = (Entity) entities.next();
Port insidePort = insideEntity.getPort(portName);
if (insidePort == null) {
insidePort = insideEntity.newPort(portName);
if (insidePort instanceof IOPort) {
IOPort castInsidePort = (IOPort) insidePort;
castInsidePort.setInput(castPort.isInput());
castInsidePort.setOutput(castPort
.isOutput());
castInsidePort.setMultiport(castPort
.isMultiport());
}
}
if (insidePort instanceof MirrorPort) {
castPort
.setAssociatedPort((MirrorPort) insidePort);
}
// Create a link only if it doesn't already exist.
List connectedPorts = insidePort
.connectedPortList();
if (!connectedPorts.contains(castPort)) {
// There is no connection. Create one.
ComponentRelation newRelation = newRelation(uniqueName("relation"));
insidePort.link(newRelation);
castPort.link(newRelation);
}
}
} finally {
workspace().doneWriting();