001package de.deepamehta.core.impl;
002
003import de.deepamehta.core.RelatedTopic;
004import de.deepamehta.core.model.AssociationModel;
005import de.deepamehta.core.model.RelatedTopicModel;
006import de.deepamehta.core.model.TopicModel;
007
008import org.codehaus.jettison.json.JSONObject;
009
010
011
012class RelatedTopicModelImpl extends TopicModelImpl implements RelatedTopicModel {
013
014    // ---------------------------------------------------------------------------------------------- Instance Variables
015
016    private AssociationModelImpl relatingAssoc;
017
018    // ---------------------------------------------------------------------------------------------------- Constructors
019
020    RelatedTopicModelImpl(TopicModelImpl topic, AssociationModelImpl relatingAssoc) {
021        super(topic);
022        this.relatingAssoc = relatingAssoc;
023    }
024
025    RelatedTopicModelImpl(RelatedTopicModelImpl relatedTopic) {
026        super(relatedTopic);
027        this.relatingAssoc = relatedTopic.getRelatingAssociation();
028    }
029
030    // -------------------------------------------------------------------------------------------------- Public Methods
031
032    @Override
033    public AssociationModelImpl getRelatingAssociation() {
034        return relatingAssoc;
035    }
036
037
038
039    // === Serialization ===
040
041    @Override
042    public JSONObject toJSON() {
043        try {
044            JSONObject o = super.toJSON();
045            // Note: the relating association might be uninitialized and thus not serializable.
046            // This is the case at least for enrichments which have no underlying topics (e.g. timestamps).
047            // ### TODO: remodel enrichments? Don't put them in a child topics model but in a proprietary field?
048            if (relatingAssoc.getRoleModel1() != null) {
049                o.put("assoc", relatingAssoc.toJSON());
050            }
051            //
052            return o;
053        } catch (Exception e) {
054            throw new RuntimeException("Serialization failed (" + this + ")", e);
055        }
056    }
057
058
059
060    // === Java API ===
061
062    @Override
063    public RelatedTopicModel clone() {
064        try {
065            return (RelatedTopicModel) super.clone();
066        } catch (Exception e) {
067            throw new RuntimeException("Cloning a RelatedTopicModel failed", e);
068        }
069    }
070
071    @Override
072    public String toString() {
073        return super.toString() + ", relating " + relatingAssoc;
074    }
075
076
077
078    // ----------------------------------------------------------------------------------------- Package Private Methods
079
080    @Override
081    String className() {
082        return "related topic";
083    }
084
085    @Override
086    RelatedTopic instantiate() {
087        return new RelatedTopicImpl(this, pl);
088    }
089}