// SPDX-FileCopyrightText: 2020 Roberto Posenato // // SPDX-License-Identifier: LGPL-3.0-or-later package it.univr.di.cstnu.graph; import javax.annotation.Nonnull; import java.io.Serial; /** * Base class for implementing Node. * * @author posenato * @version $Rev$ */ @SuppressWarnings("AbstractClassWithOnlyOneDirectInheritor") public abstract class AbstractNode extends AbstractComponent implements Node { /** * */ @Serial private static final long serialVersionUID = 2L; /** * To provide a unique ID for the default creation of the component. */ static private int idSeq; /** * @return next id */ static private int nextId() { return idSeq++; } /** * Minimal constructor. * * @see #AbstractNode(String) */ public AbstractNode() { this((String) null); } /** * Simplified constructor * * @param n name of node */ AbstractNode(String n) { super(n); this.setName(((n == null) || (n.isEmpty())) ? "n%d".formatted(AbstractNode.nextId()) : n); } /** * Constructor to clone the component. * * @param node the component to clone. */ AbstractNode(Node node) { this((node != null) ? node.getName() : null); } /** * Sets the name of the node. *

* Once this node has been added to a graph, its name is managed by that graph: use {@code * TemporalConstraintGraph.renameNode(this, newName)} instead of calling this method directly. * * @param newName cannot empty. If empty, it does nothing. * * @return the old name. * * @throws IllegalStateException if this node's name is already managed by a graph. */ @Override @Nonnull public String setName(@Nonnull String newName) { final String old = this.getName(); if (newName.equals(old)) { // Not an actual rename: always allowed, even once graph-managed (e.g., Component#takeIn(Component) // copying a same-named clone's other attributes onto an already-inserted node). return old; } if (isNameManagedByGraph()) { throw new IllegalStateException("The name of node '%s' is managed by a graph; use TemporalConstraintGraph.renameNode(...) instead of setName(...).".formatted(getName())); } if (!newName.isEmpty()) { name = newName; } return old; } /** * */ @Override public void takeIn(Node n) { super.takeIn(n); } }