Project

General

Profile

Download (27.9 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * European Distributed Institute of Taxonomy
3
 * http://www.e-taxonomy.eu
4
 *
5
 * The contents of this file are subject to the Mozilla Public License Version 1.1
6
 * See LICENSE.TXT at the top of this package for the full license terms.
7
 */
8

    
9
package eu.etaxonomy.cdm.model.description;
10

    
11
import java.util.ArrayList;
12
import java.util.HashMap;
13
import java.util.List;
14
import java.util.Map;
15
import java.util.Map.Entry;
16

    
17
import javax.persistence.Entity;
18
import javax.persistence.FetchType;
19
import javax.persistence.JoinColumn;
20
import javax.persistence.ManyToOne;
21
import javax.persistence.MapKeyJoinColumn;
22
import javax.persistence.OneToMany;
23
import javax.persistence.OrderColumn;
24
import javax.persistence.Transient;
25
import javax.xml.bind.annotation.XmlAccessType;
26
import javax.xml.bind.annotation.XmlAccessorType;
27
import javax.xml.bind.annotation.XmlElement;
28
import javax.xml.bind.annotation.XmlElementWrapper;
29
import javax.xml.bind.annotation.XmlIDREF;
30
import javax.xml.bind.annotation.XmlRootElement;
31
import javax.xml.bind.annotation.XmlSchemaType;
32
import javax.xml.bind.annotation.XmlType;
33
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
34

    
35
import org.apache.logging.log4j.LogManager;
36
import org.apache.logging.log4j.Logger;
37
import org.hibernate.annotations.Cascade;
38
import org.hibernate.annotations.CascadeType;
39
import org.hibernate.envers.Audited;
40

    
41
import eu.etaxonomy.cdm.jaxb.MultilanguageTextAdapter;
42
import eu.etaxonomy.cdm.model.common.IMultiLanguageTextHolder;
43
import eu.etaxonomy.cdm.model.common.Language;
44
import eu.etaxonomy.cdm.model.common.LanguageString;
45
import eu.etaxonomy.cdm.model.common.MultilanguageText;
46
import eu.etaxonomy.cdm.model.common.VersionableEntity;
47
import eu.etaxonomy.cdm.model.taxon.Taxon;
48

    
49
/**
50
 * This class represents a node within a {@link PolytomousKey polytomous key}
51
 * structure. The structure of such a key is a directed tree like acyclic graph
52
 * of <code>PolytomousKeyNode</code>s.
53
 * A <code>PolytomousKeyNode</code> represents both the node and the edges that lead
54
 * to <code>this</code> node, therefore an extra class representing the edges
55
 * does not exist.
56
 * <BR>
57
 * The attribute representing the edge leading from its parent node to <code>this</code>
58
 * node is the {@link #getStatement() statement}, attributes leading to the child nodes
59
 * are either the {@link #getQuestion() question} or the {@link #getFeature() feature}.
60
 * While {@link #getStatement() statements} are required, {@link #getQuestion() questions} and
61
 * {@link #getFeature() features} are optional and do typically not exist in classical keys.
62
 * Both, {@link #getQuestion() questions} and {@link #getFeature() features}, will be "answered" by the
63
 * {@link #getStatement() statements} of the child nodes, where {@link #getQuestion() questions}
64
 * are usually free text used in manually created keys while {@link #getFeature() features} are
65
 * typically used in automatically created keys based on structured descriptive data.
66
 * Only one of them should be defined in a node. However, if both exist the {@link #getQuestion() question}
67
 * should always be given <b>priority</b> over the {@link #getFeature() feature}.<br>
68
 *
69
 * Typically a node either links to its child nodes (subnodes) or represents a link
70
 * to a {@link Taxon taxon}. The later, if taken as part of the tree,  are usually
71
 * the leaves of the represented tree like structure (taxonomically they are the
72
 * end point of the decision process).<br>
73
 *
74
 * However, there are exceptions to this simple structure:
75
 *
76
 * <li>Subnodes and taxon link<br>
77
 *
78
 * In rare cases a node can have both, subnodes and a {@link #getTaxon() link to a taxon}.
79
 * In this case the taxonomic determination process may be either terminated
80
 * at the given {@link Taxon taxon} or can proceed with the children if a more accurate
81
 * determination is wanted. This may be the case e.g. in a key that generally
82
 * covers all taxa of rank species and at the same time allows identification of
83
 * subspecies or varieties of these taxa.</li>
84
 *
85
 * <li>{@link #getOtherNode() Other nodes}: <br>
86
 *
87
 * A node may not only link to its subnodes or to a taxon but it may
88
 * also link to {@link #getOtherNode() another node} (with a different parent) of either the same key
89
 * or another key.
90
 * <br>
91
 * <b>NOTE: </b>
92
 * If an {@link #getOtherNode() otherNode} represents a node
93
 * of the same tree the key does not represent a strict tree structure
94
 * anymore. However, as this is a rare case we will still use this term
95
 * at some places.</li>
96
 *
97
 * <li>{@link #getSubkey() Subkey}:<br>
98
 *
99
 * A node may also link to another key ({@link #getSubkey() subkey}) as a whole, which is
100
 * equal to an {@link #getOtherNode() otherNode} link to the root node of the other key.
101
 * In this case the path in the decision graph spans over multiple keys.</li>
102
 * This structure is typically used when a key covers taxa down to a certain rank, whereas
103
 * taxa below this rank are covered by extra keys (e.g. a parent key may cover all taxa
104
 * of rank species while subspecies and varieties are covered by a subkeys for each of these
105
 * species.
106
 * Another usecase for subkeys is the existence of an alternative key for a certain part
107
 * of the decision tree.
108
 *
109
 * <li>Multiple taxa<br>
110
 *
111
 * Some nodes in legacy keys do link to multiple taxa, meaning that the key ambigous at
112
 * this point. To represent such nodes one must use child nodes with empty
113
 * {@link #getStatement() statements} for each such taxon (in all other cases - except for
114
 * root nodes - the <code>statement</code> is required).
115
 * Applications that do visualize the key should handle such a node-subnode structure as one
116
 * node with multiple taxon links. This complicated data structure has been chosen for
117
 * this rare to avoid a more complicated <code>List<Taxon></code> structure for the standard
118
 * case.</li>
119
 *
120
 * The {@link PolytomousKey#getRoot() root node of the key} may represent the entry point
121
 * question or feature but does naturally neither have a statement nor a linked taxon as
122
 * there is no prior decision yet.
123
 *
124
 * <h4>Notes</h4>
125
 * <p>
126
 * A polytomous key node can be referenced from multiple other nodes via the
127
 * {@link #getOtherNode() otherNode} attribute of the other nodes. Therefore, though
128
 * we speek about a "decision tree" structure a node does not necessarily have only
129
 * one parent.
130
 * However, nodes are mainly represented in a tree structure and therefore do have
131
 * a defined {@link #getParent() parent} which is the "main" parent. But when implementing
132
 * visualizing or editing tools one should keep in mind that this parent may not be
133
 * the only node linking the child node.
134
 *
135
 * @author a.mueller
136
 * @since 13-Oct-2010
137
 */
138
@SuppressWarnings("serial")
139
@XmlAccessorType(XmlAccessType.FIELD)
140
@XmlType(name = "PolytomousKeyNode", propOrder = {
141
        "key",
142
        "parent",
143
        "children",
144
		"sortIndex",
145
		"nodeNumber",
146
		"statement",
147
		"question",
148
		"feature",
149
		"taxon",
150
		"subkey",
151
		"otherNode",
152
		"modifyingText" })
153
@XmlRootElement(name = "FeaPolytomousKeyNodetureNode")
154
@Entity
155
@Audited
156
public class PolytomousKeyNode extends VersionableEntity implements IMultiLanguageTextHolder {
157
	private static final Logger logger = LogManager.getLogger(PolytomousKeyNode.class);
158

    
159
	// This is the main key a node belongs to. Although other keys may also
160
	// reference <code>this</code> node, a node usually belongs to a given key.
161
	@XmlElement(name = "PolytomousKey")
162
	@XmlIDREF
163
	@XmlSchemaType(name = "IDREF")
164
//	@NotNull
165
	@ManyToOne(fetch = FetchType.LAZY)
166
	@Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE })
