Use scripting language to access models in Astah


smarter2 Use scripting language to access models in Astah

We have a free plug-in to enable you to access models within Astah using script language called “Astah Script Plug-in“.
Using this plug-in enables you to perform what Astah’s standard functionalities do not offer such as extracting model information as you want and edit them at all once..etc.

download Astah script plugin

This page will give you sample scripts that you can start using today!
(These sample are available in Astah Professional & Community 7.0 and GSN 1.1 or later. If you are using older version, you need to edit – this page may help.)


Create Models/Diagrams

Get Model Information

Edit/Search Models

Mind Map

Others


Create a new class diagram

var newDiagramName = 'New Class Diagram';
 
run();
 
function run() {
    if (!isSupportedAstah()) {
        print('This edition is not supported');
    }
 
    with(new JavaImporter(
            com.change_vision.jude.api.inf.editor)) {
        //Edit the astah model
        TransactionManager.beginTransaction();
        var editor = astah.getDiagramEditorFactory().getClassDiagramEditor();
        var newDgm = editor.createClassDiagram(astah.getProject(), newDiagramName);
        TransactionManager.endTransaction();
        print('New Class Diagram was created!');
    }
     
    //Open the diagram
    var dgmViewManager = astah.getViewManager().getDiagramViewManager();
    dgmViewManager.open(newDgm);
}
 
function isSupportedAstah() {
    var edition = astah.getAstahEdition();
    print('Your edition is ' + edition);
    if (edition == 'professional' || edition == 'UML') {
        return true;
    } else {
        return false;
    }
}

Download this Script

 

Create a new ER Entity with logical and physical names

var entities = [
                'Entity1LogicalName', 'Entity1PhysicalName',
                'Entity2LogicalName', 'Entity2PhysicalName',
                'Entity3LogicalName', 'Entity3PhysicalName'
               ];
 
run();
 
function run() {
    //Edit the astah model
    var editor = astah.getModelEditorFactory().getERModelEditor();
 
    var erModel = getOrCreateERModel(editor);
    var erSchema = erModel.getSchemata()[0];
    with(new JavaImporter(
            com.change_vision.jude.api.inf.editor)) {
        for (var i = 0; i < entities.length; i += 2) {
            var logicalName = entities[i];
            var physicalName = entities[i + 1];
            try {
                TransactionManager.beginTransaction();
                var newEntity = editor.createEREntity(erSchema, logicalName, physicalName);
                print('Created EREntity: ' + logicalName);
                TransactionManager.endTransaction();
            } catch (e) {
                print('Failed to create EREntity: ' + logicalName);
                TransactionManager.abortTransaction();
            }
        }
    }
}
 
function getOrCreateERModel(editor) {
    with(new JavaImporter(
            com.change_vision.jude.api.inf.model,
            com.change_vision.jude.api.inf.editor)) {
        //Search ERModel
        var elements = astah.findElements(IERModel.class);
        if (elements.length > 0) {
            return elements[0];
        }
 
        //Create ERModel
        TransactionManager.beginTransaction();
        erModel = editor.createERModel(astah.getProject(), 'ER Model');
        TransactionManager.endTransaction();
    }
 
    return erModel;
}

Download this Script

List up all the classes on a currently-open diagram

//This script writes out all the classifiers in the current Astah project.
with(new JavaImporter(
        com.change_vision.jude.api.inf.model)) {
    classes = astah.findElements(IClass.class);
    for(var i in classes) {
        print(classes[i].getName());
    }
}

Download this Script

 

List up all the Index information defined in ER model

with(new JavaImporter(
        com.change_vision.jude.api.inf.model)) {
    var entities = astah.findElements(IEREntity.class);
    for(var i in entities) {
        var entity = entities[i];
        var indexList = entity.getERIndices();
        if (indexList.length > 0) {
            print('ENTITY: ' + entity.getName());
            for(var j in indexList) {
                var index = indexList[j];
                //print index
                print('  INDEX[' + j + ']: ' + index.getName());
                print(', ' + index.getKind());
                if (index.isUnique()) print(', unique');
                print('');
                 
                //print attributes
                var attributes = index.getERAttributes();
                for(var k in attributes) {
                    var attribute = attributes[k];
                    print('    ATTR[' + k + ']: ' + attribute.getName());
                }
            }
            print('');
        }
    }
}

