Scriptプラグインで、すぐに使えるサンプル集

astah*には、スクリプト言語を使って、astah*内のモデルを編集、参照できる「Scriptプラグイン」があります。
Scriptプラグインを利用すれば、標準では搭載していない機能、例えば、条件を指定して特定のモデルを一括編集する、知りたいモデルの情報を抽出するなどという事を、astah*のAPIを使ってスクリプトを書く事で、簡単に実現できます。
linktoscript

このページでは、JavaScriptを使った、すぐに使える実用的なサンプルのスクリプトを紹介します。
(astah* professionalUMLcommunity 7.0、astah* GSN 1.1以降で利用可能なスクリプトです。これより前のバージョンでは、スクリプトの修正が必要です)


モデル/図の作成

モデル情報の取得

モデルの編集/検索

マインドマップ

その他


モデル/図の作成

新しいクラス図を作成

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;
    }
}

このスクリプトをダウンロードする

指定した論理名・物理名を用いてERエンティティを作成

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;
}

このスクリプトをダウンロードする

モデル情報の取得

開いているプロジェクトファイルに含まれるクラスの名称を表示

with(new JavaImporter(
        com.change_vision.jude.api.inf.model)) {
    classes = astah.findElements(IClass.class);
    for(var i in classes) {
        print(classes[i].getName());
    }
}

このスクリプトをダウンロードする

ERモデル中に定義されているインデックスの情報を列挙

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('');
        }
    }
}

このスクリプトをダウンロードする

パッケージ名、クラス名を列挙

//This script writes out the information of packages and classes.
//The current Astah project should have packages and classes.
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());
}

このスクリプトをダウンロードする

選択した図要素のプロパティをリスト表示

// This script prints the properties of the selected element.
// You should select an element in the DiagramEditor before running this.
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('---------------------------');
    }
}

このスクリプトをダウンロードする

開いているプロジェクトファイルに含まれるクラスの数を表示

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

このスクリプトをダウンロードする

クラスの情報をCSV形式で出力

//This script generates a CSV file about the classes in the current model.
//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("\"", "\"\"");
}

このスクリプトをダウンロードする

シーケンス図の操作が指定されていないメッセージを検索

run();

function run() {
    var targets = searchMessagesWithoutOperation();

    if (targets.length === 0) {
        print('No target messages found');
        return;
    }

}

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 printTaggedValueInfo(model) {
    if(model == null) {
        return
    }
    var taggedValues = model.getTaggedValues()
    for each(var taggedValue in taggedValues) {
        print(taggedValue.getKey() + ":" + taggedValue.getValue())
    }
}

図上で選択している要素のタグ付き値を表示する

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

タグ付き値を表示するのコードも必要です

構造ツリー上で選択しているモデルのタグ付き値を表示する

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

タグ付き値を表示するのコードも必要です

指定したステレオタイプを持つモデルを表示

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)
}

モデルの編集/検索

定義欄に同じキーワードを含むプレゼンテーションを指定した色に塗り替える

// [定義]欄に同じキーワードを含むプレゼンテーションを指定した色に塗り替えます。
// 現在開いている図のプレゼンテーションが対象です。
var infNamespace = 'com.change_vision.jude.api.inf'
var INamedElement = Java.type(infNamespace + '.model.INamedElement');
var TransactionManager = Java.type(infNamespace + '.editor.TransactionManager');
var Key = Java.type(infNamespace + '.presentation.PresentationPropertyConstants.Key');

// 塗り替えたい色
var COLOR = "#BBCCFF";
// 定義欄のキーワード
var IDENTICAL_STRING = "a";

// 以下スクリプト
run();

function run() {
    var currentDiagram = getCurrentDiagram();
    if (currentDiagram == null) {
        print("error: 図を開いていません\n\n図を開いてください。");
        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(Key.FILL_COLOR, color);
        }
        TransactionManager.endTransaction();
        print("info: " + presentations.length + "個の要素の色を変更しました。");
    } catch (e) {
        TransactionManager.abortTransaction();
        print("error: 要素の色を変更できませんでした。");
        print(e);
    }
}

選択した属性にSetter/Getter操作を追加する

//This script generates the setter/getter operations for the selected attributes.
//You should select attributes in the StructureTree before running this.
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;
}

このスクリプトをダウンロードする

選択したモデルにステレオタイプを追加する

//Only for Astah UML and Professional.
//This script adds a new stereotype to the selected classes
//in the Diagram Editor.
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);
}

このスクリプトをダウンロードする

アクターを型にもつライフラインの名前をアクターの型名に一括変更する

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);
}