167
	private PolytomousKey key;
168

    
169
	@XmlElementWrapper(name = "Children")
170
	@XmlElement(name = "Child")
171
	// @OrderColumn("sortIndex") //JPA 2.0 same as @IndexColumn
172
	// @IndexColumn does not work because not every PolytomousKeyNode has a parent.
173
	// But only NotNull will solve the problem (otherwise
174
	// we will need a join table
175
	// http://stackoverflow.com/questions/2956171/jpa-2-0-ordercolumn-annotation-in-hibernate-3-5
176
	// http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-collection-extratype-indexbidir
177
	// see also https://forum.hibernate.org/viewtopic.php?p=2392563
178
	// http://opensource.atlassian.com/projects/hibernate/browse/HHH-4390
179
	// reading works, but writing doesn't
180
	//
181
	@OrderColumn(name = "sortIndex", nullable=true)  //, base = 0
182
//	@OrderBy("sortIndex")
183
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
184
	@Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.DELETE })
185
	private List<PolytomousKeyNode> children = new ArrayList<>();
186

    
187
	@XmlElement(name = "Parent")
188
	@XmlIDREF
189
	@XmlSchemaType(name = "IDREF")
190
	@Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE })
191
	@ManyToOne(fetch = FetchType.LAZY, targetEntity = PolytomousKeyNode.class)
