Project

General

Profile

Download (28 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
	 * @return
308
	 */
309
	public PolytomousKey getKey() {
310
		return key;
311
	}
312

    
313
	/**
314
	 * @param key
315
	 */
316
	public void setKey(PolytomousKey key) {
317
		this.key = key;
318
	}
319

    
320
	/**
321
	 * The node number is the number of the node within the key. This
322
	 * corresponds to the number for key choices in written keys.
323
	 */
324
	public Integer getNodeNumber() {
325
		return nodeNumber;
326
	}
327

    
328
	/**
329
	 * Is computed automatically and therefore should not be set by the user.
330
	 */
331
	public void setNodeNumber(Integer nodeNumber) {
332
		this.nodeNumber = nodeNumber;
333
	}
334

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

    
349
	/**
350
	 * Sets the taxon this node links to. <BR>
351
	 * If a tax
352
	 *
353
	 * @param taxon
354
	 * @see #getTaxon()
355
	 */
356
	public void setTaxon(Taxon taxon) {
357
		this.taxon = taxon;
358
	}
359

    
360
	/**
361
	 * @return
362
	 * @see #setSubkey(PolytomousKey)
363
	 * @see #getTaxon()
364
	 * @see #getChildren()
365
	 * @see #getOtherNode()
366
	 */
367
	public PolytomousKey getSubkey() {
368
		return subkey;
369
	}
370

    
371
	/**
372
	 * @param subkey
373
	 * @see #getSubkey()
374
	 */
375
	public void setSubkey(PolytomousKey subkey) {
376
		this.subkey = subkey;
377
	}
378

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

    
392
	/**
393
	 * @param otherNode
394
	 * @see #getOtherNode()
395
	 */
396
	public void setOtherNode(PolytomousKeyNode otherNode) {
397
		this.otherNode = otherNode;
398
	}
399

    
400
	// TODO
401
	public void setFeature(Feature feature) {
402
		this.feature = feature;
403
	}
404
	public Feature getFeature() {
405
		return feature;
406
	}
407

    
408
	/**
409
	 * Returns the parent node of <code>this</code> child.
410
	 */
411
	public PolytomousKeyNode getParent() {
412
		return parent;
413
	}
414

    
415
	/**
416
	 * For bidirectional use only !
417
	 *
418
	 * @param parent
419
	 */
420
	protected void setParent(PolytomousKeyNode parent) {
421
        PolytomousKeyNode oldParent = this.parent;
422
        if (oldParent != null){
423
            if (oldParent.getChildren().contains(this)){
424
                    oldParent.removeChild(this);
425
            }
426
        }
427
        this.parent = parent;
428

    
429
    }
430

    
431
	/**
432
	 * Returns the (ordered) list of feature nodes which are children nodes of
433
	 * <i>this</i> feature node.
434
	 */
435
	public List<PolytomousKeyNode> getChildren() {
436
		return children;
437
	}
438

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

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

    
476
		if(nodeNumber == null) {
477
            	nodeNumber = getMaxNodeNumberFromRoot() + 1;
478
        }
479

    
480
		children.add(index, child);
481
		child.setKey(this.getKey());
482

    
483
		child.setParent(this);
484
	}
485

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

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

    
533
// **************************** METHODS ************************************/
534

    
535
	/**
536
	 * Returns the current maximum value of the node number in the entire key
537
	 * starting from the root.
538
	 */
539
	private int getMaxNodeNumberFromRoot() {
540
		PolytomousKeyNode rootKeyNode = this.getKey().getRoot();
541
		int rootNumber = this.getKey().getStartNumber();
542

    
543
		return getMaxNodeNumber(rootNumber, rootKeyNode);
544
	}
545

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

    
566
	/**
567
	 * Refresh numbering of key nodes starting from root.
568
	 *
569
	 */
570
	public void refreshNodeNumbering() {
571
		updateNodeNumbering(getKey().getRoot(), getKey().getStartNumber());
572
	}
573

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

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

    
614
	/**
615
	 * Returns the number of children nodes of <i>this</i> feature node.
616
	 *
617
	 * @see #getChildren()
618
	 */
619
	@Transient
620
	public int childCount() {
621
		return children.size();
622
	}
623

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

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

    
655
	// ** ********************** QUESTIONS AND STATEMENTS ************************/
656

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

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

    
696
	/**
697
	 * @param statement
698
	 * @see #getStatement()
699
	 */
700
	public void setStatement(KeyStatement statement) {
701
		this.statement = statement;
702
	}
703

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

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

    
738
	/**
739
	 * @param question
740
	 * @see #getQuestion()
741
	 */
742
	public void setQuestion(KeyStatement question) {
743
		this.question = question;
744
	}
745

    
746
	// **************** modifying text ***************************************
747

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

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

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

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

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

    
863
			result.modifyingText = new HashMap<Language, LanguageString>();
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
    public Taxon removeTaxon() {
878
        Taxon result = taxon;
879
        this.taxon = null;
880
        return result;
881
    }
882

    
883
}
(23-23/38)