Download this Script

 

List up all the Package and Class names

run();
 
function run() {
    var project = astah.getProject();
    printPackageInfo(project);
}
 
function printPackageInfo(iPackage) {
    print("Package name: " + iPackage.getName());
    print("Package definition: " + iPackage.getDefinition());
 
    with(new JavaImporter(
            com.change_vision.jude.api.inf.model)) {
        // Display packages and classes
        var namedElements = iPackage.getOwnedElements();
        for (var i in namedElements) {
            var namedElement = namedElements[i];
            if (namedElement instanceof IPackage) {
                printPackageInfo(namedElement);
            } else if (namedElement instanceof IClass) {
                printClassInfo(namedElement);
            }
        }
    }
}
 
function printClassInfo(iClass) {
    print("Class name: " + iClass.getName());
    print("Class definition: " + iClass.getDefinition());
 
    // Display all attributes
    var iAttributes = iClass.getAttributes();
    for (var i in iAttributes) {
        printAttributeInfo(iAttributes[i]);
    }
 
    // Display all operations
    var iOperations = iClass.getOperations();
    for (var i in iOperations) {
        printOperationInfo(iOperations[i]);
    }
 
    // Display inner class information
    var classes = iClass.getNestedClasses();
    for (var i in classes) {
        printClassInfo(classes[i]);
    }
}
 
function printOperationInfo(iOperation) {
    print("Operation name: " + iOperation.getName());
    print("Operation returnType: " + iOperation.getReturnTypeExpression());
    print("Operation definition: " + iOperation.getDefinition());
}
 
function printAttributeInfo(iAttribute) {
    print("Attribute name: " + iAttribute.getName());
    print("Attribute type: " + iAttribute.getTypeExpression());
    print("Attribute definition: " + iAttribute.getDefinition());
}

Download this Script

 

List up all the properties of selected model element

run();
 
function run() {
    var targets = getSelectedPresentationsInDiagramEditor();
 
    if (targets.length === 0) {
        print('Please select an element in a diagram');
        return;
    }
 
    for (var i in targets) {
        printAllProperties(targets[i]);
    }
}
 
function getSelectedPresentationsInDiagramEditor() {
    var diagramViewManager = astah.getViewManager().getDiagramViewManager();
    return diagramViewManager.getSelectedPresentations();
}
 
function printAllProperties(presentation) {
    with(new JavaImporter(
            java.util)) {
        var props = presentation.getProperties();
        var keyList = new ArrayList(props.keySet());
        Collections.sort(keyList);
        print('---------------------------');
        for (var i = 0; i < keyList.size(); i++) {
            var key = keyList.get(i);
            var value = props.get(key);
            print(key + ': ' + value);
        }
        print('---------------------------');
    }
}

Download this Script

 

Count classes on a currently-open diagram

with (new JavaImporter(
        com.change_vision.jude.api.inf.model)) {
    classes = astah.findElements(IClass.class);
    print('Class # = ' + classes.length);
}

Download this Script

 

Export Class information in csv format

//CSV format:
// "Name of a class", "Name of the parent model", "Definition of the class"
run();
 
function run() {
    exportClassesInCsv();
}
 
function exportClassesInCsv() {
    with(new JavaImporter(
            com.change_vision.jude.api.inf.model)) {
        classes = astah.findElements(IClass.class);
    }
     
    var csvFile = selectCsvFile();
    if (csvFile == null) {
        print('Canceled');
        return;
    }
    print('Selected file = ' + csvFile.getAbsolutePath());
    if (csvFile.exists()) {
        var msg = "Do you want to overwrite?";
        var ret = JOptionPane.showConfirmDialog(scriptWindow, msg);
        if (ret != JOptionPane.YES_OPTION) {
            print('Canceled');
            return;
        }
    }
 
    with(new JavaImporter(
            java.io)) {
        var writer = new BufferedWriter(new FileWriter(csvFile));
         
        for(var i in classes) {
            var clazz = classes[i];
            var rowData = [];
            rowData.push(clazz.getName());
            rowData.push(clazz.getOwner().getName());
            rowData.push(clazz.getDefinition());
            writeRow(writer, rowData);
        }
         
        writer.close();
    }
}
 