192
	@JoinColumn(name = "parent_id" /*, insertable=false, updatable=false, nullable=false */)
193
	private PolytomousKeyNode parent;
194

    
195
	//see comment on children @IndexColumn
196
	//see also https://dev.e-taxonomy.eu/redmine/issues/3722, #4278
197
	@Transient
198
	private Integer sortIndex = -1;
199

    
200
	@XmlElement(name = "Statement")
201
	@XmlIDREF
202
	@XmlSchemaType(name = "IDREF")
203
	@ManyToOne(fetch = FetchType.LAZY)
204
	@Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.DELETE })
205
	private KeyStatement statement;
206

    
207
	@XmlElement(name = "Question")
208
	@XmlIDREF
209
	@XmlSchemaType(name = "IDREF")
210
	@ManyToOne(fetch = FetchType.LAZY)
211
	@Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.DELETE})
212
	private KeyStatement question;
213

    
214
	@XmlElement(name = "Feature")
215
	@XmlIDREF
216
	@XmlSchemaType(name = "IDREF")
217
	@ManyToOne(fetch = FetchType.LAZY)
218
//    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})  remove cascade #5755
219
	private Feature feature;
220

    
221
	@XmlElement(name = "Taxon")
222
	@XmlIDREF
223
	@XmlSchemaType(name = "IDREF")
224
	@ManyToOne(fetch = FetchType.LAZY)
225
	@Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})
226
	private Taxon taxon;
227

    
228
	// Refers to an entire key
229
	// <code>this</code> node, a node usually belongs to a given key.
230
	@XmlElement(name = "SubKey")
231
	@XmlIDREF
232
	@XmlSchemaType(name = "IDREF")
233
	@ManyToOne(fetch = FetchType.LAZY)
234
	@Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})
235
	private PolytomousKey subkey;
236

    
237
	// Refers to an other node within this key or an other key
238
	@XmlElement(name = "PolytomousKey")
239
	@XmlIDREF
240
	@XmlSchemaType(name = "IDREF")
241
	@ManyToOne(fetch = FetchType.LAZY)
242
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})
243
	private PolytomousKeyNode otherNode;
244

    
245
	private Integer nodeNumber = null;
246

    
247
	// TODO should be available for each taxon/result
248
	@XmlElement(name = "ModifyingText")
249
	@XmlJavaTypeAdapter(MultilanguageTextAdapter.class)
250
	@OneToMany(fetch = FetchType.LAZY)
251
	@MapKeyJoinColumn(name="modifyingtext_mapkey_id")
252
    @Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE })
253
	private Map<Language, LanguageString> modifyingText = new HashMap<>();
254

    
255
// ************************** FACTORY ********************************/
256

    
257
	/**
258
	 * Creates a new empty polytomous key node instance.
259
	 */
260
	public static PolytomousKeyNode NewInstance() {
261
		return new PolytomousKeyNode();
262
	}
263

    
264
	/**
265
	 * Creates a new polytomous key node instance.
266
	 *
267
	 */
