Beispiel #1
0
 /// <summary>
 /// Creates a new relation.
 /// </summary>
 /// <param name="id"></param>
 /// <param name="members"></param>
 /// <returns></returns>
 public static Relation Create(long id, params RelationMember[] members)
 {
     Relation relation = new Relation();
     relation.Id = id;
     relation.Members = new List<RelationMember>(members);
     return relation;
 }
Beispiel #2
0
 /// <summary>
 /// Creates a new relation.
 /// </summary>
 /// <param name="id"></param>
 /// <param name="tags"></param>
 /// <param name="members"></param>
 /// <returns></returns>
 public static Relation Create(long id, TagsCollectionBase tags, params RelationMember[] members)
 {
     Relation relation = new Relation();
     relation.Id = id;
     relation.Members = new List<RelationMember>(members);
     relation.Tags = tags;
     return relation;
 }
        public override void AddRelation(Relation relation)
        {
            if (!relation.Id.HasValue)
                return;

            MaxStringLength(relation.UserName, ref RelationUsr);

            if (relation.Tags != null)
            {
                foreach (Tag tag in relation.Tags)
                {
                    MaxStringLength(tag.Key, ref RelationTagsKey);
                    MaxStringLength(tag.Value, ref RelationTagsValue);
                }
            }

            if (relation.Members != null)
            {
                foreach (RelationMember member in relation.Members)
                {
                    MaxStringLength(member.MemberRole, ref RelationMemberRole);
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Returns the relations for the given ids.
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public override IList<Relation> GetRelations(IList<long> ids)
        {
            if (ids.Count > 0)
            {
                SQLiteConnection con = this.CreateConnection();

                // STEP2: Load ways.
                Dictionary<long, Relation> relations = new Dictionary<long, Relation>();
                string sql;
                SQLiteCommand com;
                SQLiteDataReader reader;
                for (int idx_1000 = 0; idx_1000 <= ids.Count / 1000; idx_1000++)
                {
                    int start_idx = idx_1000 * 1000;
                    int stop_idx = System.Math.Min((idx_1000 + 1) * 1000, ids.Count);

                    sql = "SELECT id, changeset_id, visible, timestamp, version, usr, usr_id FROM relation WHERE (id IN ({0})) ";
                    string ids_string = this.ConstructIdList(ids, start_idx, stop_idx);
                    if (ids_string.Length > 0)
                    {
                        sql = string.Format(sql, ids_string);
                        com = new SQLiteCommand(sql);
                        com.Connection = con;
                        reader = ExecuteReader(com);
                        Relation relation;
                        while (reader.Read())
                        {
                            long id = reader.GetInt64(0);
                            long? changeset_id = reader.IsDBNull(1) ? null : (long?)reader.GetInt64(1);
                            bool? visible = reader.IsDBNull(2) ? null : (bool?)reader.GetBoolean(2);
                            DateTime? timestamp = reader.IsDBNull(3) ? null : (DateTime?)this.ConvertDateTime(reader.GetInt64(3));
                            ulong? version = reader.IsDBNull(4) ? null : (ulong?)reader.GetInt64(4);
                            string user = reader.IsDBNull(5) ? null : reader.GetString(5);
                            long? user_id = reader.IsDBNull(6) ? null : (long?)reader.GetInt64(6);

                            // create way.
                            relation = new Relation();
                            relation.Id = id;
                            relation.Version = version;
                            relation.UserName = user;
                            relation.UserId = user_id;
                            relation.Visible = visible;
                            relation.TimeStamp = timestamp;
                            relation.ChangeSetId = changeset_id;

                            relations.Add(relation.Id.Value, relation);
                        }
                        reader.Close();
                    }
                }

                //STEP3: Load all relation-member relations
                List<long> missing_node_ids = new List<long>();
                for (int idx_1000 = 0; idx_1000 <= ids.Count / 1000; idx_1000++)
                {
                    int start_idx = idx_1000 * 1000;
                    int stop_idx = System.Math.Min((idx_1000 + 1) * 1000, ids.Count);

                    sql = "SELECT relation_id, member_type, member_id, member_role, sequence_id FROM relation_members WHERE (relation_id IN ({0})) ORDER BY sequence_id";
                    string ids_string = this.ConstructIdList(ids, start_idx, stop_idx);
                    if (ids_string.Length > 0)
                    {
                        sql = string.Format(sql, ids_string);
                        com = new SQLiteCommand(sql);
                        com.Connection = con;
                        reader = ExecuteReader(com);
                        while (reader.Read())
                        {
                            long relation_id = reader.GetInt64(0);
                            long member_type = reader.GetInt64(1);
                            long? member_id = reader.IsDBNull(2) ? null : (long?)reader.GetInt64(2);
                            string member_role = reader.IsDBNull(3) ? null : reader.GetString(3);

                            Relation relation;
                            if (relations.TryGetValue(relation_id, out relation))
                            {
                                if (relation.Members == null)
                                {
                                    relation.Members = new List<RelationMember>();
                                }
                                RelationMember member = new RelationMember();
                                member.MemberId = member_id;
                                member.MemberRole = member_role;
                                member.MemberType = this.ConvertMemberType(member_type);

                                relation.Members.Add(member);
                            }
                        }
                        reader.Close();
                    }
                }

                //STEP4: Load all tags.
                for (int idx_1000 = 0; idx_1000 <= ids.Count / 1000; idx_1000++)
                {
                    int start_idx = idx_1000 * 1000;
                    int stop_idx = System.Math.Min((idx_1000 + 1) * 1000, ids.Count);

                    sql = "SELECT * FROM relation_tags WHERE (relation_id IN ({0})) ";
                    string ids_string = this.ConstructIdList(ids, start_idx, stop_idx);
                    if (ids_string.Length > 0)
                    {
                        sql = string.Format(sql, ids_string);
                        com = new SQLiteCommand(sql);
                        com.Connection = con;
                        reader = ExecuteReader(com);
                        while (reader.Read())
                        {
                            long id = reader.GetInt64(0);
                            string key = reader.GetString(1);
                            object value_object = reader[2];
                            string value = string.Empty;
                            if (value_object != null && value_object != DBNull.Value)
                            {
                                value = (string)value_object;
                            }

                            Relation relation;
                            if (relations.TryGetValue(id, out relation))
                            {
                                if (relation.Tags == null)
                                {
                                    relation.Tags = new TagsCollection();
                                }
                                relation.Tags.Add(key, value);
                            }
                        }
                        reader.Close();
                    }
                }

                return relations.Values.ToList<Relation>();
            }
            return new List<Relation>();
        }
        /// <summary>
        /// Tests read/writing a relation.
        /// </summary>
        protected void TestRelationReadWrite()
        {
            this.NotifyEmptyExpected(); // empty test database.

            // create a test-relation.
            Relation relation = new Relation();
            relation.Id = 1;

            // create a target, add the relation, create a source and verify relation in db.
            var target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddRelation(relation);
            target.Flush();
            target.Close();
            var dataSource = this.CreateDataSource();
            Relation foundRelation = dataSource.GetRelation(1);
            this.CompareRelations(relation, foundRelation);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-relation.
            relation = new Relation();
            relation.Id = 1;
            relation.UserName = "******";

            // create a target, add the relation, create a source and verify relation in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddRelation(relation);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundRelation = dataSource.GetRelation(1);
            this.CompareRelations(relation, foundRelation);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-relation.
            relation = new Relation();
            relation.Id = 1;
            relation.UserName = "******";
            relation.UserId = 10;

            // create a target, add the relation, create a source and verify relation in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddRelation(relation);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundRelation = dataSource.GetRelation(1);
            this.CompareRelations(relation, foundRelation);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-relation.
            relation = new Relation();
            relation.Id = 1;
            relation.UserName = "******";
            relation.UserId = 10;
            relation.Version = 1;

            // create a target, add the relation, create a source and verify relation in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddRelation(relation);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundRelation = dataSource.GetRelation(1);
            this.CompareRelations(relation, foundRelation);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-relation.
            relation = new Relation();
            relation.Id = 1;
            relation.UserName = "******";
            relation.UserId = 10;
            relation.Version = 1;
            relation.Visible = true;

            // create a target, add the relation, create a source and verify relation in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddRelation(relation);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundRelation = dataSource.GetRelation(1);
            this.CompareRelations(relation, foundRelation);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-relation.
            relation = new Relation();
            relation.Id = 1;
            relation.UserName = "******";
            relation.UserId = 10;
            relation.Version = 1;
            relation.Visible = true;
            relation.TimeStamp = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

            // create a target, add the relation, create a source and verify relation in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddRelation(relation);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundRelation = dataSource.GetRelation(1);
            this.CompareRelations(relation, foundRelation);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-relation.
            relation = new Relation();
            relation.Id = 1;
            relation.UserName = "******";
            relation.UserId = 10;
            relation.Version = 1;
            relation.Visible = true;
            relation.TimeStamp = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            relation.Tags = new SimpleTagsCollection();
            relation.Tags.Add("tag", "value");

            // create a target, add the relation, create a source and verify relation in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddRelation(relation);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundRelation = dataSource.GetRelation(1);
            this.CompareRelations(relation, foundRelation);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-relation.
            relation = new Relation();
            relation.Id = 1;
            relation.UserName = "******";
            relation.UserId = 10;
            relation.Version = 1;
            relation.Visible = true;
            relation.TimeStamp = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            relation.Members = new List<RelationMember>();
            relation.Members.Add(new RelationMember() { MemberId = 1, MemberRole = "node1", MemberType = OsmGeoType.Node });
            relation.Members.Add(new RelationMember() { MemberId = 2, MemberRole = "node2", MemberType = OsmGeoType.Node });
            relation.Members.Add(new RelationMember() { MemberId = 1, MemberRole = "node1", MemberType = OsmGeoType.Node });
            relation.Members.Add(new RelationMember() { MemberId = 1, MemberRole = "way", MemberType = OsmGeoType.Way });

            // create a target, add the relation, create a source and verify relation in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddRelation(relation);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundRelation = dataSource.GetRelation(1);
            this.CompareRelations(relation, foundRelation);

            this.NotifyEmptyExpected(); // empty test database.

            // create a test-relation.
            relation = new Relation();
            relation.Id = 1;
            relation.UserName = "******";
            relation.UserId = 10;
            relation.Version = 1;
            relation.Visible = true;
            relation.TimeStamp = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            relation.Members = new List<RelationMember>();
            relation.Members.Add(new RelationMember() { MemberId = 1, MemberRole = string.Empty, MemberType = OsmGeoType.Node });

            // create a target, add the relation, create a source and verify relation in db.
            target = this.CreateDataStreamTarget();
            target.Initialize();
            target.AddRelation(relation);
            target.Flush();
            target.Close();
            dataSource = this.CreateDataSource();
            foundRelation = dataSource.GetRelation(1);
            this.CompareRelations(relation, foundRelation);
        }
Beispiel #6
0
        /// <summary>
        /// Adds a relation.
        /// </summary>
        /// <param name="relation"></param>
        private void AddRelation(Relation relation)
        {
            if (_relations.ContainsKey(relation.Id))
            {
                throw new InvalidOperationException("Cannot add an object that already exists in this source!" + Environment.NewLine +
                    "If there is a modification use a changeset!");
            }
            else
            {
                _relations.Add(relation.Id, relation);

                foreach (RelationMember member in relation.Members)
                {
                    OsmGeo member_already_in = null;
                    switch (member.Member.Type)
                    {
                        case OsmType.Node:
                            member_already_in = this.GetNode(member.Member.Id);
                            break;
                        case OsmType.Relation:
                            member_already_in = this.GetRelation(member.Member.Id);
                            break;
                        case OsmType.Way:
                            member_already_in = this.GetWay(member.Member.Id);
                            break;
                    }
                    if (member_already_in == null)
                    {
                        this.AddOsmBase(member.Member);
                    }
                }

            }
        }
        /// <summary>
        /// Converts a domain model relation to an Xml relation.
        /// </summary>
        /// <returns></returns>
        public static relation ConvertTo(this OsmSharp.Osm.Relation relation)
        {
            relation xmlRelation = new relation();

            // set the changeset.
            if (relation.ChangeSetId.HasValue)
            {
                xmlRelation.changeset          = relation.ChangeSetId.Value;
                xmlRelation.changesetSpecified = true;
            }

            // set the id.
            if (relation.Id.HasValue)
            {
                xmlRelation.id          = relation.Id.Value;
                xmlRelation.idSpecified = true;
            }
            else
            {
                xmlRelation.idSpecified = false;
            }

            if (relation.Tags != null)
            {
                xmlRelation.tag = new tag[relation.Tags.Count];
                int idx = 0;
                foreach (var tag in relation.Tags)
                {
                    tag t = new tag();
                    t.k = tag.Key;
                    t.v = tag.Value;
                    xmlRelation.tag[idx] = t;
                    idx++;
                }
            }

            // set the timestamp.
            if (relation.TimeStamp.HasValue)
            {
                xmlRelation.timestamp          = relation.TimeStamp.Value;
                xmlRelation.timestampSpecified = true;
            }

            // set the user data.
            if (relation.UserId.HasValue)
            {
                xmlRelation.uid          = relation.UserId.Value;
                xmlRelation.uidSpecified = true;
            }
            xmlRelation.user = xmlRelation.user;

            // set the version.
            if (relation.Version.HasValue)
            {
                xmlRelation.version          = (ulong)relation.Version.Value;
                xmlRelation.versionSpecified = true;
            }

            // set the visible.
            if (relation.Visible.HasValue)
            {
                xmlRelation.visible          = relation.Visible.Value;
                xmlRelation.visibleSpecified = true;
            }
            else
            {
                xmlRelation.visibleSpecified = false;
            }

            // set the way-specific properties.
            xmlRelation.member = new member[relation.Members.Count];
            for (int i = 0; i < relation.Members.Count; i++)
            {
                var member = relation.Members[i];
                var m      = new member();

                if (member.MemberType.HasValue)
                {
                    switch (member.MemberType.Value)
                    {
                    case OsmGeoType.Node:
                        m.type          = memberType.node;
                        m.typeSpecified = true;
                        break;

                    case OsmGeoType.Relation:
                        m.type          = memberType.relation;
                        m.typeSpecified = true;
                        break;

                    case OsmGeoType.Way:
                        m.type          = memberType.way;
                        m.typeSpecified = true;
                        break;
                    }
                }
                else
                {
                    m.typeSpecified = false;
                }

                if (member.MemberId.HasValue)
                {
                    m.@ref         = member.MemberId.Value;
                    m.refSpecified = true;
                }
                else
                {
                    m.refSpecified = false;
                }
                m.role = member.MemberRole;

                xmlRelation.member[i] = m;
            }

            return(xmlRelation);
        }
        private void Delete(Relation relation)
        {
            OracleCommand command;

            command = this.CreateCommand("delete from relation_members where relation_id = :relation_id");
            command.Parameters.Add(new OracleParameter("relation_id", relation.Id.Value));
            command.ExecuteNonQuery();
            command.Dispose();

            command = this.CreateCommand("delete from relation_tags where relation_id = :relation_id");
            command.Parameters.Add(new OracleParameter("relation_id", relation.Id.Value));
            command.ExecuteNonQuery();
            command.Dispose();

            command = this.CreateCommand("delete from relation where id = :id");
            command.Parameters.Add(new OracleParameter("id", relation.Id.Value));
            command.ExecuteNonQuery();
            command.Dispose();
        }
Beispiel #9
0
        /// <summary>
        /// Creates a relation from a SimpleRelation.
        /// </summary>
        /// <param name="simpleRelation"></param>
        /// <param name="osmGeoSource"></param>
        /// <param name="ways"></param>
        /// <param name="relations"></param>
        /// <returns></returns>
        public static CompleteRelation CreateFrom(Relation simpleRelation, IOsmGeoSource osmGeoSource,
                                                  IDictionary <long, CompleteWay> ways,
                                                  IDictionary <long, CompleteRelation> relations)
        {
            if (simpleRelation == null)
            {
                throw new ArgumentNullException("simpleRelation");
            }
            if (osmGeoSource == null)
            {
                throw new ArgumentNullException("osmGeoSource");
            }
            if (simpleRelation.Id == null)
            {
                throw new Exception("simpleRelation.Id is null");
            }

            CompleteRelation relation = Create(simpleRelation.Id.Value);

            relation.ChangeSetId = simpleRelation.ChangeSetId;
            foreach (Tag pair in simpleRelation.Tags)
            {
                relation.Tags.Add(pair);
            }
            for (int idx = 0; idx < simpleRelation.Members.Count; idx++)
            {
                long   memberId = simpleRelation.Members[idx].MemberId.Value;
                string role     = simpleRelation.Members[idx].MemberRole;

                var member = new CompleteRelationMember();
                member.Role = role;
                switch (simpleRelation.Members[idx].MemberType.Value)
                {
                case OsmGeoType.Node:
                    Node simpleNode = osmGeoSource.GetNode(memberId);
                    if (simpleNode != null)
                    {
                        member.Member = CompleteNode.CreateFrom(simpleNode);
                    }
                    else
                    {
                        return(null);
                    }
                    break;

                case OsmGeoType.Way:
                    CompleteWay completeWay;
                    if (!ways.TryGetValue(memberId, out completeWay))
                    {
                        Way simpleWay = osmGeoSource.GetWay(memberId);
                        if (simpleWay != null)
                        {
                            completeWay = CompleteWay.CreateFrom(simpleWay, osmGeoSource);
                        }
                    }
                    if (completeWay != null)
                    {
                        member.Member = completeWay;
                    }
                    else
                    {
                        return(null);
                    }
                    break;

                case OsmGeoType.Relation:
                    CompleteRelation completeRelation;
                    if (!relations.TryGetValue(memberId, out completeRelation))
                    {
                        Relation simpleRelationMember = osmGeoSource.GetRelation(memberId);
                        if (simpleRelationMember != null)
                        {
                            completeRelation = CompleteRelation.CreateFrom(simpleRelationMember, osmGeoSource);
                        }
                    }
                    if (completeRelation != null)
                    {
                        member.Member = completeRelation;
                    }
                    else
                    {
                        return(null);
                    }
                    break;
                }
                relation.Members.Add(member);
            }
            relation.TimeStamp = simpleRelation.TimeStamp;
            relation.User      = simpleRelation.UserName;
            relation.UserId    = simpleRelation.UserId;
            relation.Version   = simpleRelation.Version.HasValue ? (long)simpleRelation.Version.Value : (long?)null;
            relation.Visible   = simpleRelation.Visible.HasValue && simpleRelation.Visible.Value;

            return(relation);
        }
        /// <summary>
        /// Returns all restrictions that are represented by the given node.
        /// </summary>
        /// <param name="relation"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public List<KeyValuePair<string, long[]>> CalculateRestrictions(Relation relation, IOsmGeoSource source)
        {
            var restrictions = new List<KeyValuePair<string, long[]>>();
            if(relation.Tags.ContainsKeyValue("type", "restriction") &&
                relation.Members != null)
            { // regular restriction.
                Way fromWay = null, toWay = null, viaWay = null;
                Node viaNode = null;
                for(int idx = 0; idx < relation.Members.Count; idx++)
                {
                    var member = relation.Members[idx];
                    if(member.MemberRole == "from")
                    { // the from-way.
                        fromWay = source.GetWay(member.MemberId.Value);
                    }
                    else if(member.MemberRole == "to")
                    { // the to-way.
                        toWay = source.GetWay(member.MemberId.Value);
                    }
                    else if(member.MemberRole == "via")
                    { // the via node/way.
                        if (member.MemberType.Value == OsmGeoType.Node)
                        {
                            viaNode = source.GetNode(member.MemberId.Value);
                        }
                        else if(member.MemberType.Value == OsmGeoType.Way)
                        {
                            viaWay = source.GetWay(member.MemberId.Value);
                        }
                    }
                }

                // check if all data was found and type of restriction.
                if(fromWay != null && toWay != null &&
                    fromWay.Nodes.Count > 1 && toWay.Nodes.Count > 1)
                { // ok, from-to is there and has enough nodes.
                    if(viaWay != null)
                    { // via-part is a way.

                    }
                    else if (viaNode != null)
                    { // via-node is a node.
                        var restriction = new long[3];
                        // get from.
                        if (fromWay.Nodes[0] == viaNode.Id)
                        { // next node is from-node.
                            restriction[0] = fromWay.Nodes[1];
                        }
                        else if(fromWay.Nodes[fromWay.Nodes.Count - 1] == viaNode.Id)
                        { // previous node is from-node.
                            restriction[0] = fromWay.Nodes[fromWay.Nodes.Count - 2];
                        }
                        else
                        { // not found!
                            return restrictions;
                        }
                        restriction[1] = viaNode.Id.Value;
                        // get to.
                        if (toWay.Nodes[0] == viaNode.Id)
                        { // next node is to-node.
                            restriction[2] = toWay.Nodes[1];
                        }
                        else if (toWay.Nodes[toWay.Nodes.Count - 1] == viaNode.Id)
                        { // previous node is to-node.
                            restriction[2] = toWay.Nodes[toWay.Nodes.Count - 2];
                        }
                        else
                        { // not found!
                            return restrictions;
                        }
                        restrictions.Add(new KeyValuePair<string, long[]>(VehicleType.Vehicle, restriction));
                    }
                }
            }
            return restrictions;
        }
Beispiel #11
0
        /// <summary>
        /// Removes a relation from this source but none of the sub-objects.
        /// </summary>
        /// <param name="relation"></param>
        private void RemoveRelation(Relation relation)
        {
            // check if relation can be removed.
            IList<Relation> relations = this.GetRelationsFor(relation);
            if (relations.Count > 0)
            { // cannot remove node; there is still a relation for this relation.
                throw new InvalidOperationException("Cannot remove relation {0}; there exists al least one relation that uses it!");
            }

            // remove all the relation for all it's members
            foreach (RelationMember member in relation.Members)
            {
                _relations_per_member[member.Member.Id].Remove(relation.Id);

                // if there was only one relation for this member remove the member.
                if (_relations_per_member[member.Member.Id].Count == 0)
                {
                    _relations_per_member.Remove(member.Member.Id);
                }
            }

            // remove the relation.
            _relations.Remove(relation.Id);
        }
        /// <summary>
        /// Adds a relation.
        /// </summary>
        /// <param name="relation"></param>
        public override void AddRelation(Relation relation)
        {
            DataRow relation_row = _relationTable.NewRow();

            // format data and create parameters.
            long? id = relation.Id.Value; // id should alrelations contain a value.
            relation_row["id"] = id.ConvertToDBValue<long>();

            long? changeset_id = relation.ChangeSetId;
            relation_row["changeset_id"] = changeset_id.ConvertToDBValue<long>();

            if (!relation.Visible.HasValue)
            {
                relation_row["visible"] = DBNull.Value;
            }
            else
            {
                relation_row["visible"] = relation.Visible.Value ? 1 : 0;
            }

            DateTime? timestamp = relation.TimeStamp;
            relation_row["timestamp"] = timestamp.ConvertToDBValue<DateTime>();

            ulong? version = relation.Version;
            relation_row["version"] = version.ConvertToDBValue<ulong>();

            // set the usr
            relation_row["usr"] = relation.UserName;
            relation_row["usr_id"] = relation.UserId.ConvertToDBValue<long>();

            // add the node and it's tags.
            _relationTable.Rows.Add(relation_row);

            // tags.
            if (relation.Tags != null)
            {
                foreach (Tag tag in relation.Tags)
                {
                    string key = tag.Key;
                    string value = tag.Value;

                    DataRow tag_row = _relationTagsTable.NewRow();
                    tag_row["relation_id"] = id;
                    tag_row["key"] = key.Truncate(255);
                    tag_row["value"] = value.Truncate(255);

                    _relationTagsTable.Rows.Add(tag_row);
                }
            }

            // member.
            if (relation.Members != null)
            {
                long relation_id = relation.Id.Value;

                for (int idx = 0; idx < relation.Members.Count; idx++)
                {
                    RelationMember member = relation.Members[idx]; ;

                    DataRow tag_row = _relationMembersTable.NewRow();
                    tag_row["relation_id"] = id;
                    tag_row["member_type"] = member.MemberType;
                    tag_row["member_id"] = member.MemberId;
                    tag_row["member_role"] = member.MemberRole;
                    tag_row["sequence_id"] = idx;

                    _relationMembersTable.Rows.Add(tag_row);
                }
            }

            // bulk insert if needed.
            if (_relationTable.Rows.Count >= _batch_relations)
            {
                this.BulkCopy(_relationTable, "relation");
                this.BulkCopy(_relationTagsTable, "relation_tags");
                this.BulkCopy(_relationMembersTable, "relation_members");
                this.CreateRelationTables();
            }
        }
Beispiel #13
0
        /// <summary>
        /// Converts an API v6 xml node to a SimpleRelation object.
        /// </summary>
        /// <param name="xml_relation"></param>
        /// <returns></returns>
        private Relation Convertv6XmlRelation(relation xml_relation)
        {
            Relation relation = new Relation();
            relation.Id = xml_relation.id;

            if (xml_relation.tag != null)
            {
                relation.Tags = new TagsCollection();
                foreach (Osm.Xml.v0_6.tag xml_tag in xml_relation.tag)
                {
                    relation.Tags.Add(xml_tag.k, xml_tag.v);
                }
            }

            if (xml_relation.member != null)
            {
                relation.Members = new List<RelationMember>();
                foreach (Osm.Xml.v0_6.member xml_member in xml_relation.member)
                {
                    OsmGeoType? member_type = null;
                    switch (xml_member.type)
                    {
                        case memberType.node:
                            member_type = OsmGeoType.Node;
                            break;
                        case memberType.way:
                            member_type = OsmGeoType.Way;
                            break;
                        case memberType.relation:
                            member_type = OsmGeoType.Relation;
                            break;
                    }

                    relation.Members.Add(new RelationMember()
                    {
                        MemberId = xml_member.@ref,
                        MemberRole = xml_member.role,
                        MemberType = member_type
                    });
                }
            }

            relation.ChangeSetId = xml_relation.changeset;
            relation.TimeStamp = xml_relation.timestamp;
            relation.UserName = xml_relation.user;
            relation.UserId = xml_relation.uid;
            relation.Version = xml_relation.version;
            relation.Visible = xml_relation.visible;

            return relation;
        }
Beispiel #14
0
        /// <summary>
        /// Updates the given relation by adding it's changes to the current changeset.
        /// </summary>
        /// <param name="relation"></param>
        public void RelationUpdate(Relation relation)
        {
            if (_current_changeset == null)
            {
                throw new InvalidOperationException("No open changeset found!");
            }
            if (!relation.Id.HasValue)
            {
                throw new ArgumentOutOfRangeException("Cannot update an object without an id!");
            }

            // build a new node.
            relation xml_relation = relation.ConvertTo();
            xml_relation.changeset = _current_changeset.id;
            xml_relation.changesetSpecified = true;

            // encapsulate into an osm object.
            OsmSharp.Osm.Xml.v0_6.osm osm = new Osm.Xml.v0_6.osm();
            osm.relation = new Osm.Xml.v0_6.relation[1];
            osm.relation[0] = xml_relation;

            // serialize the changeset.
            XmlSerializer serializer = new XmlSerializer(typeof(OsmSharp.Osm.Xml.v0_6.osm));
            MemoryStream mem_stream = new MemoryStream();
            Stream stream = mem_stream;
            serializer.Serialize(stream, osm);
            stream.Flush();
            mem_stream.Flush();
            byte[] put_data = mem_stream.ToArray();

            // do the api call.
            this.DoApiCall(true, string.Format("api/0.6/relation/{0}", relation.Id.Value),
                Method.PUT, put_data);
        }
Beispiel #15
0
        /// <summary>
        /// Creates a new relation.
        /// </summary>
        /// <param name="relation"></param>
        /// <returns></returns>
        public Relation RelationCreate(Relation relation)
        {
            if (_current_changeset == null)
            {
                throw new InvalidOperationException("No open changeset found!");
            }

            // build a new node.
            relation xml_relation = relation.ConvertTo();
            xml_relation.changeset = _current_changeset.id;
            xml_relation.changesetSpecified = true;

            // encapsulate into an osm object.
            OsmSharp.Osm.Xml.v0_6.osm osm = new Osm.Xml.v0_6.osm();
            osm.relation = new Osm.Xml.v0_6.relation[1];
            osm.relation[0] = xml_relation;

            // serialize the changeset.
            XmlSerializer serializer = new XmlSerializer(typeof(OsmSharp.Osm.Xml.v0_6.osm));
            MemoryStream mem_stream = new MemoryStream();
            Stream stream = mem_stream;
            serializer.Serialize(stream, osm);
            stream.Flush();
            mem_stream.Flush();
            byte[] put_data = mem_stream.ToArray();

            // do the api call.
            string response_string = this.DoApiCall(true, "api/0.6/relation/create",
                Method.PUT, put_data);

            // get the id-response.
            long id;
            if (!long.TryParse(response_string, out id))
            { // invalid response!
                throw new APIException(string.Format("Invalid response when creating a new relation: {0}", response_string));
            }
            relation.Id = id;
            return relation;
        }
Beispiel #16
0
        /// <summary>
        /// Creates a new relation from a SimpleRelation.
        /// </summary>
        /// <param name="table"></param>
        /// <param name="simpleRelation"></param>
        /// <param name="nodes"></param>
        /// <param name="ways"></param>
        /// <param name="relations"></param>
        /// <returns></returns>
        public static CompleteRelation CreateFrom(ObjectTable <string> table, Relation simpleRelation,
                                                  IDictionary <long, CompleteNode> nodes,
                                                  IDictionary <long, CompleteWay> ways,
                                                  IDictionary <long, CompleteRelation> relations)
        {
            if (simpleRelation == null)
            {
                throw new ArgumentNullException("simpleRelation");
            }
            if (nodes == null)
            {
                throw new ArgumentNullException("nodes");
            }
            if (ways == null)
            {
                throw new ArgumentNullException("ways");
            }
            if (relations == null)
            {
                throw new ArgumentNullException("relations");
            }
            if (simpleRelation.Id == null)
            {
                throw new Exception("simpleRelation.Id is null");
            }

            CompleteRelation relation = Create(table, simpleRelation.Id.Value);

            relation.ChangeSetId = simpleRelation.ChangeSetId;
            foreach (Tag pair in simpleRelation.Tags)
            {
                relation.Tags.Add(pair);
            }
            for (int idx = 0; idx < simpleRelation.Members.Count; idx++)
            {
                long   memberId = simpleRelation.Members[idx].MemberId.Value;
                string role     = simpleRelation.Members[idx].MemberRole;

                var member = new CompleteRelationMember();
                member.Role = role;
                switch (simpleRelation.Members[idx].MemberType.Value)
                {
                case OsmGeoType.Node:
                    CompleteNode node = null;
                    if (nodes.TryGetValue(memberId, out node))
                    {
                        member.Member = node;
                    }
                    else
                    {
                        return(null);
                    }
                    break;

                case OsmGeoType.Way:
                    CompleteWay way = null;
                    if (ways.TryGetValue(memberId, out way))
                    {
                        member.Member = way;
                    }
                    else
                    {
                        return(null);
                    }
                    break;

                case OsmGeoType.Relation:
                    CompleteRelation relationMember = null;
                    if (relations.TryGetValue(memberId, out relationMember))
                    {
                        member.Member = relationMember;
                    }
                    else
                    {
                        return(null);
                    }
                    break;
                }
                relation.Members.Add(member);
            }
            relation.TimeStamp = simpleRelation.TimeStamp;
            relation.User      = simpleRelation.UserName;
            relation.UserId    = simpleRelation.UserId;
            relation.Version   = simpleRelation.Version.HasValue ? (long)simpleRelation.Version.Value : (long?)null;
            relation.Visible   = simpleRelation.Visible.HasValue && simpleRelation.Visible.Value;

            return(relation);
        }
Beispiel #17
0
        public void APITestRelationCreateGet()
        {
            // intialize the connection.
            var apiInstance = new APIConnection("http://api06.dev.openstreetmap.org/",
                "osmsharp", "osmsharp");

            // open a changeset.
            long changesetId = apiInstance.ChangeSetOpen("Simple Relation Creation Test");

            // initialize the relation.
            var relation = new Relation();
            relation.Tags = new TagsCollection();
            relation.Tags.Add("type", "testrelation");
            relation.Members = new List<RelationMember>();
            relation.Visible = true;

            // initialize the nodes.
            var node = new Node();
            node.Latitude = -0.494497;
            node.Longitude = -24.119325;
            node.Tags = new TagsCollection();
            node.Tags.Add("type", "testnode1");
            node.Visible = true;
            node = apiInstance.NodeCreate(node);
            relation.Members.Add(new RelationMember()
            {
                MemberId = node.Id.Value,
                MemberRole = "some_nodes_role",
                MemberType = OsmGeoType.Node
            });
            node = new Node();
            node.Latitude = -0.494497 + 0.0001f;
            node.Longitude = -24.119325 + 0.0001f;
            node.Tags = new TagsCollection();
            node.Tags.Add("type", "testnode2");
            node.Visible = true;
            node = apiInstance.NodeCreate(node);
            relation.Members.Add(new RelationMember()
            {
                MemberId = node.Id.Value,
                MemberRole = "some_nodes_role",
                MemberType = OsmGeoType.Node
            });

            // save the relation.
            relation = apiInstance.RelationCreate(relation);

            // close the changeset.
            apiInstance.ChangeSetClose();

            // check if the id now has a value.
            Assert.IsTrue(relation.Id.HasValue);

            // get the new relation id.
            long relationId = relation.Id.Value;

            // get the relation from the api.
            Relation relationAPI = apiInstance.RelationGet(relation.Id.Value);
            Assert.AreEqual(relationId, relationAPI.Id.Value);
            Assert.AreEqual(relation.Tags.Count, relationAPI.Tags.Count);
            Assert.AreEqual(relation.Visible, relationAPI.Visible);
            Assert.IsTrue(relationAPI.ChangeSetId.HasValue);
            Assert.AreEqual(changesetId, relationAPI.ChangeSetId.Value);
            Assert.AreEqual(relation.Members[0].MemberId, relationAPI.Members[0].MemberId);
            Assert.AreEqual(relation.Members[0].MemberRole, relationAPI.Members[0].MemberRole);
            Assert.AreEqual(relation.Members[0].MemberType, relationAPI.Members[0].MemberType);
            Assert.AreEqual(relation.Members[1].MemberId, relationAPI.Members[1].MemberId);
            Assert.AreEqual(relation.Members[1].MemberRole, relationAPI.Members[1].MemberRole);
            Assert.AreEqual(relation.Members[1].MemberType, relationAPI.Members[1].MemberType);
        }
Beispiel #18
0
 private void RelationCachePut(Relation relation)
 {
     _relations.Add(relation.Id, relation);
 }
Beispiel #19
0
        public void APITestRelationCreateGetUpdate()
        {
            // intialize the connection.
            var apiInstance = new APIConnection("http://api06.dev.openstreetmap.org/",
                "osmsharp", "osmsharp");

            // open a changeset.
            apiInstance.ChangeSetOpen("Simple Relation Creation Test");

            // initialize the relation.
            var relation = new Relation();
            relation.Tags = new TagsCollection();
            relation.Tags.Add("type", "testrelation");
            relation.Members = new List<RelationMember>();
            relation.Visible = true;

            // initialize the nodes.
            var node = new Node();
            node.Latitude = -0.494497;
            node.Longitude = -24.119325;
            node.Tags = new TagsCollection();
            node.Tags.Add("type", "testnode1");
            node.Visible = true;
            node = apiInstance.NodeCreate(node);
            relation.Members.Add(new RelationMember()
            {
                MemberId = node.Id.Value,
                MemberRole = "some_nodes_role",
                MemberType = OsmGeoType.Node
            });
            node = new Node();
            node.Latitude = -0.494497 + 0.0001f;
            node.Longitude = -24.119325 + 0.0001f;
            node.Tags = new TagsCollection();
            node.Tags.Add("type", "testnode2");
            node.Visible = true;
            node = apiInstance.NodeCreate(node);
            relation.Members.Add(new RelationMember()
            {
                MemberId = node.Id.Value,
                MemberRole = "some_nodes_role",
                MemberType = OsmGeoType.Node
            });

            // save the relation.
            relation = apiInstance.RelationCreate(relation);

            // close the changeset.
            apiInstance.ChangeSetClose();

            // check if the id now has a value.
            Assert.IsTrue(relation.Id.HasValue);

            // get the new relation id.
            long relationId = relation.Id.Value;

            // open new changeset.
            apiInstance.ChangeSetOpen("Simple Relation Update Test");

            // get the relation.
            Relation apiRelation = apiInstance.RelationGet(relation.Id.Value);
            apiRelation.Tags.Add("another_tag", "test adding a tag!");
            apiInstance.RelationUpdate(apiRelation);

            // close the current changeset.
            apiInstance.ChangeSetClose();

            // get the api relation.
            apiRelation = apiInstance.RelationGet(relation.Id.Value);

            Assert.AreEqual(2, apiRelation.Tags.Count);
            Assert.IsTrue(apiRelation.Tags.ContainsKey("another_tag"));
            Assert.AreEqual("test adding a tag!", apiRelation.Tags["another_tag"]);
        }
        /// <summary>
        /// Converts the given relation to a redis relation.
        /// </summary>
        /// <param name="relation"></param>
        /// <returns></returns>
        public static RedisRelation ConvertTo(Relation relation)
        {
            RedisRelation redisWay = new RedisRelation();
            redisWay.Id = relation.Id.Value;
            redisWay.ChangeSetId = relation.ChangeSetId;
            redisWay.TimeStamp = relation.TimeStamp;
            redisWay.UserId = relation.UserId;
            redisWay.UserName = relation.UserName;
            redisWay.Version = relation.Version;
            redisWay.Visible = relation.Visible;
            redisWay.Tags = PrimitiveExtensions.ConvertTo(relation.Tags);
            redisWay.Members = PrimitiveExtensions.ConvertTo(relation.Members);

            return redisWay;
        }
        /// <summary>
        /// Creates a relation from a SimpleRelation.
        /// </summary>
        /// <param name="simpleRelation"></param>
        /// <param name="cache"></param>
        /// <returns></returns>
        public static CompleteRelation CreateFrom(Relation simpleRelation, IDataSourceReadOnly cache)
        {
            if (simpleRelation == null)
            {
                throw new ArgumentNullException("simpleRelation");
            }
            if (cache == null)
            {
                throw new ArgumentNullException("cache");
            }
            if (simpleRelation.Id == null)
            {
                throw new Exception("simpleRelation.Id is null");
            }

            CompleteRelation relation = Create(simpleRelation.Id.Value);

            relation.ChangeSetId = simpleRelation.ChangeSetId;
            foreach (Tag pair in simpleRelation.Tags)
            {
                relation.Tags.Add(pair);
            }
            for (int idx = 0; idx < simpleRelation.Members.Count; idx++)
            {
                long   memberId = simpleRelation.Members[idx].MemberId.Value;
                string role     = simpleRelation.Members[idx].MemberRole;

                var member = new CompleteRelationMember();
                member.Role = role;
                switch (simpleRelation.Members[idx].MemberType.Value)
                {
                case OsmGeoType.Node:
                    Node simpleNode = cache.GetNode(memberId);
                    if (simpleNode != null)
                    {
                        member.Member = CompleteNode.CreateFrom(simpleNode);
                    }
                    else
                    {
                        return(null);
                    }
                    break;

                case OsmGeoType.Way:
                    Way simpleWay = cache.GetWay(memberId);
                    if (simpleWay != null)
                    {
                        member.Member = CompleteWay.CreateFrom(simpleWay, cache);
                    }
                    else
                    {
                        return(null);
                    }
                    break;

                case OsmGeoType.Relation:
                    Relation simpleRelationMember = cache.GetRelation(memberId);
                    if (simpleRelationMember != null)
                    {
                        member.Member = CompleteRelation.CreateFrom(simpleRelationMember, cache);
                    }
                    else
                    {
                        return(null);
                    }
                    break;
                }
                relation.Members.Add(member);
            }
            relation.TimeStamp = simpleRelation.TimeStamp;
            relation.User      = simpleRelation.UserName;
            relation.UserId    = simpleRelation.UserId;
            relation.Version   = simpleRelation.Version.HasValue ? (long)simpleRelation.Version.Value : (long?)null;
            relation.Visible   = simpleRelation.Visible.HasValue && simpleRelation.Visible.Value;

            return(relation);
        }
Beispiel #22
0
        public void APITestRelationCreateGetDelete()
        {
            // intialize the connection.
            var apiInstance = new APIConnection("http://api06.dev.openstreetmap.org/",
                "osmsharp", "osmsharp");

            // open a changeset.
            apiInstance.ChangeSetOpen("Simple Relation Creation Test");

            // initialize the relation.
            var relation = new Relation();
            relation.Tags = new TagsCollection();
            relation.Tags.Add("type", "testrelation");
            relation.Members = new List<RelationMember>();
            relation.Visible = true;

            // initialize the nodes.
            var node = new Node();
            node.Latitude = -0.494497;
            node.Longitude = -24.119325;
            node.Tags = new TagsCollection();
            node.Tags.Add("type", "testnode1");
            node.Visible = true;
            node = apiInstance.NodeCreate(node);
            relation.Members.Add(new RelationMember()
            {
                MemberId = node.Id.Value,
                MemberRole = "some_nodes_role",
                MemberType = OsmGeoType.Node
            });
            node = new Node();
            node.Latitude = -0.494497 + 0.0001f;
            node.Longitude = -24.119325 + 0.0001f;
            node.Tags = new TagsCollection();
            node.Tags.Add("type", "testnode2");
            node.Visible = true;
            node = apiInstance.NodeCreate(node);
            relation.Members.Add(new RelationMember()
            {
                MemberId = node.Id.Value,
                MemberRole = "some_nodes_role",
                MemberType = OsmGeoType.Node
            });

            // save the relation.
            relation = apiInstance.RelationCreate(relation);

            // close the changeset.
            apiInstance.ChangeSetClose();

            // check if the id now has a value.
            Assert.IsTrue(relation.Id.HasValue);

            // get the new relation id.
            long relationId = relation.Id.Value;

            // get the relation again: a relation can only be deleted using the correct changesetid and version.
            relation = apiInstance.RelationGet(relation.Id.Value);

            // open new changeset.
            apiInstance.ChangeSetOpen("Simple Relation Delete Test");

            // get the relation.
            apiInstance.RelationDelete(relation);

            // close the current changeset.
            apiInstance.ChangeSetClose();

            // get the relation.
            Relation apiRelation = apiInstance.RelationGet(relation.Id.Value);
            Assert.IsNull(apiRelation);
        }
 /// <summary>
 /// Returns false if this mapcss interpreter does not contain an interpretation for a relation with the given tags.
 /// </summary>
 /// <param name="relation"></param>
 /// <returns></returns>
 private bool AppliesToRelation(Relation relation)
 {
     List<MapCSSRuleProperties> rules = this.BuildRules(new MapCSSObject(relation));
     return rules != null && rules.Count > 0;
 }
        private void Create(Relation relation)
        {
            OracleCommand command;
            DateTime? timestamp = relation.TimeStamp;
            string timestamp_str = timestamp.Value.ToString("HH:mm dd/MM/yyyy");

            command = this.CreateCommand(string.Format(
                "insert into relation (id,changeset_id,timestamp,visible,version,usr,usr_id) values (:id,:changeset_id,to_date('{0}','HH24:MI DD/MM/YYYY'),:visible,:version,:usr,:usr_id)",
                timestamp_str));

            // format data and create parameters.
            long? id = relation.Id;
            command.Parameters.Add(new OracleParameter("id", id.ConvertToDBValue<long>()));

            long? changeset_id = relation.ChangeSetId;
            command.Parameters.Add(new OracleParameter("changeset_id", changeset_id.ConvertToDBValue<long>()));

            bool? visible = relation.Visible;
            int visible_int = 1;
            if (!visible.HasValue)
            {
                visible_int = 0;
            }
            command.Parameters.Add(new OracleParameter("visible", visible_int));

            long? version = (long)relation.Version;
            command.Parameters.Add(new OracleParameter("version", version.ConvertToDBValue<long>()));

            command.Parameters.Add("usr", relation.UserName);
            command.Parameters.Add("usr_id", relation.UserId);

            command.ExecuteNonQuery();
            command.Dispose();

            // insert tags.
            this.CreateTags(relation.Id.Value, relation.Tags, "relation_tags", "relation_id");

            // insert members.
            this.CreateRelationMembers(relation.Id.Value, relation.Members);
        }
 /// <summary>
 /// Adds a new relation.
 /// </summary>
 /// <param name="simpleRelation"></param>
 public override void AddRelation(Relation simpleRelation)
 {
     _graphTarget.AddRelation(simpleRelation);
 }
        private void Modify(Relation relation)
        {
            OracleCommand command;
            string sql = string.Empty;

            DateTime? timestamp = relation.TimeStamp;
            if (timestamp.HasValue)
            {
                sql = "update relation set changeset_id=:changeset_id,visible=:visible,timestamp=to_date('{0}','YYYY/MM/DD HH24:MI'),version=:version, usr=:usr, usr_id=:usr_id where id = :id";
                sql = string.Format(sql, timestamp.Value.ToString("yyyy/MM/dd HH:mm"));
            }
            else
            {
                sql = "update relation set changeset_id=:changeset_id,visible=:visible,timestamp=null,version=:version, usr_id=:usr_id where id = :id";
            }
            command = this.CreateCommand(sql);

            // format data and create parameters.
            long? changeset_id = relation.ChangeSetId;
            command.Parameters.Add(new OracleParameter("changeset_id", changeset_id.ConvertToDBValue<long>()));

            bool? visible = relation.Visible;
            int visible_int = 1;
            if (!visible.HasValue || !visible.Value)
            {
                visible_int = 0;
            }
            command.Parameters.Add("visible", visible_int);

            long? version = (long)relation.Version;
            command.Parameters.Add(new OracleParameter("version", version.ConvertToDBValue<long>()));

            command.Parameters.Add("usr", relation.UserName);
            command.Parameters.Add("usr_id", relation.UserId);

            long? id = relation.Id;
            command.Parameters.Add(new OracleParameter("id", id.ConvertToDBValue<long>()));

            command.ExecuteNonQuery();
            command.Dispose();

            if (this.Exists("relation",id.Value))
            {
                // update tags.
                this.ModifyTags(relation.Id.Value, relation.Tags, "relation_tags", "relation_id");

                // update members
                this.ModifyRelationMembers(relation.Id.Value, relation.Members);
            }

            // raise the modified event.
            this.RaiseChange(ChangeType.Modify, OsmGeoType.Relation, relation.Id.Value);
        }
        /// <summary>
        /// Adds a relation.
        /// </summary>
        /// <param name="relation">The relation to add to the SQLite DB</param>
        public override void AddRelation(Relation relation)
        {
            // if the relation passes the geo filter or is a dependency for another feature
            if (_geo_filter.Evaluate(relation) || _required_relations.Contains(relation.Id.Value))
            {
                if (_cached_relations.Count == RelationBatchCount)
                {
                    BatchAddRelations(_cached_relations, _replaceRelationBatchCommand);
                }

                _cached_relations.Add(relation);

                AddTags(relation, _unique_relation_tags, _cached_relation_tags);
                AddRelationMembers(relation);
            }
        }
Beispiel #28
0
 /// <summary>
 /// Adds the member-relation for the given relation.
 /// </summary>
 /// <param name="relation"></param>
 private void RegisterRelationMemberRelation(Relation relation)
 {
     foreach (RelationMember member in relation.Members)
     {
         if (!_relations_per_member.ContainsKey(member.Member.Id))
         {
             _relations_per_member.Add(member.Member.Id, new List<long>());
         }
         _relations_per_member[member.Member.Id].Add(relation.Id);
     }
 }
        private void AddRelationMembers(Relation relation)
        {
            if (relation.Members != null)
            {
                long? sequence_id = 0;
                foreach (var relation_member in relation.Members)
                {
                    if(relation_member.MemberId.HasValue && relation_member.MemberType.HasValue)
                    {
                        CacheDependency(relation_member);

                        if (_cached_relation_members.Count == RelationMembersBatchCount)
                        {
                            BatchAddRelationMembers(_cached_relation_members, _replaceRelationMembersBatchCommand);
                        }

                        _cached_relation_members.Add(new Tuple<long?, RelationMember, long?>(relation.Id, relation_member, sequence_id));
                        ++sequence_id;
                    }
                }
            }
        }
        /// <summary>
        /// Compares a found relation to an expected relation.
        /// </summary>
        public static void CompareSimple(Relation expected, Relation actual)
        {
            Assert.IsNotNull(expected);
            Assert.IsNotNull(actual);
            Assert.AreEqual(expected.Id, actual.Id);
            Assert.AreEqual(expected.ChangeSetId, actual.ChangeSetId);
            Assert.AreEqual(expected.TimeStamp, actual.TimeStamp);
            Assert.AreEqual(expected.Type, actual.Type);
            Assert.AreEqual(expected.UserId, actual.UserId);
            Assert.AreEqual(expected.UserName, actual.UserName);
            Assert.AreEqual(expected.Version, actual.Version);
            Assert.AreEqual(expected.Visible, actual.Visible);

            if (expected.Members == null)
            {
                Assert.IsNull(actual.Members);
            }
            else
            {
                Assert.IsNotNull(actual.Members);
                Assert.AreEqual(expected.Members.Count, actual.Members.Count);
                for (int idx = 0; idx < expected.Members.Count; idx++)
                {
                    Assert.AreEqual(expected.Members[idx].MemberId, actual.Members[idx].MemberId);
                    // the oracle database converts empty strings to null and does not follow standards.
                    // this is why there is this ugly code here matching empty strings to null.
                    if (expected.Members[idx].MemberRole == string.Empty &&
                        actual.Members[idx].MemberRole == null)
                    { // only for oracle!
                        Assert.AreEqual(null, actual.Members[idx].MemberRole);
                    }
                    else
                    {
                        Assert.AreEqual(expected.Members[idx].MemberRole, actual.Members[idx].MemberRole);
                    }
                    Assert.AreEqual(expected.Members[idx].MemberType, actual.Members[idx].MemberType);
                }
            }

            ComparisonHelpers.CompareTags(expected.Tags, actual.Tags);
        }
        /// <summary>
        /// Adds a relation.
        /// </summary>
        /// <param name="relation"></param>
        public void AddRelation(Relation relation)
        {
            if (relation == null) throw new ArgumentNullException();
            if (!relation.Id.HasValue) throw new ArgumentException("Relations without a valid id cannot be saved!");

            _relations[relation.Id.Value] = relation;

            if (relation.Members != null)
            {
                foreach (var member in relation.Members)
                {
                    HashSet<long> relationsIds = null;
                    switch(member.MemberType.Value)
                    {
                        case OsmGeoType.Node:
                            if (!_relationsPerNode.TryGetValue(member.MemberId.Value, out relationsIds))
                            {
                                relationsIds = new HashSet<long>();
                                _relationsPerNode.Add(member.MemberId.Value, relationsIds);
                            }
                            break;
                        case OsmGeoType.Way:
                            if (!_relationsPerWay.TryGetValue(member.MemberId.Value, out relationsIds))
                            {
                                relationsIds = new HashSet<long>();
                                _relationsPerWay.Add(member.MemberId.Value, relationsIds);
                            }
                            break;
                        case OsmGeoType.Relation:
                            if (!_relationsPerRelation.TryGetValue(member.MemberId.Value, out relationsIds))
                            {
                                relationsIds = new HashSet<long>();
                                _relationsPerRelation.Add(member.MemberId.Value, relationsIds);
                            }
                            break;
                    }
                    relationsIds.Add(relation.Id.Value);
                }
            }
        }
        /// <summary>
        /// Compares a found relation to an expected relation.
        /// </summary>
        /// <param name="expected"></param>
        /// <param name="found"></param>
        private void CompareRelations(Relation expected, Relation found)
        {
            Assert.IsNotNull(expected);
            Assert.IsNotNull(found);
            Assert.AreEqual(expected.Id, found.Id);
            Assert.AreEqual(expected.ChangeSetId, found.ChangeSetId);
            Assert.AreEqual(expected.TimeStamp, found.TimeStamp);
            Assert.AreEqual(expected.Type, found.Type);
            Assert.AreEqual(expected.UserId, found.UserId);
            Assert.AreEqual(expected.UserName, found.UserName);
            Assert.AreEqual(expected.Version, found.Version);
            Assert.AreEqual(expected.Visible, found.Visible);

            if (expected.Members == null)
            {
                Assert.IsNull(found.Members);
            }
            else
            {
                Assert.IsNotNull(found.Members);
                Assert.AreEqual(expected.Members.Count, found.Members.Count);
                for (int idx = 0; idx < expected.Members.Count; idx++)
                {
                    Assert.AreEqual(expected.Members[idx].MemberId, found.Members[idx].MemberId);
                    // the oracle database converts empty strings to null and does not follow standards.
                    // this is why there is this ugly code here matching empty strings to null.
                    if (expected.Members[idx].MemberRole == string.Empty &&
                        found.Members[idx].MemberRole == null)
                    { // only for oracle!
                        Assert.AreEqual(null, found.Members[idx].MemberRole);
                    }
                    else
                    {
                        Assert.AreEqual(expected.Members[idx].MemberRole, found.Members[idx].MemberRole);
                    }
                    Assert.AreEqual(expected.Members[idx].MemberType, found.Members[idx].MemberType);
                }
            }

            this.CompareTags(expected.Tags, found.Tags);
        }
Beispiel #33
0
 /// <summary>
 /// Adds a relation.
 /// </summary>
 /// <param name="relation"></param>
 public void AddRelation(Relation relation)
 {
     _relations[relation.Id] = relation;
 }
        private bool DoMoveNextRelation()
        {
            if (_relation_reader == null)
            {
                var relationCommand = new SQLiteCommand("select * from relation order by id", _connection);
                _relation_reader = relationCommand.ExecuteReader();
                if (!_relation_reader.Read())
                {
                    _relation_reader.Close();
                }
                var relationTagCommand = new SQLiteCommand("select * from relation_tags order by relation_id", _connection);
                _relation_tag_reader = relationTagCommand.ExecuteReader();
                if (!_relation_tag_reader.IsClosed && !_relation_tag_reader.Read())
                {
                    _relation_tag_reader.Close();
                }
                var relationNodeCommand = new SQLiteCommand("select * from relation_members order by relation_id,sequence_id", _connection);
                _relation_member_reader = relationNodeCommand.ExecuteReader();
                if (!_relation_member_reader.IsClosed && !_relation_member_reader.Read())
                {
                    _relation_member_reader.Close();
                }
            }

            // read next relation.
            if (!_relation_reader.IsClosed)
            {
                // load/parse data.
                long id = _relation_reader.GetInt64(0);
                long changesetId = _relation_reader.GetInt64(1);
                bool visible = _relation_reader.GetInt64(2) == 1;
                DateTime timestamp = _relation_reader.IsDBNull(3) ? DateTime.MinValue : _relation_reader.GetDateTime(3);
                long version = _relation_reader.GetInt64(4);
                string user = _relation_reader.GetString(5);
                long uid = _relation_reader.GetInt64(6);
                var relation = new Relation
                {
                    Id = id,
                    ChangeSetId = changesetId,
                    TimeStamp = timestamp,
                    UserId = null,
                    UserName = null,
                    Version = (ulong)version,
                    Visible = visible
                };
                relation.UserName = user;
                relation.UserId = uid;

                if (!_relation_tag_reader.IsClosed)
                {
                    long returnedId = _relation_tag_reader.GetInt64(0);
                    while (returnedId == relation.Id.Value)
                    {
                        if (relation.Tags == null)
                        {
                            relation.Tags = new TagsCollection();
                        }
                        string key = _relation_tag_reader.GetString(1);
                        string value = _relation_tag_reader.GetString(2);

                        relation.Tags.Add(key, value);

                        if (!_relation_tag_reader.Read())
                        {
                            _relation_tag_reader.Close();
                            returnedId = -1;
                        }
                        else
                        {
                            returnedId = _relation_tag_reader.GetInt64(0);
                        }
                    }
                }
                if (!_relation_member_reader.IsClosed)
                {
                    long returnedId = _relation_member_reader.GetInt64(0);
                    while (returnedId == relation.Id.Value)
                    {
                        if (relation.Members == null)
                        {
                            relation.Members = new List<RelationMember>();
                        }
                        string memberType = _relation_member_reader.GetString(1);
                        long memberId = _relation_member_reader.GetInt64(2);
                        object memberRole = _relation_member_reader.GetValue(3);

                        var member = new RelationMember();
                        member.MemberId = memberId;
                        if (memberRole != DBNull.Value)
                        {
                            member.MemberRole = memberRole as string;
                        }
                        switch (memberType)
                        {
                            case "Node":
                                member.MemberType = OsmGeoType.Node;
                                break;
                            case "Way":
                                member.MemberType = OsmGeoType.Way;
                                break;
                            case "Relation":
                                member.MemberType = OsmGeoType.Relation;
                                break;
                        }

                        relation.Members.Add(member);

                        if (!_relation_member_reader.Read())
                        {
                            _relation_member_reader.Close();
                            returnedId = -1;
                        }
                        else
                        {
                            returnedId = _relation_member_reader.GetInt64(0);
                        }
                    }
                }

                // set the current variable!
                _current = relation;

                // advance the reader(s).
                if (!_relation_reader.Read())
                {
                    _relation_reader.Close();
                }
                if (!_relation_tag_reader.IsClosed && !_relation_tag_reader.Read())
                {
                    _relation_tag_reader.Close();
                }
                if (!_relation_member_reader.IsClosed && !_relation_member_reader.Read())
                {
                    _relation_member_reader.Close();
                }
                return true;
            }
            else
            {
                _relation_reader.Close();
                _relation_reader.Dispose();
                _relation_reader = null;

                _relation_tag_reader.Close();
                _relation_tag_reader.Dispose();
                _relation_tag_reader = null;

                _current_type = OsmGeoType.Relation;

                return false;
            }
        }
Beispiel #35
0
        /// <summary>
        /// Creates a relation from a SimpleRelation.
        /// </summary>
        /// <returns></returns>
        public static CompleteRelation CreateFrom(Relation simpleRelation, IOsmGeoSource osmGeoSource)
        {
            if (simpleRelation == null)
            {
                throw new ArgumentNullException("simpleRelation");
            }
            if (osmGeoSource == null)
            {
                throw new ArgumentNullException("osmGeoSource");
            }
            if (simpleRelation.Id == null)
            {
                throw new Exception("simpleRelation.Id is null");
            }

            var relation = Create(simpleRelation.Id.Value);

            relation.ChangeSetId = simpleRelation.ChangeSetId;
            if (simpleRelation.Tags != null)
            {
                foreach (var pair in simpleRelation.Tags)
                {
                    relation.Tags.Add(pair);
                }
            }
            if (simpleRelation.Members != null)
            {
                for (var idx = 0; idx < simpleRelation.Members.Count; idx++)
                {
                    var memberId = simpleRelation.Members[idx].MemberId.Value;
                    var role     = simpleRelation.Members[idx].MemberRole;
                    var member   = new CompleteRelationMember();
                    member.Role = role;
                    switch (simpleRelation.Members[idx].MemberType.Value)
                    {
                    case OsmGeoType.Node:
                        var simpleNode = osmGeoSource.GetNode(memberId);
                        if (simpleNode == null)
                        {
                            return(null);
                        }
                        var completeNode = simpleNode;
                        if (completeNode != null)
                        {
                            member.Member = completeNode;
                        }
                        else
                        {
                            return(null);
                        }
                        break;

                    case OsmGeoType.Way:
                        var simpleWay = osmGeoSource.GetWay(memberId);
                        if (simpleWay == null)
                        {
                            return(null);
                        }
                        var completeWay = CompleteWay.CreateFrom(simpleWay, osmGeoSource);
                        if (completeWay != null)
                        {
                            member.Member = completeWay;
                        }
                        else
                        {
                            return(null);
                        }
                        break;

                    case OsmGeoType.Relation:
                        var simpleRelationMember = osmGeoSource.GetRelation(memberId);
                        if (simpleRelationMember == null)
                        {
                            return(null);
                        }
                        var completeRelation = CompleteRelation.CreateFrom(simpleRelationMember, osmGeoSource);
                        if (completeRelation != null)
                        {
                            member.Member = completeRelation;
                        }
                        else
                        {
                            return(null);
                        }
                        break;
                    }
                    relation.Members.Add(member);
                }
            }
            relation.TimeStamp = simpleRelation.TimeStamp;
            relation.User      = simpleRelation.UserName;
            relation.UserId    = simpleRelation.UserId;
            relation.Version   = simpleRelation.Version.HasValue ? (long)simpleRelation.Version.Value : (long?)null;
            relation.Visible   = simpleRelation.Visible.HasValue && simpleRelation.Visible.Value;
            return(relation);
        }