function selectCsvFile() {
    with(new JavaImporter(
            java.io,
            javax.swing)) {
        var chooser = new JFileChooser();
        var selected = chooser.showSaveDialog(scriptWindow);
        if (selected == JFileChooser.APPROVE_OPTION) {
            var file = chooser.getSelectedFile();
            if (file.getName().toLowerCase().endsWith('.csv')) {
                return file;
            } else {
                return new File(file.getAbsolutePath() + '.csv');
            }
        } else {
            return null;
        }
    }
}
 
function writeRow(writer, rowData) {
    for (var i in rowData) {
        writeItem(writer, rowData[i]);
        if (i < rowData.length - 1) {
            writer.write(',');
        }
    }
    writer.newLine();
}
 
function writeItem(writer, data) {
    writer.write('"');
    writer.write(escapeDoubleQuotes(data));
    writer.write('"');
}
 
function escapeDoubleQuotes(data) {
    return data.replaceAll("\"", "\"\"");
}

Download this Script

 

List up all the messages without Operation in Sequence diagram

var COLOR_PROPERTY_KEY = "font.color";
var newColor = '#0000ff';
 
run();
 
function run() {
    var targets = searchMessagesWithoutOperation();
 
    if (targets.length === 0) {
        print('No target messages found');
        return;
    }
     
    /*
    TransactionManager.beginTransaction();
    for (var i in targets) {
        edit(targets[i]);
    }
    TransactionManager.endTransaction();
 
    println('The color of the messages were changed.');
    */
}
 
function searchMessagesWithoutOperation() {
    with(new JavaImporter(
        com.change_vision.jude.api.inf.model)) {
        var targets = [];
        var messages = astah.findElements(IMessage.class);
        for (var i in messages) {
            var message = messages[i];
            if (message.isReturnMessage() || message.isCreateMessage()) {
                continue;  //ignore
            }
            var operation = message.getOperation();
            if (operation === null) {
                targets.push(message);
                print('HIT: Message [' + message.getName()
                    + '] in Sequence diagram [' + message.getPresentations()[0].getDiagram().getFullName('::') + ']');
            }
        }
    }
    return targets;
}
 
function edit(target) {
    var presentations = target.getPresentations();
    for (var j in presentations) {
        var messagePs = presentations[j];
        // Change color of the message
        messagePs.setProperty(COLOR_PROPERTY_KEY, newColor);
    }
}

Download this Script

 

List up TaggedValues

function printTaggedValueInfo(model) {
    if(model == null) {
        return
    }
    var taggedValues = model.getTaggedValues()
    for each(var taggedValue in taggedValues) {
        print(taggedValue.getKey() + ":" + taggedValue.getValue())
    }
}

 

List up TaggedValues of selected model elements on diagram

function printSelectedPresentationsTaggedValueInfo() {
    var viewManager = astah.getViewManager()
    var diagramViewManager = viewManager.getDiagramViewManager()
    var selectedPresentations = diagramViewManager.getSelectedPresentations()
    for each(var selectedPresentation in selectedPresentations) {
        printTaggedValueInfo(selectedPresentation.getModel())
    }
}

 

List up TaggedValues of selected models in the structure tree

function printSelectedEntitiesTaggedValueInfo() {
    var viewManager = astah.getViewManager()
    var projectViewManager = viewManager.getProjectViewManager()
    var selectedEntities = projectViewManager.getSelectedEntities()
    for each(var selectedEntity in selectedEntities) {
        printTaggedValueInfo(selectedEntity)
    }
}

 

List up models by its stereotype

var IElement = Java.type('com.change_vision.jude.api.inf.model.IElement');
var Arrays = Java.type('java.util.Arrays');
  
// Search by stereotype
var stereotype = "stereotype"
  
for each(var element in astah.findElements(IElement.class)) {
    if(containsStereotype(element, stereotype)) {
        print(element.getName())
    }
 }
  