268
	public static PolytomousKeyNode NewInstance(String statement) {
269
		PolytomousKeyNode result = new PolytomousKeyNode();
270
		result.setStatement(KeyStatement.NewInstance(statement));
271
		return result;
272
	}
273

    
274
	/**
275
	 * Creates a new polytomous key node instance.
276
	 *
277
	 */
278
	public static PolytomousKeyNode NewInstance(String statement,
279
			String question, Taxon taxon, Feature feature) {
280
		PolytomousKeyNode result = new PolytomousKeyNode();
281
		result.setTaxon(taxon);
282
		result.setStatement(KeyStatement.NewInstance(statement));
283
		result.setQuestion(KeyStatement.NewInstance(question));
284
		result.setFeature(feature);
285
		return result;
286
	}
287

    
288
// ************************** CONSTRUCTOR *****************************/
289

    
290
	/**
291
	 * Class constructor: creates a new empty feature node instance.
292
	 */
293
	protected PolytomousKeyNode() {
294
		super();
295
	}
296

    
297
// ** ********************** GETTER / SETTER  ******************************/
298

    
299

    
300
	//see #4278 and #4200, alternatively can be private and use deproxy(this, PolytomousKeyNode.class)
301
	protected void setSortIndex(Integer sortIndex) {
302
//      sortIndex = sortIndex;  old #3722
303
        //do nothing
304
	}
305

    
306

    
307
	public PolytomousKey getKey() {
308
		return key;
309
	}
310
	public void setKey(PolytomousKey key) {
311
		this.key = key;
312
	}
313

    
314
	/**
315
	 * The node number is the number of the node within the key. This
316
	 * corresponds to the number for key choices in written keys.
317
	 */
318
	public Integer getNodeNumber() {
319
		return nodeNumber;
320
	}
321

    
322
	/**
323
	 * Is computed automatically and therefore should not be set by the user.
324
	 */
325
	public void setNodeNumber(Integer nodeNumber) {
326
		this.nodeNumber = nodeNumber;
327
	}
328

    
329
	/**
330
	 * Returns the taxon this node links to. This is usually the case when this
331
	 * node is a leaf.
332
	 *
333
	 * @return
334
	 * @see #setTaxon(Taxon)
335
	 * @see #getSubkey()
336
	 * @see #getChildren()
337
	 * @see #getOtherNode()
338
	 */
339
	public Taxon getTaxon() {
340
		return taxon;
341
	}
342

    
343
	/**
344
	 * Sets the taxon this node links to. <BR>
345
	 * If a tax
346
	 *
347
	 * @param taxon
348
	 * @see #getTaxon()
349
	 */
350
	public void setTaxon(Taxon taxon) {
351
		this.taxon = taxon;
352
	}
353

    
354
	/**
355
	 * @return
356
	 * @see #setSubkey(PolytomousKey)
357
	 * @see #getTaxon()
358
	 * @see #getChildren()
359
	 * @see #getOtherNode()
360
	 */
361
	public PolytomousKey getSubkey() {
362
		return subkey;
363
	}
364

    
365
	/**
366
	 * @param subkey
367
	 * @see #getSubkey()
368
	 */
369
	public void setSubkey(PolytomousKey subkey) {
370
		this.subkey = subkey;
371
	}
372

    
373
	/**
374
	 * A link to another sub-node, which has not *this*
375
	 * node as primary parent. The sub-node may be within
376
	 * this key or within another key.
377
	 * @see #setOtherNode(PolytomousKeyNode)
378
	 * @see #getTaxon()
379
	 * @see #getChildren()
380
	 * @see #getSubkey()
381
	 */
382
	public PolytomousKeyNode getOtherNode() {
383
		return otherNode;
384
	}
385

    
386
	/**
387
	 * @param otherNode
388
	 * @see #getOtherNode()
389
	 */
390
	public void setOtherNode(PolytomousKeyNode otherNode) {
391
		this.otherNode = otherNode;
392
	}
393

    
394
	// TODO
395
	public void setFeature(Feature feature) {
396
		this.feature = feature;
397
	}
398
	public Feature getFeature() {
399
		return feature;
400
	}
401

    
402
	/**
403
	 * Returns the parent node of <code>this</code> child.
404
	 */
