Project

General

Profile

Download (27.8 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

    
158
	private static final Logger logger = LogManager.getLogger(PolytomousKeyNode.class);
159

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

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

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

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

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

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

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

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

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

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

    
246
	private Integer nodeNumber = null;
247

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

    
256
// ************************** FACTORY ********************************/
257

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

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

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

    
289
// ************************** CONSTRUCTOR *****************************/
290

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

    
298
// ** ********************** GETTER / SETTER  ******************************/
299

    
300

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

    
307

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

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

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

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

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

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

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

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

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

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

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

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

    
424
    }
425

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

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

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

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

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

    
478
		child.setParent(this);
479
	}
480

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

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

    
528
// **************************** METHODS ************************************/
529

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

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

    
541
	/**
542
	 * Returns the current maximum value of the node number in the entire key
543
	 * starting from the given key node, comparing with a given max value as input.
544
	 *
545
	 * @return
546
	 */
547
	private int getMaxNodeNumber(int maxNumber, PolytomousKeyNode parent) {
548
		if (parent.getNodeNumber() != null) {
549
			maxNumber = (maxNumber < parent.getNodeNumber()) ? parent.getNodeNumber() : maxNumber;
550
			for (PolytomousKeyNode child : parent.getChildren()) {
551
			    if (parent == child){
552
					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.");
553
				}else{
554
					maxNumber = getMaxNodeNumber(maxNumber, child);
555
				}
556
			}
557
		}
558
		return maxNumber;
559
	}
560

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

    
569
	/**
570
	 * Recursively (depth-first) refresh numbering of key nodes starting from the given key node,
571
	 * starting with a given node number.
572
	 *
573
	 * @return new starting node number value
574
	 */
575
	private int updateNodeNumbering(PolytomousKeyNode node,int nodeN) {
576
		int newNodeN = nodeN;
577
		if (node.isLeaf()) {
578
			node.setNodeNumber(null);
579
		} else {
580
			node.setNodeNumber(nodeN);
581
			newNodeN++;
582
			List<PolytomousKeyNode> children = node.getChildren();
583
			for (PolytomousKeyNode child : children) {
584
				if (node == child){
585
					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.");
586
				}else{
587
					newNodeN = updateNodeNumbering(child, newNodeN);
588
				}
589
			}
590
		}
591
		return newNodeN;
592
	}
593

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

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

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

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

    
650
	// ** ********************** QUESTIONS AND STATEMENTS ************************/
651

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

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

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

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

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

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

    
741
	// **************** modifying text ***************************************
742

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

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

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

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

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

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

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

    
845
	// *********************** CLONE ********************************************************/
846

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

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

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

    
878
}
(23-23/38)