function containsStereotype(element, stereotype) {
    var stereotypes = Arrays.asList(element.getStereotypes())
    return stereotypes.contains(stereotype)    
}

 

Search class with specific keyword and add color and notes

load("nashorn:mozilla_compat.js");
println = print;
  
// Add colors to model elements if they had the same keyword in [Definition Field]
importPackage(com.change_vision.jude.api.inf.model);
importPackage(com.change_vision.jude.api.inf.editor);
importPackage(com.change_vision.jude.api.inf.presentation);
  
// Color to add
var COLOR = "#BBCCFF";
// Keyword to look for in Definition field
var IDENTICAL_STRING = "a";
  
run();
  
function run() {
    var currentDiagram = getCurrentDiagram();
    if (currentDiagram == null) {
        println("error: Diagram is not opened.\n\nPlease open a diagram.");
        return;
    }
    var presentations = getPresentations(currentDiagram);
    var chengeColorPresentations = getIdenticalDefinitionPresentations(presentations, IDENTICAL_STRING);
    setColor(chengeColorPresentations, COLOR);
}
  
function getCurrentDiagram() {
    try{
        var viewManager = astah.getViewManager();
        var diagramViewManager = viewManager.getDiagramViewManager();
        return diagramViewManager.getCurrentDiagram();
    } catch(e) {
        return null;
    }
}
  
function getPresentations(currentDiagram) {
    try {
        return currentDiagram.getPresentations();
    } catch (e) {
        return new IPresentation[0];
    }
}
  
function getIdenticalDefinitionPresentations(presentations, identicalString) {
    var regularExpression = new RegExp("(.*)(" + identicalString + ")(.*)");
    var identicalDefinitionPresentations = [];
    for(var i in presentations) {
        var presentation = presentations[i];
        if (presentation == null) {
            continue;
        }
        var model = presentation.getModel();
        if (model == null) {
            continue;
        }
        if (!(model instanceof INamedElement)) {
            continue;
        }
        var definition = model.getDefinition();
        if (definition.match(regularExpression)) {
            identicalDefinitionPresentations.push(presentation);
        }
    }
    return identicalDefinitionPresentations;
}
  
function setColor(presentations, color) {
    try {
        TransactionManager.beginTransaction();
        for(var i in presentations) {
            var presentation = presentations[i];
            presentation.setProperty(PresentationPropertyConstants.Key.FILL_COLOR, color);
        }
        TransactionManager.endTransaction();
        println("info: " + presentations.length + "model elements changed its colors.");
    } catch (e) {
        TransactionManager.abortTransaction();
        println("error: Failed to color.");
        println(e);
    }
}

 

Add Setter/Getter to selected Attributes

run();
  
function run() {
    var attributes = getSelectedAttributesInProjectView();
  
    if (attributes.length === 0) {
        print('Please select attributes that you want to add setter/getter in StructureTree');
        return;
    }
  
    with(new JavaImporter(
            com.change_vision.jude.api.inf.editor)) {
        TransactionManager.beginTransaction();
        for (var i in attributes) {
            addSetterGetter(attributes[i]);
        }
        TransactionManager.endTransaction();
    }
}
  
function getSelectedAttributesInProjectView() {
    with(new JavaImporter(
            com.change_vision.jude.api.inf.model)) {
        var attributes = [];
        var projectViewManager = astah.getViewManager().getProjectViewManager();
        var selectedEntities = projectViewManager.getSelectedEntities();
        for (var i in selectedEntities) {
            var entity = selectedEntities[i];
            if (entity instanceof IAttribute) {
                attributes.push(entity);
                print('Target attribute: ' + entity.getName());
            }
        }
    }
  
    return attributes;
}
  
function addSetterGetter(attribute) {
    var editor = astah.getModelEditorFactory().getBasicModelEditor();
    var clazz = attribute.getOwner();
    var attributeName = attribute.getName();
    //setter
    var setter = editor.createOperation(clazz, getSetterName(attributeName), 'void');
    editor.createParameter(setter, attribute.getName(), attribute.getType());
    print('Added Setter Operation: ' + setter.getName());
    //getter
    var getter = editor.createOperation(clazz, getGetterName(attributeName), attribute.getType());
    print('Added Getter Operation: ' + getter.getName());
}
  