405
	public PolytomousKeyNode getParent() {
406
		return parent;
407
	}
408

    
409
	/**
410
	 * For bidirectional use only !
411
	 *
412
	 * @param parent
413
	 */
414
	protected void setParent(PolytomousKeyNode parent) {
415
        PolytomousKeyNode oldParent = this.parent;
416
        if (oldParent != null){
417
            if (oldParent.getChildren().contains(this)){
418
                    oldParent.removeChild(this);
419
            }
420
        }
421
        this.parent = parent;
422

    
423
    }
424

    
425
	/**
426
	 * Returns the (ordered) list of feature nodes which are children nodes of
427
	 * <i>this</i> feature node.
428
	 */
429
	public List<PolytomousKeyNode> getChildren() {
430
		return children;
431
	}
432

    
433
	/**
434
	 * Adds the given polytomous key node at the end of the list of children of
435
	 * <i>this</i> polytomous key node.
436
	 *
437
	 * @param child
438
	 *            the feature node to be added
439
	 * @see #getChildren()
440
	 * @see #setChildren(List)
441
	 * @see #addChild(PolytomousKeyNode, int)
442
	 * @see #removeChild(PolytomousKeyNode)
443
	 * @see #removeChild(int)
444
	 */
445
	public void addChild(PolytomousKeyNode child) {
446
		addChild(child, children.size());
447
	}
448

    
449
	/**
450
	 * Inserts the given child node in the list of children of <i>this</i>
451
	 * polytomous key node at the given (index + 1) position. If the given index
452
	 * is out of bounds an exception will be thrown.<BR>
453
	 *
454
	 * @param child
455
	 *            the polytomous key node to be added
456
	 * @param index
457
	 *            the integer indicating the position at which the child should
458
	 *            be added
459
	 * @see #getChildren()
460
	 * @see #setChildren(List)
461
	 * @see #addChild(PolytomousKeyNode)
462
	 * @see #removeChild(PolytomousKeyNode)
463
	 * @see #removeChild(int)
464
	 */
465
	public void addChild(PolytomousKeyNode child, int index) {
466
		if (index < 0 || index > children.size() + 1) {
467
			throw new IndexOutOfBoundsException("Wrong index: " + index);
468
		}
469

    
470
		if(nodeNumber == null) {
471
            	nodeNumber = getMaxNodeNumberFromRoot() + 1;
472
        }
473

    
474
		children.add(index, child);
475
		child.setKey(this.getKey());
476

    
477
		child.setParent(this);
478
	}
479

    
480
	/**
481
	 * Removes the given polytomous key node from the list of
482
	 * {@link #getChildren() children} of <i>this</i> polytomous key node.
483
	 *
484
	 * @param child
485
	 *            the feature node which should be removed
486
	 * @see #getChildren()
487
	 * @see #addChild(PolytomousKeyNode, int)
488
	 * @see #addChild(PolytomousKeyNode)
489
	 * @see #removeChild(int)
490
	 */
491
	public void removeChild(PolytomousKeyNode child) {
492
	    int index = children.indexOf(child);
493
		if (index >= 0) {
494
			removeChild(index);
495
		}
496
	}
497

    
498
	/**
499
	 * Removes the feature node placed at the given (index + 1) position from
500
	 * the list of {@link #getChildren() children} of <i>this</i> feature node.
501
	 * If the given index is out of bounds no child will be removed.
502
	 *
503
	 * @param index
504
	 *            the integer indicating the position of the feature node to be
505
	 *            removed
506
	 * @see #getChildren()
507
	 * @see #addChild(PolytomousKeyNode, int)
508
	 * @see #addChild(PolytomousKeyNode)
509
	 * @see #removeChild(PolytomousKeyNode)
510
	 */
511
	public void removeChild(int index) {
512
		PolytomousKeyNode child = children.get(index);
513
		if (child != null) {
514
			children.remove(index);
515
			child.setParent(null);
516
			// TODO workaround (see sortIndex doc)
517
			for (int i = 0; i < children.size(); i++) {
518
				PolytomousKeyNode childAt = children.get(i);
519
				childAt.setSortIndex(i);
520
			}
521
			child.setSortIndex(null);
522
			child.setNodeNumber(null);
523
		}
524
		refreshNodeNumbering();
525
	}
