blob: 2b1dcc882bc22f48364a3354227f7771cdaae2a3 [file] [log] [blame]
/*****************************************************************************
* Copyright (c) 2020 CEA LIST
*
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* ansgar.radermacher@cea.fr - Initial API and implementation
*
*****************************************************************************/
package org.eclipse.papyrus.robotics.core.utils;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.NamedElement;
/**
* Simple mechanism to provide a unique named (within the owning namespace) based on a prefix
* and a 4 digit number
*/
public class NamingUtil {
// max. number of distinguishable names
final public static int MAX_COUNT = 1000;
/**
* Return a unique name for a named element
*
* @param ne
* a named element
* @param prefix
* the name prefix to use
* @param format
* the number format to use, e.g. "%04d"
*/
public static String getName(NamedElement ne, String prefix, String format) {
List<String> existingNames = new ArrayList<String>();
for (NamedElement existingNE : ne.getNamespace().getMembers()) {
existingNames.add(existingNE.getName());
}
for (int index = 1; index < MAX_COUNT; index++) {
String name = calcName(prefix, format, index);
if (!existingNames.contains(name)) {
return name;
}
}
return null;
}
/**
* Return a unique name for a comment (largely duplicated code with setName for a named element),
*
* @param comment
* a comment
* @param prefix
* the name prefix to use
* @param format
* the number format to use, e.g. "%04d"
*/
public static String getName(Comment comment, String prefix, String format) {
List<String> existingNames = new ArrayList<String>();
for (Comment existingComment : comment.getOwner().getOwnedComments()) {
existingNames.add(existingComment.getBody());
}
for (int index = 1; index < MAX_COUNT; index++) {
String name = calcName(prefix, format, index);
if (!existingNames.contains(name)) {
return name;
}
}
return null;
}
/**
* Calculate the resulting name
*
* @param prefix
* the name prefix to use
* @param format
* a number format string
* @param index
* the index number
* @return
*/
protected static String calcName(String prefix, String format, int index) {
return String.format("%s" + format, prefix, index); //$NON-NLS-1$
}
}