function getSetterName(attributeName) {
    return 'set' + attributeName;
}
  
function getGetterName(attributeName) {
    return 'get' + attributeName;
}

Download this Script

 

Add Stereotype to selected Models

var newStereotype = "New Stereotype";
 
run();
 
function run() {
    var targets = getSelectedClassesInDiagramEditor();
 
    if (targets.length === 0) {
        print('Please select classes you want to add the stereotype to.');
        return;
    }
 
    with(new JavaImporter(
            com.change_vision.jude.api.inf.editor)) {
        TransactionManager.beginTransaction();
        for (var i in targets) {
            addStereotype(targets[i]);
        }
        TransactionManager.endTransaction();
    }
}
 
function getSelectedClassesInDiagramEditor() {
    var targets = [];
    var diagramViewManager = astah.getViewManager().getDiagramViewManager();
    var selectedPss = diagramViewManager.getSelectedPresentations();
    for (var i in selectedPss) {
        var ps = selectedPss[i];
        //println(ps.getType());
        if (ps.getType() == 'Class' && !(ps.getModel() in targets)) {
            targets.push(ps.getModel());
            print('HIT: ' + ps.getModel().getName());
        }
    }
 
    return targets;
}
 
function addStereotype(target) {
    target.addStereotype(newStereotype);
}

Download this Script

 

Rename Lifelines with related Actor’s Type name

run();
  
function run() {
    var TransactionManager = Java.type('com.change_vision.jude.api.inf.editor.TransactionManager');
    var targets = searchTargetLifeline();
  
    if (targets.length === 0) {
        print('No target lifeline found.');
        return;
    }
  
    TransactionManager.beginTransaction();
    for (var i in targets) {
        updateName(targets[i]);
    }
    TransactionManager.endTransaction();
  
    print('The name of lifelines were updated.');
}
  
function searchTargetLifeline() {
    var ILifeline = Java.type('com.change_vision.jude.api.inf.model.ILifeline');
    var targets = [];
    var lifelines = astah.findElements(ILifeline.class);
    for (var i in lifelines) {
        var lifeline = lifelines[i];
        var type = lifeline.getBase();
        if (type != null && type.hasStereotype('actor')) {
            targets.push(lifeline);
            print('HIT: ' + lifeline.getName() + ': ' + type.getName());
        }
    }
    return targets;
}
  
function updateName(lifeline) {
    var orgName = lifeline.getName();
    var type = lifeline.getBase();
    var typeName = type.getName();
    var newName = typeName.charAt(0).toLowerCase() + typeName.slice(1);
    lifeline.setName(newName);
    print('Updated: ' + orgName + ' ---> ' + newName);
}

 

Delete all the notes from currently-open diagram

run();
  
function run() {
    var notes = getAllNotesInDiagramEditor();
    if (notes.length === 0) return;
  
    var TransactionManager = Java.type('com.change_vision.jude.api.inf.editor.TransactionManager');
    TransactionManager.beginTransaction();
    notes.forEach(function(note) {
        deleteElement(note);
    });
    TransactionManager.endTransaction();
}
  
function getAllNotesInDiagramEditor() {
    var diagramViewManager = astah.getViewManager().getDiagramViewManager();
    var diagram = diagramViewManager.getCurrentDiagram();
    if (diagram === null) {
        print('Open any diagram.');
        return [];
    }
  
    var presentations = Java.from(diagram.getPresentations());
    return presentations.filter(function(p) {
        return p.type.equals('Note');
    });
}
  
function deleteElement(presentation) {
    var modelEditor = astah.getModelEditorFactory().getBasicModelEditor();
    modelEditor.delete(presentation.getModel());
}

 

List up all the topics on currently-open Mind Map

//This script writes out a list of text in the current mindmap.
//The format is like a WiKi.
var depth = 0;
var INDENT_STR = '  '; //2 spaces
var ITEM_MARKER_STR = '* ';
 
run();
 