526

    
527
// **************************** METHODS ************************************/
528

    
529
	/**
530
	 * Returns the current maximum value of the node number in the entire key
531
	 * starting from the root.
532
	 */
533
	private int getMaxNodeNumberFromRoot() {
534
		PolytomousKeyNode rootKeyNode = this.getKey().getRoot();
535
		int rootNumber = this.getKey().getStartNumber();
536

    
537
		return getMaxNodeNumber(rootNumber, rootKeyNode);
538
	}
539

    
540
	/**
541
	 * Returns the current maximum value of the node number in the entire key
542
	 * starting from the given key node, comparing with a given max value as input.
543
	 *
544
	 * @return
545
	 */
546
	private int getMaxNodeNumber(int maxNumber, PolytomousKeyNode parent) {
547
		if (parent.getNodeNumber() != null) {
548
			maxNumber = (maxNumber < parent.getNodeNumber()) ? parent.getNodeNumber() : maxNumber;
549
			for (PolytomousKeyNode child : parent.getChildren()) {
550
			    if (parent == child){
551
					throw new RuntimeException("Parent and child are the same for the given key node. This will lead to an infinite loop when updating the max node number.");
552
				}else{
553
					maxNumber = getMaxNodeNumber(maxNumber, child);
554
				}
555
			}
556
		}
557
		return maxNumber;
558
	}
559

    
560
	/**
561
	 * Refresh numbering of key nodes starting from root.
562
	 *
563
	 */
564
	public void refreshNodeNumbering() {
565
		updateNodeNumbering(getKey().getRoot(), getKey().getStartNumber());
566
	}
567

    
568
	/**
569
	 * Recursively (depth-first) refresh numbering of key nodes starting from the given key node,
570
	 * starting with a given node number.
571
	 *
572
	 * @return new starting node number value
573
	 */
574
	private int updateNodeNumbering(PolytomousKeyNode node,int nodeN) {
575
		int newNodeN = nodeN;
576
		if (node.isLeaf()) {
577
			node.setNodeNumber(null);
578
		} else {
579
			node.setNodeNumber(nodeN);
580
			newNodeN++;
581
			List<PolytomousKeyNode> children = node.getChildren();;
582
			for (PolytomousKeyNode child : children) {
583
				if (node == child){
584
					throw new RuntimeException("Parent and child are the same for the given key node. This will lead to an infinite loop when updating node numbers.");
585
				}else{
586
					newNodeN = updateNodeNumbering(child, newNodeN);
587
				}
588
			}
589
		}
590
		return newNodeN;
591
	}
592

    
593
	/**
594
	 * Returns the feature node placed at the given (childIndex + 1) position
595
	 * within the list of {@link #getChildren() children} of <i>this</i> feature
596
	 * node. If the given index is out of bounds no child will be returned.
597
	 *
598
	 * @param childIndex
599
	 *            the integer indicating the position of the feature node
600
	 * @see #getChildren()
601
	 * @see #addChild(PolytomousKeyNode, int)
602
	 * @see #removeChild(int)
603
	 */
604
	public PolytomousKeyNode getChildAt(int childIndex) {
605
		return children.get(childIndex);
606
	}
607

    
608
	/**
609
	 * Returns the number of children nodes of <i>this</i> feature node.
610
	 *
611
	 * @see #getChildren()
612
	 */
613
	@Transient
614
	public int childCount() {
615
		return children.size();
616
	}
617

    
618
	/**
619
	 * Returns the integer indicating the position of the given feature node
620
	 * within the list of {@link #getChildren() children} of <i>this</i> feature
621
	 * node. If the list does not contain this node then -1 will be returned.
622
	 *
623
	 * @param node
624
	 *            the polytomous key node the position of which is searched
625
	 * @see #addChild(PolytomousKeyNode, int)
626
	 * @see #removeChild(int)
627
	 */
628
	public int getIndex(PolytomousKeyNode node) {
629
		if (!children.contains(node)) {
630
			return -1;
631
		} else {
632
			return children.indexOf(node);
633
		}
634
	}