開いている図から全てのノートを一括削除する

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());
}

ドメインからER属性へ定義を上書きコピーする

var IERAttribute = Java.type('com.change_vision.jude.api.inf.model.IERAttribute');
var TransactionManager = Java.type('com.change_vision.jude.api.inf.editor.TransactionManager');

run();

function run() {
    try {
        TransactionManager.beginTransaction();
        for each(var eRAttribute in astah.findElements(IERAttribute.class)) {
            var domain = eRAttribute.getDomain();
            if(domain == null) {
                continue;
            }
            print('Overwrite copying definition to ' + eRAttribute + ' from ' + domain);
            eRAttribute.setDefinition(domain.getDefinition());
        }
        TransactionManager.endTransaction();
    } catch (e) {
        TransactionManager.abortTransaction();
        print(e);
        return;
    }
    print('Finished.');
}

マインドマップ

開いているマインドマップのトピックをリスト表示

//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;
}

このスクリプトをダウンロードする

レベルを指定してトピックを開閉する

//指定したレベル(トピックの階層の深さ)のトピックを全て開閉するスクリプト
var Key = Java.type('com.change_vision.jude.api.inf.presentation.PresentationPropertyConstants.Key');
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;//指定したレベルのサブトピックを開閉します

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();

    try {
        TransactionManager.beginTransaction();
        reverseTopicVisibility(rootTopic);
        TransactionManager.endTransaction();
        print('LEVEL' + TARGET_LEVEL + 'のサブトピックを開閉しました')
    } catch (e) {
        TransactionManager.abortTransaction();
        print('error: LEVEL' + TARGET_LEVEL + 'のサブトピックを開閉できませんでした');
        print(e);
    }
}

function reverseTopicVisibility(topic) {
    if (isNaN(TARGET_LEVEL) || TARGET_LEVEL < 0) {
        throw { toString: function() { return 'TARGET_LEVELには整数値を指定してください'; } };
    }
    if (level === TARGET_LEVEL) {
        if (doOpen == undefined) {
            doOpen = topic.getProperty(Key.SUB_TOPIC_VISIBILITY) == 'false';
        }
        topic.setProperty(Key.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--;
}

このスクリプトをダウンロードする / 利用例を読む

トピックに通し番号を振る

var Key = Java.type('com.change_vision.jude.api.inf.presentation.PresentationPropertyConstants.Key');
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;
    }
    if (number !== 'text' && number !== 'icon') {
        print('Please change number to "text" or "icon".');
        return;
    }
    try {
        topics.forEach(function (topic) {
            if (number === 'text') {
                setNumberText(topic);
            } else if (number === 'icon') {
                setNumberIcon(topic);
            }
        });
    } catch (e) {
        print('error: Could not number topics.');
        print(e);
        return;
    }

}

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());

    try {
        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();
    } catch (e) {
        TransactionManager.abortTransaction();
        throw e;
    }
}

function setNumberIcon(topic) {
    var REGEXP_NUMBER_ICON = /^number_\d+/;
    var children = Java.from(topic.getChildren());

    try {
        TransactionManager.beginTransaction();
        children.forEach(function(child, index) {
            var icons = child.getProperty(Key.ICONS);
            var iconsToKeep = icons.replace(REGEXP_NUMBER_ICON, '');
            var no = index + 1;
            child.setProperty(Key.ICONS, 'number_' + no + ',' + iconsToKeep);
        });
        TransactionManager.endTransaction();
    } catch (e) {
        TransactionManager.abortTransaction();
        throw e;
    }
}

このスクリプトをダウンロードする / 利用例を読む

その他

起動中のエディションを表示

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;
        }
    }
}

このスクリプトをダウンロードする

起動中のastahの情報を表示

print("AstahVersion : " + astah.getAstahVersion());
print("AstahEdition : " + astah.getAstahEdition());
print("AstahInstallPath : " + astah.getAstahInstallPath());
print("UserHome : " + Java.type('java.lang.System').getProperty('user.home'));
print("AstahModelVersion : " + astah.getAstahModelVersion());
print("AstahAPIVersion : " + astah.getAstahAPIVersion());
print("AstahAPIModelVersion : " + astah.getAstahAPIModelVersion());

ダイアログを表示して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);
}

このスクリプトをダウンロードする


スクリプトを使う

スクリプトの実行には「astah* Scriptプラグイン」(無償)が必要です。下のボタンをクリックし、Scriptプラグイン詳細ページから、ダウンロード、インストールしてください。linktoscript

Advertisements