function run() {
    with(new JavaImporter(
            com.change_vision.jude.api.inf.model)) {
        var diagramViewManager = astah.getViewManager().getDiagramViewManager();
        var diagram = diagramViewManager.getCurrentDiagram();
        if (!(diagram instanceof IMindMapDiagram)) {
            print('Open a mindmap and run again.');
            return;
        }
     
        var rootTopic = diagram.getRoot();
        depth = 0;
        printTopics(rootTopic);
    }
}
 
function printTopics(topic) {
    var topicLabel = topic.getLabel().replaceAll('\n', ' ');
    print(getIndent(depth) + ITEM_MARKER_STR + topicLabel);
 
    var topics = topic.getChildren();
    depth++;
    for (var i in topics) {
        if (topics[i].getType() == 'Topic') { //skip MMBoundary
            printTopics(topics[i]);
        }
    }
    depth--;
}
 
function getIndent(depth) {
    var indent = '';
    for (var i = 0; i < depth; i++) {
        indent += INDENT_STR;
    }
    return indent;
}

Download this Script

 

Close/Open topics by specifying level

var PresentationPropertyConstants = Java.type('com.change_vision.jude.api.inf.presentation.PresentationPropertyConstants');
var IMindMapDiagram = Java.type('com.change_vision.jude.api.inf.model.IMindMapDiagram');
var TransactionManager = Java.type('com.change_vision.jude.api.inf.editor.TransactionManager');
var level = 0;
var doOpen = undefined;
var TARGET_LEVEL = 1;//Specify the target level
  
run();
  
function run() {
    var diagramViewManager = astah.getViewManager().getDiagramViewManager();
    var diagram = diagramViewManager.getCurrentDiagram();
    if (!(diagram instanceof IMindMapDiagram)) {
        print('Open a mindmap and run again.');
        return;
    }
    var rootTopic = diagram.getRoot();

    TransactionManager.beginTransaction();
    reverseTopicVisibility(rootTopic);
    TransactionManager.endTransaction();

    if (doOpen) {
        print('Opened subtopics of LEVEL ' + TARGET_LEVEL);
    } else {
        print('Closed subtopics of LEVEL ' + TARGET_LEVEL);
    }
}
  
function reverseTopicVisibility(topic) {
    if (level === TARGET_LEVEL) {
        if (doOpen == undefined) {
            if (topic.getProperty('sub_topic_visibility') == 'false') {
                doOpen = true;
            } else {
                doOpen = false;
            }
        }
  
        topic.setProperty('sub_topic_visibility', doOpen);
    }
    var topics = topic.getChildren();
    level++;
    for (var i in topics) {
        if (topics[i].getType() =='Topic') { //skip MMBoundary
            reverseTopicVisibility(topics[i]);
        }
    }
    level--;
}

 

Add index numbers to all the topics from the top

var PresentationPropertyConstants = Java.type('com.change_vision.jude.api.inf.presentation.PresentationPropertyConstants');
var TransactionManager = Java.type('com.change_vision.jude.api.inf.editor.TransactionManager');
   
var number = 'icon'; // please select text or icon.
   
putSerialNumber();
   
function putSerialNumber() {
    var topics = getSelectedTopicsInDiagramEditor();
   
    if (topics.length === 0) {
        print('Please select a topic');
        return;
    }
   
    topics.forEach(function (topic) {
        if (number === 'text') {
            setNumberText(topic);
        } else if (number === 'icon') {
            setNumberIcon(topic);
        }
    });
}
   
function getSelectedTopicsInDiagramEditor() {
    var diagramViewManager = astah.getViewManager().getDiagramViewManager();
    var presentations =  diagramViewManager.getSelectedPresentations();
   
    return Java.from(presentations).filter(function(p) {
        return p.getType() === 'Topic';
    });
}
   
function setNumberText(topic) {
    var REGEXP_START_WITH_NUMBER = /^\d+\.\s/;
    var children = Java.from(topic.getChildren());
   
    TransactionManager.beginTransaction();
    children.forEach(function(child, index) {
        var label = child.getLabel();
        if (label.search(REGEXP_START_WITH_NUMBER) !== -1) {
            label = label.replace(REGEXP_START_WITH_NUMBER, '');
        }
        var no = index + 1;
        child.setLabel(no + '. ' + label);
    });
    TransactionManager.endTransaction();
}
   