635

    
636
	/**
637
	 * Returns the boolean value indicating if <i>this</i> polytomous key node has
638
	 * children (false) or not (true). A node without children is at the
639
	 * bottommost level of a tree and is called a leaf.
640
	 *
641
	 * @see #getChildren()
642
	 * @see #getChildCount()
643
	 */
644
	@Transient
645
	public boolean isLeaf() {
646
		return children.size() < 1;
647
	}
648

    
649
	// ** ********************** QUESTIONS AND STATEMENTS ************************/
650

    
651
	/**
652
	 * Returns the statement for <code>this</code> PolytomousKeyNode. When coming
653
	 * from the parent node the user needs to agree with the statement (and disagree
654
	 * with all statements of sibling nodes) to follow <code>this</code> node.<BR>
655
	 * The statement may stand alone (standard in classical keys) or it may be
656
	 * either the answer to the {@link #getQuestion() question} or the
657
	 * value for the {@link #getFeature() feature} of the parent node.
658
	 *
659
	 * @return the statement
660
	 * @see #getQuestion()
661
	 */
662
	public KeyStatement getStatement() {
663
		return statement;
664
	}
665

    
666
	/**
667
	 * This is a convenience method to set the statement text for this node in
668
	 * the given language. <BR>
669
	 * If no statement exists yet a new statement is created. <BR>
670
	 * If a statement text in the given language exists already it is
671
	 * overwritten and the old text is returned. If language is
672
	 * <code>null</code> the default language is used instead.
673
	 *
674
	 * @param text
675
	 *            the statement text
676
	 * @param language
677
	 *            the language of the statement text
678
	 * @return the old statement text in the given language as LanguageString
679
	 */
680
	public LanguageString addStatementText(String text, Language language) {
681
		if (language == null) {
682
			language = Language.DEFAULT();
683
		}
684
		if (this.statement == null) {
685
			setStatement(KeyStatement.NewInstance());
686
		}
687
		return getStatement().putLabel(language, text);
688
	}
689

    
690
	/**
691
	 * @param statement
692
	 * @see #getStatement()
693
	 */
694
	public void setStatement(KeyStatement statement) {
695
		this.statement = statement;
696
	}
697

    
698
	/**
699
	 * Returns the question for <code>this</code> PolytomousKeyNode. <BR>
700
	 * A question is answered by statements in leads below this tree node.
701
	 * Questions are optional and are usually empty in traditional keys.
702
	 *
703
	 * @return the question
704
	 * @see #getStatement()
705
	 */
706
	public KeyStatement getQuestion() {
707
		return question;
708
	}
709

    
710
	/**
711
	 * This is a convenience method to sets the question text for this node in
712
	 * the given language. <BR>
713
	 * If no question exists yet a new question is created. <BR>
714
	 * If a question text in the given language exists already it is overwritten
715
	 * and the old text is returned. If language is <code>null</code> the
716
	 * default language is used instead.
717
	 *
718
	 * @param text
719
	 * @param language
720
	 * @return
721
	 */
722
	public LanguageString addQuestionText(String text, Language language) {
723
		if (language == null) {
724
			language = Language.DEFAULT();
725
		}
726
		if (this.question == null) {
727
			setQuestion(KeyStatement.NewInstance());
728
		}
729
		return getQuestion().putLabel(language, text);
730
	}
731

    
732
	/**
733
	 * @param question
734
	 * @see #getQuestion()
735
	 */
736
	public void setQuestion(KeyStatement question) {
737
		this.question = question;
738
	}
739

    
740
	// **************** modifying text ***************************************
741

    
742
	/**
743
	 * Returns the {@link MultilanguageText} like "an unusual form of",
744
	 * commenting the determined taxon. That is a modifyingText may by used to
745
	 * comment or to constraint the decision step represented by the edge
746
	 * leading to <i>this</i> node
747
	 * <p>
748
	 * All {@link LanguageString language strings} contained in the
749
	 * multilanguage texts should all have the same meaning.<BR>
750
	 */
751
	public Map<Language, LanguageString> getModifyingText() {
752
		return this.modifyingText;
753
	}
754

    
755
	/**
756
	 * See {@link #getModifyingText}
757
	 *
758
	 * @param description
759
	 *            the language string describing the validity in a particular
760
	 *            language
761
	 * @see #getModifyingText()
762
	 * @see #putModifyingText(Language, String)
763
	 */
