public void ValidateUVID(string messageId, string messageRTZ)
        {
            if (!string.IsNullOrEmpty(messageRTZ))
            {
                var    parser    = RtzParserFactory.Create(messageRTZ);
                string routeInfo = parser.RouteInfo;
                if (routeInfo == null)
                {
                    throw new StmSchemaValidationException("Could not read routeInfo from RTZ message.");
                }

                string vesselVoyage = parser.VesselVoyage;
                if (vesselVoyage == null)
                {
                    throw new StmSchemaValidationException("Could not read uvid from RTZ message.");
                }

                if (vesselVoyage.ToLower() != messageId.ToLower())
                {
                    throw new StmSchemaValidationException(string.Format("Inconsistent UVID: UVID in argument = {0} must be equal UVID in RTZ = {1}.",
                                                                         messageId, vesselVoyage));
                }
            }
            else
            {
                throw new StmSchemaValidationException("Could not read UVID from RTZ message.");
            }
        }
예제 #2
0
        public void TestRTZMessageWithOkRouteStatus()
        {
            byte[] msg         = GetMessageRaw(@"STMMessageSamples\msg1_RouteStatus_7.rtz");
            var    msgString   = Serialization.ByteArrayToString(msg);
            var    parser      = RtzParserFactory.Create(msgString);
            string routeStatus = parser.RouteStatus;

            Assert.AreEqual <string>("7", routeStatus);
        }
예제 #3
0
        public void TestRTZMessageMissingRouteStatus()
        {
            byte[] msg         = GetMessageRaw(@"STMMessageSamples\msg1_missingRouteStatus.rtz");
            var    msgString   = Serialization.ByteArrayToString(msg);
            var    parser      = RtzParserFactory.Create(msgString);
            string routeStatus = parser.RouteStatus;

            Assert.AreEqual(routeStatus, string.Empty);
        }
예제 #4
0
        public void TestRTZ_2_0()
        {
            byte[] msg       = GetMessageRaw(@"STMMessageSamples\RTZ v1.0 STM several extensions-1.rtz");
            var    msgString = Serialization.ByteArrayToString(msg);

            var    parser = RtzParserFactory.Create(msgString);
            string uvid   = parser.VesselVoyage;

            string routeStatus = parser.RouteStatus;

            //Assert.AreEqual("urn:mrn:stm:voyage:id:wallenius:0001", uvid);
        }
예제 #5
0
        public void Rtz10Parser()
        {
            byte[] msg       = GetMessageRaw(@"STMMessageSamples\RTZ v1.0 STM several extensions-1.rtz");
            var    msgString = Serialization.ByteArrayToString(msg);

            var validator = new StmSchemaValidator();

            validator.ValidateRTZMessageXML(msgString);

            var parser = RtzParserFactory.Create(msgString);
            var status = parser.RouteStatus;
        }
예제 #6
0
        public void TestRTZMessageInincosistentUVID()
        {
            byte[] msg       = GetMessageRaw(@"STMMessageSamples\msg1_invalidUVID.rtz");
            var    msgString = Serialization.ByteArrayToString(msg);
            var    parser    = RtzParserFactory.Create(msgString);
            string uvid      = parser.VesselVoyage;
            var    validator = new StmSchemaValidator();

            try
            {
                validator.ValidateUVID("urn:mrn:stm:voyage:id:vis1:0001", msgString);
            }
            catch (StmSchemaValidationException ex)
            {
                Assert.IsNotNull(ex);
            }
        }
        /// <summary>
        /// Validate all parts of a RTZ message
        /// </summary>
        /// <param name="msg"></param>
        public void ValidateRTZMessage(string msg)
        {
            // Reset
            valResult = "";

            if (msg == null)
            {
                throw new StmSchemaValidationException("STM message is null. Not a valid message.");
            }

            var parser = RtzParserFactory.Create(msg);

            if (string.IsNullOrEmpty(parser.RouteInfo) ||
                string.IsNullOrEmpty(parser.WayPoints))
            {
                throw new StmSchemaValidationException("Some or all parts of the STM message are null. Not a valid message.");
            }

            var rtz11parser = parser as Rtz11Parser;

            if (rtz11parser != null)
            {
                if (string.IsNullOrEmpty(rtz11parser.StmRouteInfoExtension))
                {
                    throw new StmSchemaValidationException("Missing STM route info extension");
                }
            }

            if (!string.IsNullOrEmpty(parser.RouteStatus))
            {
                int status = Convert.ToInt32(parser.RouteStatus);
                if (status < 1 || status > 8)
                {
                    throw new ArgumentOutOfRangeException("routeInfo.routeStatus", status, "Forbidden status value.");
                }
            }
            else
            {
                throw new ArgumentNullException("RouteStatusEnum in STM extension can not be null or empty", "Mandatory element is null.");
            }

            if (valResult != "")
            {
                throw new StmSchemaValidationException("Message from external does not validate ok. Details: " + valResult);
            }
        }
        private void CheckRouteStatus(string msg, string uvid)
        {
            try
            {
                var parser = RtzParserFactory.Create(msg);

                if (!string.IsNullOrEmpty(msg) &&
                    !string.IsNullOrEmpty(parser.RouteInfo) &&
                    !string.IsNullOrEmpty(parser.RouteStatus))
                {
                    int status = Convert.ToInt32(parser.RouteStatus);

                    // If there is already one item in status used for monitoring set the old one to status 8
                    if (status == (int)RouteStatus.Used_for_monitoring)
                    {
                        var storedMessage = _publishedMessageService.Get(m =>
                                                                         m.MessageStatus == RouteStatus.Used_for_monitoring && m.MessageID != uvid).FirstOrDefault();

                        if (storedMessage != null)
                        {
                            storedMessage.MessageStatus = RouteStatus.Inactive;
                            _publishedMessageService.SaveAndUpdate(storedMessage, false, true);
                        }
                    }
                }
                else
                {
                    throw CreateHttpResponseException(HttpStatusCode.BadRequest, "RouteStatusEnum in STM extension cannot be null or empty");
                }
            }
            catch (HttpResponseException)
            {
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);

                var error = "VIS internal server error. " + ex.Message;

                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, error);
            }
        }
        private void Populate(PublishedRtzMessage entity, bool ignoreStatusInMessage = false)
        {
            var msg = Serialization.ByteArrayToString(entity.Message);

            var parser            = RtzParserFactory.Create(msg);
            var routeStatusString = parser.RouteStatus;

            RouteStatus routeStatus = RouteStatus.Unknown;
            int         statusId;

            if (int.TryParse(routeStatusString, out statusId))
            {
                routeStatus = (RouteStatus)statusId;
            }

            if (!ignoreStatusInMessage)
            {
                entity.MessageStatus = (RouteStatus)statusId;
            }

            DateTime?validityPeriodStart = parser.ValidityPeriodStart;

            if (validityPeriodStart == DateTime.MinValue)
            {
                entity.MessageValidFrom = null;
            }
            else
            {
                entity.MessageValidFrom = validityPeriodStart;
            }
            DateTime?validityPeriodStop = parser.ValidityPeriodStop;

            if (validityPeriodStop == DateTime.MinValue)
            {
                entity.MessageValidTo = null;
            }
            else
            {
                entity.MessageValidTo = validityPeriodStop;
            }
        }