function setNumberIcon(topic) {
    var REGEXP_NUMBER_ICON = /^number_\d+/;
    var children = Java.from(topic.getChildren());
   
    TransactionManager.beginTransaction();
    children.forEach(function(child, index) {
        var icons = child.getProperty('icons');
        var iconsToKeep = icons.replace(REGEXP_NUMBER_ICON, '');
        var no = index + 1;
        child.setProperty('icons', 'number_' + no + ',' + iconsToKeep);
    });
    TransactionManager.endTransaction();
}

Export Mind Map topics with hyperlink information in text format

var depth = 0;
var INDENT_STR = '\t';
 
run();
  
function run() {
    depth = 0;
    with(new JavaImporter(
            com.change_vision.jude.api.inf.model)) {
        var diagramViewManager = astah.getViewManager().getDiagramViewManager();
        var diagram = diagramViewManager.getCurrentDiagram();
        if (!(diagram instanceof IMindMapDiagram)) {
            print('Open a mindmap and run again.');
            return;
        }
        printTopics(diagram.getRoot());
    }
}
  
function printTopics(topic) {
    var topicLabel = topic.getLabel().replaceAll('\n', ' ');
    print(getIndent(depth) + topicLabel);
    printHyperlinks(topic)
  
    var topics = Java.from(topic.getChildren());
    depth++;
    topics.forEach(function (topic) {
        if (topic.getType() == 'Topic') {
            printTopics(topic);
        }
    });
    depth--;
}
 
function printHyperlinks(topic) {
    var links = Java.from(topic.getHyperlinks());
    links.forEach(function (link) {
        if (link.isFile()) {
            printHyperlinkInfo('[file]', link);
        } else if(link.isURL()) {
            printHyperlinkInfo('[url]', link);
        }                     
    });
}
 
function printHyperlinkInfo(title, link) {
    print(getIndent(depth) + title + 'name:' + link.getName()
        + INDENT_STR + 'path:' + link.getPath() + INDENT_STR + 'comment:' + link.getComment());
}
 
function getIndent(depth) {
    var indent = '';
    for (var i = 0; i < depth; i++) {
        indent += INDENT_STR;
    }
    return indent;
}

Download this Script

 

Show edition of currently-running Astah

//This script shows how to check the edition of Astah.
run();
 
function run() {
    if (!isSupportedAstah()) {
        print('This edition is not supported');
    }
 
    //Use a special API here.
    //Ex:
    //TransactionManager.beginTransaction();
    //Edit the astah model
    //TransactionManager.endTransaction();
}
 
function isSupportedAstah() {
    with(new JavaImporter(
        com.change_vision.jude.api.inf.editor)) {
        var edition = astah.getAstahEdition();
        print('Your edition is ' + edition);
        if (edition == 'professional' || edition == 'UML') {
            return true;
        } else {
            return false;
        }
    }
}

Download this Script

 

Show a dialogue to use Java GUI

//This script shows a GUI by using AWT and Swing of Java.
 
with(new JavaImporter(
        java.awt,
        java.awt.event,
        javax.swing)) {
 
    var frame = new JFrame("Frame title");
    frame.setLayout(new FlowLayout());
 
    var goButton = new JButton("Go!");
    goButton.addActionListener(new ActionListener({
        actionPerformed: function(event) {
            JOptionPane.showMessageDialog(frame, "Hello!");
        }
    }));
 
    var closeButton = new JButton("Close");
    closeButton.addActionListener(new ActionListener({
        actionPerformed: function(event) {
            frame.setVisible(false);
            frame.dispose();
        }
    }));
 
    frame.add(goButton);
    frame.add(closeButton);
    frame.setSize(150, 100);
    //We must not use JFrame.EXIT_ON_CLOSE
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    //We can use 'astahWindow' instead of 'scriptWindow' here.
    frame.setLocationRelativeTo(scriptWindow);
    frame.setVisible(true);
}

Download this Script


Let’s use these Scripts!

To run these scripts in Astah, you will need to install Script Plug-in first to Astah!

download Astah script plugin

Advertisements