764
	public LanguageString putModifyingText(LanguageString description) {
765
		return this.modifyingText.put(description.getLanguage(), description);
766
	}
767

    
768
	/**
769
	 * See {@link #getModifyingText}
770
	 *
771
	 * @param text
772
	 *            the string describing the validity in a particular language
773
	 * @param language
774
	 *            the language in which the text string is formulated
775
	 * @see #getModifyingText()
776
	 * @see #putModifyingText(LanguageString)
777
	 */
778
	public LanguageString putModifyingText(Language language, String text) {
779
		return this.modifyingText.put(language,
780
				LanguageString.NewInstance(text, language));
781
	}
782

    
783
	/**
784
	 * See {@link #getModifyingText}
785
	 *
786
	 * @param language
787
	 *            the language in which the language string to be removed has
788
	 *            been formulated
789
	 * @see #getModifyingText()
790
	 */
791
	public LanguageString removeModifyingText(Language language) {
792
		return this.modifyingText.remove(language);
793
	}
794

    
795
	/**
796
	 * Sets the taxon of this {@link PolytomousKeyNode}.
797
	 * If this node already has a taxon removes the taxon
798
	 * and puts it to a new empty child node. <BR>
799
	 * If no taxon exists, but empty child nodes exist
800
	 * adds a new empty child node and puts the taxon.
801
	 * Note: Handle with care, if
802
	 * @param taxon
803
	 * @return the number of taxa belong to the node
804
	 * after the taxon was added
805
	 */
806
	public PolytomousKeyNode setOrAddTaxon(Taxon taxon){
807
	    if (taxon == null){
808
	        throw new NullPointerException("Taxon must not be null");
809
	    }
810
	    if(this.taxon != null){
811
            //rearrange first taxon  //TODO code to PKNode class
812
            Taxon firstTaxon = this.removeTaxon();
813
            PolytomousKeyNode firstChildNode = PolytomousKeyNode.NewInstance();
814
            firstChildNode.setTaxon(firstTaxon);
815
            this.addChild(firstChildNode);
816
        }
817
	    if (!emptyChildNodeExists()){
818
	        setTaxon(taxon);
819
	        return this;
820
	    }else{
821
	        PolytomousKeyNode childNode = PolytomousKeyNode.NewInstance();
822
	        childNode.setTaxon(taxon);
823
	        this.addChild(childNode);
824
	        return childNode;
825
	    }
826
	}
827

    
828
    public Taxon removeTaxon() {
829
        Taxon result = taxon;
830
        this.taxon = null;
831
        return result;
832
    }
833

    
834
    private boolean emptyChildNodeExists() {
835
        for (PolytomousKeyNode child : this.children){
836
            if (child.getStatement() == null && child.getQuestion() == null && child.getChildren().isEmpty()
837
                    && child.getSubkey() == null && child.getOtherNode() == null){
838
                return true;
839
            }
840
        }
841
        return false;
842
    }
843

    
844
	// *********************** CLONE ********************************************************/
845

    
846
    /**
847
	 * Clones <i>this</i> PolytomousKeyNode. This is a shortcut that enables to
848
	 * create a new instance that differs only slightly from <i>this</i>
849
	 * PolytomousKeyNode by modifying only some of the attributes. The parent,
850
	 * the feature and the key are the are the same as for the original feature
851
	 * node the children are removed.
852
	 *
853
	 * @see eu.etaxonomy.cdm.model.common.VersionableEntity#clone()
854
	 * @see java.lang.Object#clone()
855
	 */
856
	@Override
857
	public PolytomousKeyNode clone() {
858
		PolytomousKeyNode result;
859
		try {
860
			result = (PolytomousKeyNode) super.clone();
861
			result.children = new ArrayList<>();
862

    
863
			result.modifyingText = new HashMap<>();
864
			for (Entry<Language, LanguageString> entry : this.modifyingText
865
					.entrySet()) {
866
				result.putModifyingText(entry.getValue());
867
			}
868

    
869
			return result;
870
		} catch (CloneNotSupportedException e) {
871
			logger.warn("Object does not implement cloneable");
872
			e.printStackTrace();
873
			return null;
874
		}
875
	}
876

    
877
}
(23-23/38)