예제 #10
0
        private void SubmitMessageToVIS(byte[] msg)
        {
            PublishedRtzMessageService service = new PublishedRtzMessageService(_dbContext, _logContext);

            var messageType = _dbContext.MessageType.Where(m => m.Name == "RTZ").FirstOrDefault();
            //var parsedMsg = Serialization.Deserialize<Route>(Serialization.ByteArrayToString(msg));

            var         parser      = RtzParserFactory.Create(Serialization.ByteArrayToString(msg));
            string      routeStatus = parser.RouteStatus;
            RouteStatus status;

            if (string.IsNullOrEmpty(routeStatus))
            {
                status = RouteStatus.Unknown;
            }
            else
            {
                status = (RouteStatus)Enum.Parse(typeof(RouteStatus), routeStatus);
            }
            var entityToInsert = new PublishedRtzMessage
            {
                Message               = msg,
                MessageID             = "urn:mrn:stm:voyage:id:vis1:0001",
                MessageLastUpdateTime = DateTime.UtcNow,
                MessageStatus         = status,
                MessageType           = messageType,
                MessageValidFrom      = DateTime.UtcNow.AddDays(-3),
                MessageValidTo        = DateTime.UtcNow.AddDays(3),
                PublishTime           = DateTime.UtcNow.AddHours(-3)
            };

            try
            {
                service.Insert(entityToInsert);
                _dbContext.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }
        public virtual Models.ResponseObj UploadVoyagePlan([FromBody] string voyagePlan, [FromUri] string deliveryAckEndPoint = null,
                                                           [FromUri] string callbackEndpoint = null)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

            var messageType = _messageTypeService.Get(x => x.Name.ToLower() == "rtz").First();

            var request = Request;
            var headers = request.Headers;

            var paramList = new List <KeyValuePair <string, string> >();
            var param     = new KeyValuePair <string, string>("deliveryAckEndPoint", deliveryAckEndPoint);

            paramList.Add(param);
            param = new KeyValuePair <string, string>("callbackEndpoint", callbackEndpoint);
            paramList.Add(param);

            //First, validate that we have mandatory in-parameters
            var parser = RtzParserFactory.Create(voyagePlan);

            var uvid = parser.VesselVoyage;

            if (string.IsNullOrEmpty(uvid))
            {
                log.Debug("UVID is empty");

                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Required parameter UVID is missing.");
            }

            if (!FormatValidation.IsValidUvid(uvid))
            {
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Invalid UVID format");
            }

            if (voyagePlan == null)
            {
                log.Debug("VoyagePlan is empty");

                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Required parameter VoyagePlan is missing.");
            }

            try
            {
                if (string.IsNullOrEmpty(InstanceContext.CallerOrgId))
                {
                    log.Debug("Calling organization identity missing in header.");

                    throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Required header incomingOrganizationId is missing.");
                }

                //Write to log table
                _logEventService.LogInfo(EventNumber.VIS_uploadVoyagePlan_request, EventDataType.RTZ, paramList, voyagePlan);
                // Get identity ether from internal id talbe or from id registry
                var identity = _identityService.GetCallerIdentity();

                var result = new UploadedMessage();
                result.AckDelivered        = false;
                result.DeliveryAckEndpoint = deliveryAckEndPoint;
                result.DeliveryAckReqested = string.IsNullOrEmpty(deliveryAckEndPoint) ? false : true;
                result.FetchedByShip       = false;
                result.FetchTime           = null;
                result.FromOrg             = identity;
                result.FromServiceId       = InstanceContext.CallerServiceId;
                result.Message             = Serialization.StrToByteArray(voyagePlan);
                result.MessageType         = _messageTypeService.Get(x => x.Name.ToLower() == "rtz").First();
                result.Notified            = false;
                result.ReceiveTime         = DateTime.UtcNow;
                result.MessageID           = uvid;
                result.CallbackEndpoint    = string.IsNullOrEmpty(callbackEndpoint) ? string.Empty : callbackEndpoint;

                _uploadedMessageService.InsertRTZ(result);

                //Save to DB
                _context.SaveChanges();

                //Notify STM module
                var notification = new Common.Services.Internal.Interfaces.Notification();
                notification.FromOrgName        = identity.Name;
                notification.FromOrgId          = identity.UID;
                notification.FromServiceId      = InstanceContext.CallerServiceId;
                notification.NotificationType   = EnumNotificationType.MESSAGE_WAITING;
                notification.Subject            = "New voyageplan uploaded.";
                notification.NotificationSource = EnumNotificationSource.VIS;

                var notified = _notificationService.Notify(notification);

                if (notified)
                {
                    _context.Entry(result).Reload();
                    result.Notified = true;
                    _uploadedMessageService.Update(result);
                }

                var responsObj = new ResponseObj("Success store message");

                //Save to DB
                _context.SaveChanges();

                _logEventService.LogSuccess(EventNumber.VIS_uploadVoyagePlan_response, EventDataType.Other, null,
                                            JsonConvert.SerializeObject(responsObj, Formatting.Indented));

                return(responsObj);
            }

            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);
                _logEventService.LogError(EventNumber.VIS_uploadVoyagePlan_request, EventType.Error_internal, paramList,
                                          JsonConvert.SerializeObject(ex.Response, Formatting.Indented));
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                _logEventService.LogError(EventNumber.VIS_uploadVoyagePlan_request, EventType.Error_internal, paramList,
                                          ex.Message);

                string msg = "VIS internal server error. " + ex.Message;
                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
        public ResponseObj PublishMessage([FromUri] string dataId,
                                          [FromUri] string messageType,
                                          [FromBody] string message)
        {
            try
            {
                // Check incoming args
                if (!FormatValidation.IsValidUvid(dataId))
                {
                    throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Invalid UVID format."));
                }
                if (string.IsNullOrEmpty(dataId))
                {
                    throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Missing required parameter dataId."));
                }
                if (string.IsNullOrEmpty(messageType))
                {
                    throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Missing required parameter messageType."));
                }
                if (string.IsNullOrEmpty(message))
                {
                    throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Missing required parameter message."));
                }

                // Check if correct messageType e.g. only RTZ accepted
                var msgType = _messageTypeService.Get(m => m.Name == messageType).FirstOrDefault();
                if (msgType == null ||
                    string.IsNullOrEmpty(msgType.Name) ||
                    msgType.Name.ToLower() != "rtz")
                {
                    throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Unsupported or unknown message type."));
                }

                var messageToUpdate = _publishedMessageService.Get(m => m.MessageID == dataId).FirstOrDefault();

                var responsObj = new ResponseObj(dataId);

                CheckRouteStatus(message, dataId);

                if (messageToUpdate == null) //New message
                {
                    var newMessage = new PublishedRtzMessage();
                    newMessage.Message     = Serialization.StrToByteArray(message);
                    newMessage.MessageID   = dataId;
                    newMessage.MessageType = msgType;
                    newMessage.PublishTime = DateTime.UtcNow;

                    _publishedMessageService.Insert(newMessage);
                }
                else
                {
                    messageToUpdate.Message     = Serialization.StrToByteArray(message);
                    messageToUpdate.PublishTime = DateTime.UtcNow;

                    _publishedMessageService.Update(messageToUpdate);
                }

                //Notify subscribers if messageStatus not inactive
                var parser = RtzParserFactory.Create(message);

                string routeInfo   = parser.RouteInfo;
                string routeStatus = parser.RouteStatus;
                if (!string.IsNullOrEmpty(routeInfo) && !string.IsNullOrEmpty(routeStatus))
                {
                    _publishedMessageService.SendMessageToSubsribers(message, dataId);
                }

                SetLastInteractionTime();
                // Save to DB
                _context.SaveChanges();

                return(responsObj);
            }
            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);

                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);

                var errorMessage = "VIS internal server error. " + ex.Message;
                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, errorMessage);
            }
        }