Skip to content

Instantly share code, notes, and snippets.

@y-matsuda
Last active February 16, 2024 05:51
Show Gist options
  • Save y-matsuda/7c06762eca6c4d4f6539 to your computer and use it in GitHub Desktop.
Save y-matsuda/7c06762eca6c4d4f6539 to your computer and use it in GitHub Desktop.
Astah Script プラグイン サンプルコード(Java8用)

概要

このページにはAstah scriptプラグイン用のコードを書き溜めています。 astah* professional/UML/community 7.0.0, astah* GSN 1.1 以降用となります。

なお、過去に書いたスクリプト(java7用)もあります。参考まで。


スクリプト一覧

// 選択している遷移の名前ラベルを遷移の始点付近に移動します
var infNamespace = 'com.change_vision.jude.api.inf'
var Key = Java.type(infNamespace + '.presentation.PresentationPropertyConstants.Key')
var ILinkPresentation = Java.type(infNamespace + '.presentation.ILinkPresentation')
var Point2D = Java.type('java.awt.geom.Point2D.Double')
//////////////////////////
var MARGIN_X = 5
var MARGIN_Y = 5
//////////////////////////
getSelectedPresentations().forEach(
function (presentation) {
if (presentation instanceof ILinkPresentation) {
return adjustPositionLabel(presentation, MARGIN_X, MARGIN_Y)
}
}
)
function adjustPositionLabel(linkPresentation, marginX, marginY) {
var startPoint = linkPresentation.getPoints()[0]
var nextPoint = linkPresentation.getPoints()[1]
var sourcePresentation = linkPresentation.getSourceEnd()
var sourcePRectangle = sourcePresentation.getRectangle()
var referencePoint = null
if (nextPoint.x > sourcePRectangle.getMaxX() && nextPoint.y > sourcePRectangle.getMaxY()) { // 右下に出力されている場合
referencePoint = new Point2D(sourcePRectangle.getMaxX(), sourcePRectangle.getMaxY())
} else if (nextPoint.x > sourcePRectangle.getMaxX() && nextPoint.y < sourcePRectangle.getMinY()) { // 右上に出力されている場合
// 未実装
} else if (nextPoint.x > sourcePRectangle.getMaxX()) { // 右辺と交わる場合
var belowPoint = new Point2D(nextPoint.x, startPoint.y)
var middleBelowPoint = new Point2D(sourcePRectangle.getMaxX(), startPoint.y)
referencePoint = new Point2D(middleBelowPoint.x,
middleBelowPoint.y + (startPoint.distance(middleBelowPoint)
* (belowPoint.distance(nextPoint) * ((sourcePRectangle.getCenterY() > nextPoint.y) ? -1 : 1))
/ startPoint.distance(belowPoint)))
} else if (nextPoint.y > sourcePRectangle.getMaxY()) { //下辺と交わる場合
var belowPoint = new Point2D(startPoint.x, nextPoint.y)
var middleBelowPoint = new Point2D(startPoint.x, sourcePRectangle.getMaxY())
referencePoint = new Point2D(middleBelowPoint.x + (startPoint.distance(middleBelowPoint)
* (belowPoint.distance(nextPoint) * ((sourcePRectangle.getCenterX() > nextPoint.x) ? -1 : 1))
/ startPoint.distance(belowPoint)), middleBelowPoint.y)
} else {
// 未実装
}
if (referencePoint == null) {
print("info: " + linkPresentation.getLabel() + "のラベルの位置計算は未実装のため移動できません。")
return
}
var newX = referencePoint.x + marginX
var newY = referencePoint.y + marginY
try {
astah.getTransactionManager().beginTransaction()
linkPresentation.setProperty(Key.NAME_X, newX)
linkPresentation.setProperty(Key.NAME_Y, newY)
astah.getTransactionManager().endTransaction()
print("info: " + linkPresentation.getLabel() + "のラベル位置を変更しました。")
} catch (e) {
astah.getTransactionManager().abortTransaction()
print("error: " + linkPresentation.getLabel() + "のラベル位置変更中にエラーが発生しました。")
throw e
}
}
function getSelectedPresentations() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedPresentations()
return Java.from(selectedPresentations)
}
var ILinkPresentation = Java.type('com.change_vision.jude.api.inf.presentation.ILinkPresentation')
adjustSelection()
function getSelectedPresentations() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedPresentations()
return Java.from(selectedPresentations)
}
function getLinkPresentations(presentations) {
var targets = [];
presentations.forEach(
function (selectedP) {
if (selectedP instanceof ILinkPresentation) {
targets.push(selectedP)
}
}
)
return targets;
}
function getSourceEnds(linkPs) {
var targets = [];
linkPs.forEach(
function (linkP) {
targets.push(linkP.getSourceEnd())
}
)
return targets;
}
function getTargetEnds(linkPs) {
var targets = [];
linkPs.forEach(
function (linkP) {
targets.push(linkP.getTargetEnd())
}
)
return targets;
}
function adjustSelection() {
var selectedPs = getLinkPresentations(getSelectedPresentations())
var diagramViewManager = astah.getViewManager().getDiagramViewManager()
diagramViewManager.unselectAll()
diagramViewManager.select(getSourceEnds(selectedPs))
// diagramViewManager.select(getTargetEnds(selectedPs))
}
// このスクリプトを1回実行すると、[関連図要素の選択補助]ダイアログが表示されます。
// ダイアログに書かれているオプションを適宜有効にして関連線を選択してください。
// [選択しても何もしない]を選択するか、×ボタンでダイアログを閉じるまで機能は有効です
//
// オプションの説明
// - 選択対象をダイアグラムエディタの中心に表示する
// - [ソース側を選択]が有効な時、選択した関連のソース側の図要素がダイアグラムエディタの中心に表示されます
// - [ターゲット側を選択]が有効な時、選択した関連のターゲット側の図要素がダイアグラムエディタの中心に表示されます
// - 選択しても何もしない
// - 関連を選択しても何も起こらなくなります
// - ソース側を選択
// - 関連を選択すると関連の選択が解除され、ソース側の図要素が選択されます
// - ターゲット側を選択
// - 関連を選択すると関連の選択が解除され、ターゲット側の図要素が選択されます
var JDialog = Java.type('javax.swing.JDialog')
var JRadioButton = Java.type('javax.swing.JRadioButton')
var JCheckBox = Java.type('javax.swing.JCheckBox')
var JPanel = Java.type('javax.swing.JPanel')
var BorderLayout = Java.type('java.awt.BorderLayout')
var ButtonGroup = Java.type('javax.swing.ButtonGroup')
var IEntitySelectionListener = Java.type('com.change_vision.jude.api.inf.view.IEntitySelectionListener')
var WindowListener = Java.type('java.awt.event.WindowListener')
var ILinkPresentation = Java.type('com.change_vision.jude.api.inf.presentation.ILinkPresentation')
var viewManager = astah.getViewManager()
var astahFrame = viewManager.getMainFrame()
var frame = new JDialog(astahFrame, "関連図要素の選択補助")
frame.setAlwaysOnTop(true)
var isPanCheck = new JCheckBox("選択対象をダイアグラムエディタの中心に表示する", true)
var nonRadio = new JRadioButton("選択しても何もしない", true)
var sourceEndRradio = new JRadioButton("ソース側を選択", false)
var targetEndRradio = new JRadioButton("ターゲット側を選択", false)
var group = new ButtonGroup();
group.add(nonRadio)
group.add(sourceEndRradio)
group.add(targetEndRradio)
var radioPanel = new JPanel()
radioPanel.add(nonRadio)
radioPanel.add(sourceEndRradio)
radioPanel.add(targetEndRradio)
var contentPane = frame.getContentPane()
contentPane.add(isPanCheck, BorderLayout.NORTH)
contentPane.add(radioPanel, BorderLayout.SOUTH)
frame.pack()
frame.setLocationRelativeTo(astahFrame);
frame.setVisible(true)
var diagramViewManager = viewManager.getDiagramViewManager()
var listener = createAdjustSelectionListener(diagramViewManager)
diagramViewManager.addEntitySelectionListener(listener)
var windowListener = new WindowListener() {
windowOpened : function(e) {},
windowClosing : function(e) {
diagramViewManager.removeEntitySelectionListener(listener)
},
windowOpened : function(e) {},
windowClosed : function(e) {},
windowIconified : function(e) {},
windowDeiconified : function(e) {},
windowActivated : function(e) {},
windowDeactivated : function(e) {}
}
frame.addWindowListener(windowListener)
function getLinkPresentations(presentations) {
var targets = []
presentations.forEach(
function (selectedP) {
if (selectedP instanceof ILinkPresentation) {
targets.push(selectedP)
}
}
)
return targets
}
function getNewSelectTargets(linkPs, isSourceEnds) {
var targets = []
linkPs.forEach(
function (linkP) {
if (isSourceEnds) {
targets.push(linkP.getSourceEnd())
} else {
targets.push(linkP.getTargetEnd())
}
}
)
return targets
}
var canChange = true
function createAdjustSelectionListener(diagramViewManager) {
return new IEntitySelectionListener() {
entitySelectionChanged : function(e) {
try {
if (!canChange) {
return
}
canChange = false
if(nonRadio.isSelected()) {
canChange = true
return
}
var selectedPs = Java.from(diagramViewManager.getSelectedPresentations())
var selectedLinkPs = getLinkPresentations(selectedPs)
print("選択された関連の数:" + selectedLinkPs.length)
var selectTargets = getNewSelectTargets(selectedLinkPs, sourceEndRradio.isSelected())
diagramViewManager.select(selectTargets)
if (isPanCheck.isSelected() && selectTargets.length >= 1) {
diagramViewManager.showInDiagramEditor(selectTargets[0])
}
canChange = true
} catch (e) {
print(e)
}
}
}
}
var infNamespace = 'com.change_vision.jude.api.inf'
var ISequenceDiagram = Java.type(infNamespace + '.model.ISequenceDiagram');
var Key = Java.type(infNamespace + '.presentation.PresentationPropertyConstants.Key');
var INodePresentation = Java.type(infNamespace + '.presentation.INodePresentation');
// ------------------------------------------------------
// Please set the new color as you like.
var COLOR = "#BBCCFF";
// ------------------------------------------------------
run();
function run() {
var currentSequenceDiagram = getCurrentSequenceDiagram();
if (currentSequenceDiagram == null) {
print("error : Please open the sequence diagram.");
return;
}
var presentations = getPresentations(currentSequenceDiagram);
var chengeColorPresentations = getExecutionSpecificationPresentations(presentations);
setColor(chengeColorPresentations, COLOR);
}
function getCurrentSequenceDiagram() {
try{
var viewManager = astah.getViewManager();
var diagramViewManager = viewManager.getDiagramViewManager();
var currentDiagram = diagramViewManager.getCurrentDiagram();
if(currentDiagram instanceof ISequenceDiagram) {
return currentDiagram;
}
return null;
} catch(e) {
return null;
}
}
function getPresentations(currentDiagram) {
try {
return currentDiagram.getPresentations();
} catch (e) {
return new IPresentation[0];
}
}
function getExecutionSpecificationPresentations(presentations) {
var executionSpecificationPresentations = [];
for (var i in presentations) {
var presentation = presentations[i];
if (presentation == null || !(presentation instanceof INodePresentation)) {
continue;
}
var model = presentation.getModel();
if (model != null) {
continue;
}
var parentPresentation = presentation.getParent();
if (parentPresentation == null) {
continue;
}
executionSpecificationPresentations.push(presentation);
}
return executionSpecificationPresentations;
}
function setColor(presentations, color) {
try {
astah.getTransactionManager().beginTransaction();
for(var i in presentations) {
var presentation = presentations[i];
presentation.setProperty(Key.FILL_COLOR, color);
}
astah.getTransactionManager().endTransaction();
print("info: Changed the color of " + presentations.length + " elements.");
} catch (e) {
astah.getTransactionManager().abortTransaction();
print("error : Could not change element color.");
print(e);
}
}
// 図要素作成直後にその図要素の色を上書きするリスナを登録します
// astah*の起動後に1回だけ実行してください
//////////////////////////////////////
// 塗り替えたい色
var COLOR = "#BBCCFF";
//////////////////////////////////////
var infNamespace = 'com.change_vision.jude.api.inf'
var IPresentation = Java.type(infNamespace + '.presentation.IPresentation');
var Key = Java.type(infNamespace + '.presentation.PresentationPropertyConstants.Key');
var ProjectEventListener = Java.type(infNamespace + '.project.ProjectEventListener');
var ProjectEditUnit = Java.type(infNamespace + '.project.ProjectEditUnit');
var TransactionManager = Java.type(infNamespace + '.editor.TransactionManager');
var listener = new ProjectEventListener() {
projectChanged : function(e) {
var projectEditUnits = e.getProjectEditUnit();
for(var i in projectEditUnits) {
var projectEditUnit = projectEditUnits[i];
if(projectEditUnit.getOperation() != ProjectEditUnit.ADD) {
continue;
}
var entity = projectEditUnit.getEntity();
if(entity instanceof IPresentation) {
setColor(entity, COLOR);
}
}
},
projectClosed : function(e) {
},
projectOpened : function(e) {
}
}
astah.addProjectEventListener(listener);
function setColor(presentation, color) {
try {
TransactionManager.beginTransaction();
presentation.setProperty(Key.FILL_COLOR, color);
TransactionManager.endTransaction();
print("info: " + presentation.getLabel() + "の色を上書きしました。");
} catch (e) {
TransactionManager.abortTransaction();
}
}
var VISIBILITY = "public"
//var VISIBILITY = "protected"
//var VISIBILITY = "package"
//var VISIBILITY = "private"
getSelectedElements().forEach(
function (element) {
try {
astah.getTransactionManager().beginTransaction()
element.setVisibility(VISIBILITY)
astah.getTransactionManager().endTransaction()
} catch (e) {
print("error : ")
print(e);
astah.getTransactionManager().abortTransaction()
return
}
if (element.isPrivateVisibility()) {
print("info : " + element.getName() + " is private.")
}
if (element.isPublicVisibility()) {
print("info : " + element.getName() + " is public.")
}
if (element.isProtectedVisibility()) {
print("info : " + element.getName() + " is protected.")
}
if (element.isPackageVisibility()) {
print("info : " + element.getName() + " is package.")
}
}
)
function getSelectedElements() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedElements()
return Java.from(selectedPresentations)
}
// Changes the visibility of attributes of the selected class.
// Select a class and execute.
// After execution, focus on the diagram editor and the appearance will be updated.
///////////////////////////////////////////////////////////////////
// * Please comment out leaving only one line. *
var VISIBILITY = "public"
//var VISIBILITY = "protected"
//var VISIBILITY = "package"
//var VISIBILITY = "private"
///////////////////////////////////////////////////////////////////
var IClass = Java.type('com.change_vision.jude.api.inf.model.IClass');
getSelectedElements().forEach(
function (element) {
if (element == null || !(element instanceof IClass)) {
return
}
Java.from(element.getAttributes()).forEach(
function (attribute) {
if (attribute.getAssociation() != null) {
return
}
setVisibility(attribute, VISIBILITY)
print("info : " + element.getName() + "::" + attribute.getName() + " is " + getVisibilityString(attribute))
}
)
}
)
function setVisibility(element, visibility) {
try {
astah.getTransactionManager().beginTransaction()
element.setVisibility(visibility)
astah.getTransactionManager().endTransaction()
} catch (e) {
print("error : ")
print(e);
astah.getTransactionManager().abortTransaction()
return
}
}
function getVisibilityString(element) {
if (element.isPrivateVisibility()) {
return "private"
}
if (element.isPublicVisibility()) {
return "public"
}
if (element.isProtectedVisibility()) {
return "protected"
}
if (element.isPackageVisibility()) {
return "package"
}
return ""
}
function getSelectedElements() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedElements()
return Java.from(selectedPresentations)
}
var Point2D = Java.type("java.awt.geom.Point2D.Double");
var transactionManager = astah.getTransactionManager();
var viewManager = astah.getViewManager().getDiagramViewManager();
var currentDiagram = viewManager.getCurrentDiagram();
var editor = astah.getDiagramEditorFactory().getActivityDiagramEditor();
editor.setDiagram(currentDiagram);
var actionPresentation = null;
try{
transactionManager.beginTransaction();
actionPresentation = editor.createAction("action", new Point2D(100, 200));
var actionModel = actionPresentation.getModel();
actionModel.addStereotype("aaa");
transactionManager.endTransaction();
} catch(e) {
transactionManager.abortTransaction();
print(e);
}
var CREATE_TOPIC_NUM = 1000
var maindmapEditor = astah.getDiagramEditorFactory().getMindmapEditor()
var topics = []
try {
astah.getTransactionManager().beginTransaction()
topics.push(maindmapEditor.createMindmapDiagram(astah.getProject(),
"rootTopic").getRoot())
for (var i = 0; i < CREATE_TOPIC_NUM; i++) {
var topic = topics[Math.round(Math.random() * (topics.length -
1))]
topics.push(maindmapEditor.createTopic(topic, "topic" + i))
}
astah.getTransactionManager().endTransaction()
} catch (e) {
print("error : ")
print(e);
astah.getTransactionManager().abortTransaction()
}
// Please execute after creating the project.
// Note: Not handling exceptions.
var de = astah.getDiagramEditorFactory().getSequenceDiagramEditor();
astah.getTransactionManager().beginTransaction();
var diagram = de.createSequenceDiagram(astah.getProject(), "SequenceDiagram");
var lifelineA = de.createLifeline("aaa", 10.0);
var lifelineB = de.createLifeline("bbb", 210.0);
de.createMessage("message", lifelineA, lifelineB, 100.0);
var asynchronousMessage = de.createMessage("message", lifelineA, lifelineB, 200.0);
asynchronousMessage.getModel().setAsynchronous(true);
astah.getTransactionManager().endTransaction();
astah.getViewManager().getDiagramViewManager().open(diagram)
function deleteElements(elements) {
var transactionManager = astah.getTransactionManager()
var basicModelEditor =
astah.getModelEditorFactory().getBasicModelEditor()
try {
transactionManager.beginTransaction()
for each(var element in elements) {
var id = element.getId()
basicModelEditor.delete(element)
print("deleted " + id)
}
transactionManager.endTransaction()
} catch (e) {
transactionManager.abortTransaction()
throw e
}
}
// Delete Entry and Exit in the selected state on the diagram
run()
//////////////////////////////////
function run() {
var selectedElements = getSelectedElements()
if (selectedElements.length == 0) {
print("Please select state on the diagram.")
return
}
var selectedElement = selectedElements[0]
deleteEntry(selectedElement)
deleteExit(selectedElement)
}
function deleteEntry(state) {
if (state.getEntry().length == 0) {
print("state already has no entry.")
return
}
var transactionManager = astah.getTransactionManager()
try {
transactionManager.beginTransaction()
state.setEntry(null)
transactionManager.endTransaction()
print("Deleted entry.")
} catch (e) {
transactionManager.abortTransaction()
throw e
}
}
function deleteExit(state) {
if (state.getExit().length == 0) {
print("state already has no exit.")
return
}
var transactionManager = astah.getTransactionManager()
try {
transactionManager.beginTransaction()
state.setExit(null)
transactionManager.endTransaction()
print("Deleted exit.")
} catch (e) {
transactionManager.abortTransaction()
throw e
}
}
function getSelectedElements() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedElements()
return Java.from(selectedPresentations)
}
// Delete Event and Action in the selected transition on the diagram
run()
//////////////////////////////////
function run() {
var selectedElements = getSelectedElements()
if (selectedElements.length == 0) {
print("Please select transition on the diagram.")
return
}
var selectedElement = selectedElements[0]
deleteEvent(selectedElement)
deleteAction(selectedElement)
}
function deleteAction(transition) {
if (transition.getAction().length == 0) {
print("transition already has no Action.")
return
}
var transactionManager = astah.getTransactionManager()
try {
transactionManager.beginTransaction()
transition.setAction(null)
transactionManager.endTransaction()
print("Deleted entry.")
} catch (e) {
transactionManager.abortTransaction()
throw e
}
}
function deleteEvent(transition) {
if (transition.getEvent().length == 0) {
print("transition already has no Event.")
return
}
var transactionManager = astah.getTransactionManager()
try {
transactionManager.beginTransaction()
transition.setEvent(null)
transactionManager.endTransaction()
print("Deleted Event.")
} catch (e) {
transactionManager.abortTransaction()
throw e
}
}
function getSelectedElements() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedElements()
return Java.from(selectedPresentations)
}
function getAllPresentations() {
var diagrams = astah.findElements(IDiagram.class);
var presentations = [];
for each(var diagram in diagrams) {
for each(var presentation in diagram.getPresentations()) {
presentations.push(presentation);
}
}
return presentations;
}
// var modelIds = [
// "8ivk-a4e74596d338a9bd52d99695befee8f6",
// "8p0a-a4e74596d338a9bd52d99695befee8f6"
// ]
function getElements(modelIds) {
var ModelFinder = Java.type('com.change_vision.jude.api.inf.project.ModelFinder');
var idFinder = new ModelFinder() {
isTarget: function(namedElement) {
return modelIds.indexOf(namedElement.getId()) != -1
}
}
return astah.findElements(idFinder)
}
function getPrimaryKey(erEntity, logicalName) {
var primaryKey = null
Java.from(erEntity.getPrimaryKeys()).forEach(
function (pk) {
if (pk.getLogicalName().equals(logicalName)) {
primaryKey = pk
return
}
}
)
return primaryKey
}
var diagramViewManager = astah.getViewManager().getDiagramViewManager();
var selectedPresentation = diagramViewManager.getSelectedPresentations()[0];
var model = selectedPresentation.getModel();
var presentation = model.getPresentations()[0];
print(selectedPresentation == presentation);
var infNamespace = 'com.change_vision.jude.api.inf'
var IMessage = Java.type(infNamespace + '.model.IMessage')
var Key = Java.type(infNamespace + '.presentation.PresentationPropertyConstants.Key');
var TransactionManager = astah.getTransactionManager()
moveMessageLabelToLowerRight()
function moveMessageLabelToLowerRight() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedPresentations()
Java.from(selectedPresentations).forEach(function(selectedPresentation) {
var model = selectedPresentation.getModel();
if (model instanceof IMessage) {
try {
TransactionManager.beginTransaction();
var newX = Number(selectedPresentation.getProperty(Key.NAME_X)) + 100
selectedPresentation.setProperty(Key.NAME_X, newX)
var newY = Number(selectedPresentation.getProperty(Key.NAME_Y)) + 100
selectedPresentation.setProperty(Key.NAME_Y, newY);
TransactionManager.endTransaction();
} catch(e) {
TransactionManager.abortTransaction()
print("ERROR : " + selectedPresentation.getLabel() + " - " + e.getMessage())
}
}
});
}
function printCurrentDiagramTaggedValueInfo(viewManager) {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var currentDiagram = diagramViewManager.getCurrentDiagram()
printTaggedValueInfo(currentDiagram)
}
getSelectedPresentations().forEach(
function (presentation) {
var depth = presentation.getDepth()
var infoString = depth + ":" + presentation.getLabel()
print(infoString)
}
)
function getSelectedPresentations() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedPresentations()
return Java.from(selectedPresentations)
}
var IEREntity = Java.type('com.change_vision.jude.api.inf.model.IEREntity');
var IERRelationship = Java.type('com.change_vision.jude.api.inf.model.IERRelationship');
var entities = astah.findElements(IEREntity.class);
for(var i in entities) {
var entity = entities[i];
print('ENTITY: ' + entity.getName());
print(' comment = ' + entity.getDefinition());
var primaryKeys = entity.getPrimaryKeys();
if (primaryKeys.length > 0) {
for(var j in primaryKeys) {
var attribute = primaryKeys[j];
print(' Primary[' + j + ']: LogicalName = ' + attribute.getLogicalName()
+ ', PhysicalName = ' + attribute.getPhysicalName());
var relation = attribute.getReferencedRelationship();
if (relation != null) {
print(' Relationship: ' + relation.getName());
}
var pk = attribute.getReferencedPrimaryKey();
if (pk != null) {
print(' PK: LogicalName = ' + pk.getLogicalName());
}
var fks = attribute.getReferencedForeignKeys();
for(var p in fks) {
var f = fks[p];
print(' FK[' + p + ']: LogicalName = ' + f.getLogicalName());
}
}
}
var nonPrimaryKeys = entity.getNonPrimaryKeys();
if (nonPrimaryKeys.length > 0) {
for(var k in nonPrimaryKeys) {
var attribute = nonPrimaryKeys[k];
print(' NonPrimary[' + k + ']: LogicalName = ' + attribute.getLogicalName()
+ ', PhysicalName = ' + attribute.getPhysicalName());
var relation = attribute.getReferencedRelationship();
if (relation != null) {
print(' Relationship: ' + relation.getName());
}
var pk = attribute.getReferencedPrimaryKey();
if (pk != null) {
print(' PK: LogicalName = ' + pk.getLogicalName());
}
var fks = attribute.getReferencedForeignKeys();
for(var p in fks) {
var f = fks[p];
print(' FK[' + p + ']: LogicalName = ' + f.getLogicalName());
}
}
}
print('--------');
}
var relations = astah.findElements(IERRelationship.class);
for(var m in relations) {
var relation = relations[m];
print('Relationship: ' + relation.getName());
var fks = relation.getForeignKeys();
for(var n in fks) {
var attribute = fks[n];
print(' FK[' + n + ']: LogicalName = ' + attribute.getLogicalName());
}
print('--------');
}
var IHyperlinkOwner = Java.type('com.change_vision.jude.api.inf.model.IHyperlinkOwner')
var INamedElement = Java.type('com.change_vision.jude.api.inf.model.INamedElement')
var IPresentation = Java.type('com.change_vision.jude.api.inf.presentation.IPresentation')
var hyperlinkOwners = astah.findElements(IHyperlinkOwner.class)
for(var i in hyperlinkOwners) {
var hyperlinkOwner = hyperlinkOwners[i]
var hyperlinks = hyperlinkOwner.getHyperlinks()
if(hyperlinks.length == 0) {
continue
}
print(getClassSimpleName(hyperlinkOwner) + " : " + hyperlinkOwner.getFullName("::"))
for(var j in hyperlinks) {
var hyperlink = hyperlinks[j]
printInfo(hyperlink)
}
}
function printInfo(hyperlink) {
var name = hyperlink.getName()
var type = ""
if(hyperlink.isModel()) {
type = "Model"
var linkModel = astah.getEntity(name)
if(linkModel != null) {
type += " (" + getClassSimpleName(linkModel) + ")"
if(linkModel instanceof INamedElement) {
name = linkModel.getFullName("::")
}
if(linkModel instanceof IPresentation) {
name = linkModel.getLabel()
}
}
} else if(hyperlink.isFile()) {
type = "File"
} else if(hyperlink.isURL()) {
type = "URL"
}
print(" " + type)
print(" [Name] " + name)
print(" [Path] " + hyperlink.getPath())
print(" [Comment] " + hyperlink.getComment())
}
function getClassSimpleName(object) {
var clazz = object.getClass()
var interfaces = clazz.getInterfaces()
if (interfaces.length > 0) {
return interfaces[0].getSimpleName()
}
return clazz.getSimpleName()
}
// 図上で選択した要素のモデルの情報を表示するスクリプト
getSelectedElements().forEach(
function (element) {
var infoString = ""
var stereotypes = Java.from(element.getStereotypes())
if (stereotypes.length > 0) {
infoString += "<<" + stereotypes.join(">><<") + ">> "
}
infoString += element.getName() + " - " + getClassName(element)
print(infoString)
}
)
/** 図上で選択した要素のモデルのJavaScript配列を取得する。 */
function getSelectedElements() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedElements()
return Java.from(selectedPresentations)
}
/** オブジェクトのインタフェースの名前を取得する。 */
function getClassName(object) {
var clazz = object.getClass()
var interfaces = clazz.getInterfaces()
if (interfaces.length > 0) {
return interfaces[0].getName()
}
return clazz.getName()
}
// 図上で選択したプレゼンテーションの情報を表示するスクリプト
getSelectedPresentations().forEach(
function (presentation) {
var infoString = presentation.getLabel() + " - " + getClassSimpleName(presentation)
var model = presentation.getModel()
if (model != null) {
infoString += " - " + getClassSimpleName(model)
}
print(infoString)
}
)
/** 図上で選択したプレゼンテーションのJavaScript配列を取得する。 */
function getSelectedPresentations() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedPresentations()
return Java.from(selectedPresentations)
}
/** オブジェクトのインタフェースのシンプルな名前を取得する。 */
function getClassSimpleName(object) {
var clazz = object.getClass()
var interfaces = clazz.getInterfaces()
if (interfaces.length > 0) {
return interfaces[0].getSimpleName()
}
return clazz.getSimpleName()
}
var ICombinedFragment = Java.type('com.change_vision.jude.api.inf.model.ICombinedFragment');
var IMessage = Java.type('com.change_vision.jude.api.inf.model.IMessage');
run();
function contains(combinedFragmentPresentation, messagePresentation) {
for each(var point in messagePresentation.getPoints()) {
if(!combinedFragmentPresentation.getRectangle().contains(point)){
return false;
}
}
return true;
}
function getSelectedMessagePresentation() {
var viewManager = astah.getViewManager();
var diagramViewManager = viewManager.getDiagramViewManager();
var selectedPresentations = diagramViewManager.getSelectedPresentations();
if(selectedPresentations.length > 0
&& selectedPresentations[0].getModel() instanceof IMessage){
return selectedPresentations[0];
}
return null;
}
function getLoopCount(messagePresentation) {
var count = 0;
for each(var presentation in messagePresentation.getDiagram().getPresentations()) {
var model = presentation.getModel();
if(model == null || !(model instanceof ICombinedFragment)) {
continue;
}
if(!model.isLoop()) {
continue;
}
if(!contains(presentation, messagePresentation)){
continue;
}
if(count == 0) {
count = 1;
}
count *= Number(model.getName().substring(1 , model.getName().length - 1));
}
return count;
}
function run() {
var messagePresentation = getSelectedMessagePresentation();
if(messagePresentation == null){
print("ERROR : Please select a message presentation.");
return;
}
print("\"" + messagePresentation.getLabel() + "\" loops " + getLoopCount(messagePresentation) + " times.");
}
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)
}
// Use ModelFinder
var ModelFinder = Java.type('com.change_vision.jude.api.inf.project.ModelFinder');
var Arrays = Java.type('java.util.Arrays');
var stereotypeFinder = new ModelFinder() {
isTarget: function(namedElement) {
var stereotype = "stereotype"
return containsStereotype(namedElement, stereotype)
}
}
for each(var element in astah.findElements(stereotypeFinder)) {
print(element.getName())
}
function containsStereotype(element, stereotype) {
var stereotypes = Arrays.asList(element.getStereotypes())
return stereotypes.contains(stereotype)
}
print(getAstahExePath() + " " + getProjectPath() + " -show " + getCurrentDiagram().getId());
function getAstahExePath() {
return astah.getAstahInstallPath().slice(1) + "astah-pro.exe";
}
function getProjectPath() {
var projectPath = astah.getProjectPath();
return projectPath.replace( /\\/g , "/" ) ;
}
function getCurrentDiagram() {
try{
var viewManager = astah.getViewManager();
var diagramViewManager = viewManager.getDiagramViewManager();
return diagramViewManager.getCurrentDiagram();
} catch(e) {
return null;
}
}
/** 親の情報を標準出力に表示する。 */
function printParentInfo(presentations) {
presentations.forEach(
function (presentation) {
var parent = presentation.getParent()
if(parent == null) {
print(presentation.getLabel() + "の親はありません。")
return
}
print(presentation.getLabel() + "の親は" + parent.getLabel() + "です。")
}
)
}
// Print the tagged values of the model that was selected on 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)
}
}
// Print the tagged values of the model selected in the diagram.
function printSelectedPresentationsTaggedValueInfo() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedPresentations()
for each(var selectedPresentation in selectedPresentations) {
printTaggedValueInfo(selectedPresentation.getModel())
}
}
function printTaggedValueInfo(model) {
if(model == null) {
return
}
var taggedValues = model.getTaggedValues()
for each(var taggedValue in taggedValues) {
print(taggedValue.getKey() + ":" + taggedValue.getValue())
}
}
// var command = <String of execution result of printOpenDiagramCommand.js>;
Java.type("java.lang.Runtime").getRuntime().exec(command);
//Rewrite selected presentation label
var newLabel = "aaa"
//////////////////////////////////
var selectedPresentations = getSelectedPresentations()
if (selectedPresentations.length == 0) {
print("Please select one diagram element.")
}
setLabel(selectedPresentations[0], newLabel)
//////////////////////////////////
function setLabel(presentation, labelString) {
var transactionManager = astah.getTransactionManager()
try {
transactionManager.beginTransaction()
presentation.setLabel(labelString)
transactionManager.endTransaction()
} catch (e) {
transactionManager.abortTransaction()
throw e
}
}
function getSelectedPresentations() {
var viewManager = astah.getViewManager()
var diagramViewManager = viewManager.getDiagramViewManager()
var selectedPresentations = diagramViewManager.getSelectedPresentations()
return Java.from(selectedPresentations)
}
function setMessageName(messageP, newName) {
var message = messageP.getModel();
var operation = message.getOperation();
var model = (operation != null) ? operation : message;
model.setName(newName);
}
// モデル名と別名1を入れ替えるサンプルスクリプト
// 例) クラス"apple"の別名1が"リンゴ"なら、クラスの名前を"リンゴ"、別名1を"apple"に入れ替えます
// 使用方法
// 1. プロジェクトファイルのバックアップを取る(*.astaファイルを複製)
// 2. astah*でプロジェクトファイルを開く
// 3. スクリプトエディタで本スクリプトを実行する
// - コンソールに"!!!error!!!"がある場合は保存せずにプロジェクトを開きなおし、原因を取り除いて再実行してください
var INamedElement = Java.type('com.change_vision.jude.api.inf.model.INamedElement');
var InvalidEditingException = Java.type('com.change_vision.jude.api.inf.exception.InvalidEditingException');
run();
function run() {
var namedElements =astah.findElements(INamedElement.class);
Java.from(namedElements).forEach(function(element) {
var name = element.getName();
var alias1 = element.getAlias1();
if (alias1 == null || alias1.isEmpty()) {
// print(name + " は別名1を持たないため、名前の入れ替えをスキップします");
return;
}
try {
astah.getTransactionManager().beginTransaction();
// print(name + " と " + alias1 + " を入れ替えます。");
element.setAlias1(name);
element.setName(alias1);
astah.getTransactionManager().endTransaction();
} catch (e) {
astah.getTransactionManager().abortTransaction();
var fullName = element.getFullName("::");
if(fullName.isEmpty()) {
var owner = element.getOwner();
fullName = owner.getFullName("::") + " - " + name;
}
if(InvalidEditingException.NAME_DOUBLE_ERROR_KEY.equals(e.getKey())) {
print("!!!error!!! " + alias1 + "がすでにあるため " + fullName + "を上書きすることができません");
return;
}
print("!!!error!!! " + fullName +"の名前入れ替えはスキップされました。詳細 : "+ e.getMessage());
}
});
}
// Please execute it after opening the project.
var infNamespace = 'com.change_vision.jude.api.inf'
var IDiagram = Java.type(infNamespace + '.model.IDiagram');
var INodePresentation = Java.type(infNamespace + '.presentation.INodePresentation');
var Key = Java.type(infNamespace + '.presentation.PresentationPropertyConstants.Key');
var diagramViewManager = astah.getViewManager().getDiagramViewManager()
var currentDiagram = diagramViewManager.getCurrentDiagram()
var openDiagrams = diagramViewManager.getOpenDiagrams()
diagramViewManager.closeAll()
updateDiagrams()
open(openDiagrams, currentDiagram)
print("finish.")
function updateDiagrams() {
Java.from(astah.findElements(IDiagram.class)).forEach(
function (diagram) {
diagramViewManager.open(diagram)
try {
astah.getTransactionManager().beginTransaction()
if (update(diagram) == 0) {
astah.getTransactionManager().abortTransaction()
diagramViewManager.closeAll()
return
}
print("updated :" + diagram.getName())
astah.getTransactionManager().endTransaction()
} catch (e) {
print("error : " + diagram.getName())
print(e);
astah.getTransactionManager().abortTransaction()
}
diagramViewManager.closeAll()
}
)
}
function update(diagram) {
var updateCount = 0
Java.from(diagram.getPresentations()).forEach(
function (presentation) {
if (presentation == null || !(presentation instanceof INodePresentation)) {
return
}
var isAutoResize = presentation.getProperty(Key.AUTO_RESIZE)
if (isAutoResize) {
presentation.setProperty(Key.AUTO_RESIZE, !isAutoResize)
presentation.setProperty(Key.AUTO_RESIZE, isAutoResize)
updateCount++
}
}
)
return updateCount
}
function open(diagrams, currentDiagram) {
Java.from(diagrams).forEach(
function (diagram) {
diagramViewManager.open(diagram)
}
)
if (currentDiagram != null) {
diagramViewManager.open(currentDiagram)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment