コード例 #1
0
        public ErrorResultViewModel ComprobarErrores(RegistroViewModel registro)
        {
            this.errorResult.details = new List <string>();

            if (!FormatValidation.IsValidEmail(registro.Correo))
            {
                this.errorResult.details.Add("El email no tiene un formato valido");
            }

            if (!FormatValidation.IsValidPassword(registro.Contrasena))
            {
                this.errorResult.details.Add("La contraseña no tiene un formato valido");
            }

            if (!FormatValidation.IsValidPhone(registro.Telefono))
            {
                this.errorResult.details.Add("El telefono no tiene un formato valido");
            }

            if (this.errorResult.details.Count == 0)
            {
                return(null);
            }
            else
            {
                this.errorResult.message = "Han ocurrido errores al registrar el usuario";
                return(this.errorResult);
            }
        }
コード例 #2
0
ファイル: ContactSample.cs プロジェクト: devoft/Fluent-MVVM
        public static void Initialize()
        {
            RegisterProperty(x => x.FirstName)
            .Validate((t, v, vr) => vr.Error <NotNull>(v), notifyChangeOnValidationError: true)
            .Validate((t, v, vr) => vr.Error(string.IsNullOrWhiteSpace(v), "Name cannot be empty or whitespace"), notifyChangeOnValidationError: true)
            .Coerce(name => name.Trim(),
                    name => char.ToUpper(name[0]) + name.Substring(1).ToLower());

            RegisterProperty(x => x.LastName)
            .Validate((t, v, vr) => vr.Error(v != null && string.IsNullOrWhiteSpace(v), "LastName cannot be empty or whitespace"), notifyChangeOnValidationError: true)
            .Validate((t, v, vr) => vr.Warning(!FormatValidation.IsPersonName(v), "Last names are usually in the same format as first names"))
            .Coerce(name => name.Trim());

            RegisterProperty(x => x.FullName)
            .DependOn(nameof(FirstName), nameof(LastName))
            .Validate((t, v, vr) => vr.Error(string.IsNullOrWhiteSpace(v), "FullName cannot be empty or whitespace"));

            RegisterProperty(x => x.Age)
            .DependOn(x => x.Birthdate)
            .Validate((t, v, vr) => vr.Error(v < 0, "Age cannot be negative"));


            RegisterProperty(x => x.Email)
            .Validate((t, v, vr) => vr.Error(string.IsNullOrWhiteSpace(v), "Email cannot be empty or whitespace"), notifyChangeOnValidationError: true)
            .Validate((t, v, vr) => vr.Error(!FormatValidation.IsValidEmail(v), "Email is in invalid format"), notifyChangeOnValidationError: true)
            .Coerce(name => name.Trim());
        }
コード例 #3
0
        public IList <SubscriptionObject> GetSubscriptions([FromUri] string dataId = null)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

            if (!string.IsNullOrEmpty(dataId) && !FormatValidation.IsValidUvid(dataId))
            {
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Invalid UVID format");
            }

            try
            {
                // Find all ACL objects for specified MessageID
                IEnumerable <VisSubscription> subList;

                if (string.IsNullOrEmpty(dataId))
                {
                    subList = _subscriptionService.Get(includeProperties: "SubscriberIdentity");
                }
                else
                {
                    subList = _subscriptionService.Get(s => s.MessageID == dataId, includeProperties: "SubscriberIdentity");
                }

                // Create result list
                var response = new List <SubscriptionObject>();

                if (subList != null)
                {
                    foreach (var item in subList)
                    {
                        var subObj = new SubscriptionObject
                        {
                            EndpointURL  = new Uri(item.CallbackEndpoint),
                            IdentityId   = item.SubscriberIdentity.UID,
                            IdentityName = item.SubscriberIdentity.Name
                        };
                        response.Add(subObj);
                    }
                }
                SetLastInteractionTime();
                _context.SaveChanges();
                return(response);
            }
            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);

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

                string msg = "VIS internal server error. " + ex.Message;

                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
        public IList <IdentityDescriptionObject> FindAuthorizedIdentities([FromUri] string dataId)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

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

            if (string.IsNullOrEmpty(dataId))
            {
                var msg = "Missing required query parameter dataId.";
                log.Error(msg);
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, msg);
            }

            try
            {
                // Find all ACL objects for specified MessageID
                var aclList = _aclObjectService.Get(x =>
                                                    x.MessageID == dataId, includeProperties: "Subscriber");

                // Create result list
                var response = new List <IdentityDescriptionObject>();

                if (aclList != null)
                {
                    foreach (var item in aclList)
                    {
                        response.Add(new IdentityDescriptionObject(item.Subscriber.UID, item.Subscriber.Name));
                    }
                }

                SetLastInteractionTime();
                _context.SaveChanges();

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

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

                string msg = "VIS internal server error. " + ex.Message;

                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
コード例 #5
0
        public ResponseObj RemoveSubscriptions([FromUri] string dataId, [FromBody] List <SubscriptionObject> subscriptionObjects)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

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

            try
            {
                foreach (var subscriptionObject in subscriptionObjects)
                {
                    var identityToDelete = _identityService.Get(i => i.UID == subscriptionObject.IdentityId).FirstOrDefault();
                    if (identityToDelete == null)
                    {
                        log.Info(string.Format("Identity {0} did not exist for messageId {1}.", subscriptionObject.IdentityId, dataId));
                        return(new ResponseObj(dataId));
                    }

                    var url        = subscriptionObject.EndpointURL.ToString().ToLower();
                    var currentSub = _subscriptionService.Get(s => s.MessageID == dataId &&
                                                              s.SubscriberIdentity.UID == subscriptionObject.IdentityId &&
                                                              s.CallbackEndpoint.ToLower() == url).FirstOrDefault();

                    if (currentSub != null)
                    {
                        //Delete it
                        _subscriptionService.Delete(currentSub);
                        var msg = string.Format("Subscription removed for identity {0} on messageId {1}.", subscriptionObject.IdentityId, dataId);
                        log.Info(msg);
                    }
                }

                SetLastInteractionTime();
                _context.SaveChanges();
                return(new ResponseObj(dataId));
            }
            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);

                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                string msg = "VIS internal server error. " + ex.Message;
                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
        public ResponseObj AuthorizeIdentities([FromUri] string dataId,
                                               [FromBody] List <IdentityDescriptionObject> identityDescriptionObjects)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

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

            try
            {
                foreach (var identityObject in identityDescriptionObjects)
                {
                    // CHeck if the identity already exists in the local identity table
                    var identity = _identityService.Get(x => x.UID == identityObject.IdentityId).FirstOrDefault();

                    // If not add new identity
                    if (identity == null)
                    {
                        identity = new Identity
                        {
                            UID  = identityObject.IdentityId,
                            Name = identityObject.IdentityName
                        };

                        _identityService.Insert(identity);
                    }
                    ;

                    // Get ACL for identity and messageID
                    var current = _aclObjectService.Get(x
                                                        => x.MessageID == dataId && x.Subscriber.ID == identity.ID).FirstOrDefault();

                    // If not already exists add new ACL
                    if (current == null)
                    {
                        var acl = new ACLObject();
                        acl.MessageID      = dataId;
                        acl.LastUpdateTime = DateTime.UtcNow;
                        acl.Subscriber     = identity;
                        _aclObjectService.Insert(acl);
                    }

                    log.Info(string.Format("ACL added for identity {0} on messageId {1}", identity.Name, dataId));
                }

                SetLastInteractionTime();

                // Save to DB
                _context.SaveChanges();

                // Create response
                return(new ResponseObj(dataId));
            }
            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);

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

                string msg = "VIS internal server error. " + ex.Message;

                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
        public ResponseObj RemoveAuthorizedIdentitites([FromUri] string dataId,
                                                       [FromBody] List <IdentityDescriptionObject> identityDescriptionObjects)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

            if (dataId == null)
            {
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Missing UVID");
            }

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

            if (identityDescriptionObjects == null || identityDescriptionObjects.Count == 0)
            {
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "No identities to remove");
            }

            try
            {
                foreach (var identityDescriptionObject in identityDescriptionObjects)
                {
                    // Get matching ACL-object from DB
                    var identityToDelete = _identityService.Get(i => i.UID == identityDescriptionObject.IdentityId).FirstOrDefault();
                    if (identityToDelete == null)
                    {
                        log.Info(string.Format("Identity {0} did not exist for messageId {1}.", identityDescriptionObject.IdentityId, dataId));
                        return(new ResponseObj(dataId));
                    }

                    var current = _aclObjectService.Get(x
                                                        => x.MessageID == dataId && x.Subscriber.ID == identityToDelete.ID, includeProperties: "Subscriber").FirstOrDefault();

                    // If it exists, delete it
                    if (current != null)
                    {
                        var subscribers = _subscriptionService.Get(s =>
                                                                   s.MessageID == dataId &&
                                                                   s.SubscriberIdentity.ID == current.Subscriber.ID);

                        _aclObjectService.Delete(current);
                        var msg = string.Format("ACL removed for identity {0} on messageId {1}.", identityDescriptionObject.IdentityId, dataId);
                        log.Info(msg);

                        // Remove subscriber
                        if (subscribers != null)
                        {
                            foreach (var subscriber in subscribers)
                            {
                                msg = string.Format("Subscriber {0} removed on messageId {1}", subscriber.SubscriberIdentity.UID, dataId);
                                _subscriptionService.Delete(subscriber);
                                log.Info(msg);
                            }
                        }
                    }
                }

                SetLastInteractionTime();
                _context.SaveChanges();

                return(new ResponseObj(dataId));;
            }
            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);

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

                string msg = "VIS internal server error. " + ex.Message;

                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
コード例 #8
0
        public WebRequestHelper.WebResponse FindServices(FindServicesRequestObj data)
        {
            string url         = string.Empty;
            bool   isGeoSearch = false;

            if (data.Filter.CoverageArea != null &&
                !string.IsNullOrEmpty(data.Filter.CoverageArea.Value))
            {
                if (data.Filter.CoverageArea.CoverageType == "WKT")
                {
                    url = PATH_SEARCH_WKT.Replace("[GEOMETRY]", HttpUtility.UrlEncode(data.Filter.CoverageArea.Value));
                }
                if (data.Filter.CoverageArea.CoverageType == "GeoJSON")
                {
                    url = PATH_SEARCH_GeoJSON.Replace("[GEOMETRY]", HttpUtility.UrlEncode(data.Filter.CoverageArea.Value));
                }

                isGeoSearch = true;
            }
            else
            {
                url = PATH_SEARCH_GENERIC;
            }

            string query = string.Empty;

            if (!string.IsNullOrEmpty(data.Filter.FreeText))
            {
                if (FormatValidation.IsValidFreeText(data.Filter.FreeText))
                {
                    query = data.Filter.FreeText.Replace(":", "\\:");
                    query = HttpUtility.UrlEncode(query);
                }
                else
                {
                    string msg      = "Forbidden character(s) in freetext search string.";
                    var    errorMsg = new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content      = new StringContent(msg),
                        ReasonPhrase = "Bad request."
                    };
                    throw new HttpResponseException(errorMsg);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(data.Filter.UnLoCode))
                {
                    query = AddToQuery(query, "unlocode", data.Filter.UnLoCode, "AND");
                }

                if (!string.IsNullOrEmpty(data.Filter.ServiceDesignId))
                {
                    query = AddToQuery(query, "designId", data.Filter.ServiceDesignId.Replace(":", "\\:"), "AND");
                }

                if (!string.IsNullOrEmpty(data.Filter.ServiceInstanceId))
                {
                    query = AddToQuery(query, "instanceId", data.Filter.ServiceInstanceId.Replace(":", "\\:"), "AND");
                }

                if (!string.IsNullOrEmpty(data.Filter.ServiceType))
                {
                    query = AddToQuery(query, "serviceType", data.Filter.ServiceType, "AND");
                }

                if (!string.IsNullOrEmpty(data.Filter.ServiceStatus))
                {
                    query = AddToQuery(query, "status", data.Filter.ServiceStatus, "AND");
                }

                if (!string.IsNullOrEmpty(data.Filter.Mmsi) && !string.IsNullOrEmpty(data.Filter.Imo))
                {
                    if (query == string.Empty)
                    {
                        query += "(";
                    }
                    else
                    {
                        query += " AND (";
                    }

                    query  = AddToQuery(query, "mmsi", data.Filter.Mmsi, "OR");
                    query  = AddToQuery(query, "imo", data.Filter.Imo, "OR");
                    query += ")";
                }
                else
                {
                    if (!string.IsNullOrEmpty(data.Filter.Mmsi))
                    {
                        query = AddToQuery(query, "mmsi", data.Filter.Mmsi, "AND");
                    }

                    if (!string.IsNullOrEmpty(data.Filter.Imo))
                    {
                        query = AddToQuery(query, "imo", data.Filter.Imo, "AND");
                    }
                }

                if (data.Filter.ServiceProviderIds != null && data.Filter.ServiceProviderIds.Count > 0)
                {
                    if (query == string.Empty)
                    {
                        query += "(";
                    }
                    else
                    {
                        query += " AND (";
                    }

                    foreach (var id in data.Filter.ServiceProviderIds)
                    {
                        query = AddToQuery(query, "organizationId", id.Replace(":", "\\:"), "OR");
                    }
                    query += ")";
                }

                if (data.Filter.ServiceProviderIds != null && data.Filter.ServiceProviderIds.Count > 0)
                {
                    if (query == string.Empty)
                    {
                        query += "(";
                    }
                    else
                    {
                        query += " AND (";
                    }

                    foreach (var id in data.Filter.ServiceProviderIds)
                    {
                        query = AddToQuery(query, "organizationId", id.Replace(":", "\\:"), "OR");
                    }
                    query += ")";
                }

                if (data.Filter.KeyWords != null && data.Filter.KeyWords.Count > 0)
                {
                    if (query == string.Empty)
                    {
                        query += "(";
                    }
                    else
                    {
                        query += " AND (";
                    }

                    foreach (var id in data.Filter.KeyWords)
                    {
                        query = AddToQuery(query, "keywords", id.Replace(":", "\\:"), "AND");
                    }
                    query += ")";
                }
            }

            if (string.IsNullOrEmpty(query) && !isGeoSearch)
            {
                url = PATH_ALL;
            }

            if (data.Page != null)
            {
                if (url == PATH_ALL)
                {
                    query += "?page=" + data.Page.ToString();
                }
                else
                {
                    query += "&page=" + data.Page.ToString();
                }
            }
            if (data.PageSize != null)
            {
                query += "&size=" + data.PageSize.ToString();
            }

            return(MakeGenericCall(url + query, "GET"));
        }
コード例 #9
0
        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);
            }
        }
コード例 #10
0
        public void ValidOrgMrnTest()
        {
            var result = FormatValidation.IsValidOrgId("urn:mrn:stm:org:sma");

            Assert.IsTrue(result);
        }
コード例 #11
0
        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);
            }
        }
コード例 #12
0
        public void InvalidUvidTest()
        {
            var result = FormatValidation.IsValidUvid("urn:mrn:stm:voyage:id:fel:sma:001");

            Assert.IsFalse(result);
        }
コード例 #13
0
        public void ValidUvidTest()
        {
            var result = FormatValidation.IsValidUvid("urn:mrn:stm:voyage:id:sma:001");

            Assert.IsTrue(result);
        }
コード例 #14
0
        public void InvalidServiceMrnTest()
        {
            var result = FormatValidation.IsValidServiceId("urn:mrn:stm:service:fel:sma:vistest001");

            Assert.IsFalse(result);
        }
コード例 #15
0
        public void ValidServiceMrnTest()
        {
            var result = FormatValidation.IsValidServiceId("urn:mrn:stm:service:instance:sma:vistest001");

            Assert.IsTrue(result);
        }
コード例 #16
0
        public void InvalidOrgMrnTest()
        {
            var result = FormatValidation.IsValidOrgId("urn:mrn:stm:fel:sma");

            Assert.IsFalse(result);
        }
コード例 #17
0
        public virtual Models.ResponseObj RemoveVoyagePlanSubscription([FromUri] string callbackEndpoint, [FromUri] string uvid = null)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

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

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

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

            // First, validate that we have mandatory in-parameters
            if (uvid != null && !FormatValidation.IsValidUvid(uvid))
            {
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Invalid UVID format");
            }

            if (string.IsNullOrEmpty(callbackEndpoint))
            {
                log.Debug("Callback endpoint address is empty");
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Required parameter CallbackEndpoint 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_removeSubscribeToVoyagePlan_request, EventDataType.None, paramList, null);

                // Get identity ether from internal id talbe or from id registry
                var identity = _identityService.GetCallerIdentity();

                var subscriptionsToDelete = new List <VisSubscription>();

                if (uvid == null)
                {
                    subscriptionsToDelete = _subscriptionService.Get(s => s.SubscriberIdentity.ID == identity.ID &&
                                                                     s.CallbackEndpoint == callbackEndpoint).ToList();
                }
                else
                {
                    subscriptionsToDelete = _subscriptionService.Get(s => s.SubscriberIdentity.ID == identity.ID &&
                                                                     s.MessageID == uvid &&
                                                                     s.CallbackEndpoint == callbackEndpoint).ToList();
                }

                if (subscriptionsToDelete != null &&
                    subscriptionsToDelete.Count > 0)
                {
                    foreach (var subscription in subscriptionsToDelete)
                    {
                        _subscriptionService.Delete(subscription.ID);

                        //Save to DB
                        _context.SaveChanges();
                    }
                }
                else
                {
                    string msg = string.Format("Subscription not found for UVID {0} and user {1} with endpoint {2}", uvid, InstanceContext.CallerOrgId, callbackEndpoint);
                    log.Debug(msg);

                    throw CreateHttpResponseException(HttpStatusCode.NotFound, msg);
                }

                var responseObj = new ResponseObj("Success delete subscription(s).");
                _logEventService.LogSuccess(EventNumber.VIS_removeSubscribeToVoyagePlan_response, EventDataType.Other, paramList,
                                            JsonConvert.SerializeObject(responseObj, Formatting.Indented));

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

                string msg = "VIS internal server error. " + ex.Message;
                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
コード例 #18
0
        public ResponseObj AddSubscription([FromBody] List <SubscriptionObject> subscriptions, [FromUri] string dataId)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

            if (string.IsNullOrEmpty(dataId))
            {
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Missing required parameter UVID.");
            }

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

            try
            {
                foreach (var subscription in subscriptions)
                {
                    var uri = subscription.EndpointURL.ToString().ToLower();

                    var sub = _subscriptionService.Get(s =>
                                                       s.SubscriberIdentity.UID == subscription.IdentityId &&
                                                       s.MessageID == dataId &&
                                                       s.CallbackEndpoint.ToLower() == uri, includeProperties: "SubscriberIdentity, MessageType").FirstOrDefault();

                    if (sub == null)
                    {
                        var acl = _aCLObjectService.Get(i =>
                                                        i.MessageID == dataId &&
                                                        i.Subscriber.UID == subscription.IdentityId).FirstOrDefault();

                        if (acl != null)
                        {
                            _subscriptionService.Insert(ConvertToEntity(subscription, dataId));
                        }
                        else
                        {
                            log.Debug(string.Format("No access for identity {0}", subscription.IdentityId));
                        }
                    }
                    else if (sub.IsAuthorized == false)
                    {
                        sub.IsAuthorized = true;
                    }

                    // Send message to new subscriber
                    var message = _publishedMessageService.Get(x => x.MessageID == dataId).FirstOrDefault();
                    if (message != null)
                    {
                        _publishedMessageService.SendMessage(System.Text.Encoding.Default.GetString(message.Message), dataId, subscription.EndpointURL.ToString(), new Identity {
                            Name = subscription.IdentityName, UID = subscription.IdentityId
                        });
                    }
                }

                SetLastInteractionTime();
                _context.SaveChanges();

                return(new ResponseObj(dataId));
            }
            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);

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

                string msg = "VIS internal server error. " + ex.Message;

                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
コード例 #19
0
        public virtual Models.GetVoyagePlanResponse GetVoyagePlans([FromUri] string uvid = null, [FromUri] string routeStatus = null)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

            GetVoyagePlanResponse result;

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

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

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

            // Get identity ether from internal id talbe or from id registry
            var identity = _identityService.GetCallerIdentity();

            // Get the calling serviceId
            if (string.IsNullOrEmpty(InstanceContext.CallerServiceId))
            {
                var msg = "Missing 'incomingServiceId'";
                log.Debug(msg);
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, msg);
            }
            log.Debug("incomingServiceId: " + InstanceContext.CallerServiceId);

            // Get the calling organisation identity
            if (string.IsNullOrEmpty(InstanceContext.CallerOrgId))
            {
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Missing organizationId in request");
            }
            log.Debug("incomingOrganizationId: " + InstanceContext.CallerServiceId);

            try
            {
                _logEventService.LogInfo(EventNumber.VIS_getVoyagePlan_request, EventDataType.None, paramList, null);

                if (string.IsNullOrEmpty(uvid) && string.IsNullOrEmpty(routeStatus))
                {
                    result = GetPublishedVoyagePlans(identity, paramList);
                }

                else if (!string.IsNullOrEmpty(uvid) && string.IsNullOrEmpty(routeStatus))
                {
                    if (!FormatValidation.IsValidUvid(uvid))
                    {
                        throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Invalid UVID format");
                    }
                    result = GetPublishedVoyagePlans(identity, paramList, uvid);
                }

                else if (string.IsNullOrEmpty(uvid) && !string.IsNullOrEmpty(routeStatus))
                {
                    int routeStatusInt = -1;
                    if (int.TryParse(routeStatus, out routeStatusInt))
                    {
                        if (routeStatusInt <= 0 || routeStatusInt > 7)
                        {
                            throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Argument {0} out of range.", routeStatus));
                        }
                    }
                    else
                    {
                        throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Argument {0} format unknown.", routeStatus));
                    }
                    result = GetPublishedVoyagePlans(identity, paramList, null, routeStatusInt);
                }
                else
                {
                    if (!FormatValidation.IsValidUvid(uvid))
                    {
                        throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Invalid UVID format");
                    }

                    int routeStatusInt = -1;
                    if (int.TryParse(routeStatus, out routeStatusInt))
                    {
                        if (routeStatusInt <= 0 || routeStatusInt > 8)
                        {
                            throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Argument {0} out of range.", routeStatus));
                        }
                    }
                    else
                    {
                        throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Argument {0} format unknown.", routeStatus));
                    }
                    result = GetPublishedVoyagePlans(identity, paramList, uvid, routeStatusInt);
                }
                _logEventService.LogSuccess(EventNumber.VIS_getVoyagePlan_response, EventDataType.Other,
                                            paramList, JsonConvert.SerializeObject(result, Formatting.Indented));

                var conStatus = _connectionInformationService.Get().FirstOrDefault();
                if (conStatus != null && conStatus.LastInteraction != null)
                {
                    result.LastInteractionTime = conStatus.LastInteraction;
                    result.LastInteractionTime = DateTime.SpecifyKind(result.LastInteractionTime.Value, DateTimeKind.Utc);
                }

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

                string msg = "VIS internal server error. " + ex.Message;
                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
コード例 #20
0
        public ResponseObj RemovePublishedMessage([FromUri] string dataId)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

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

            try
            {
                var message = _publishedMessageService.Get(x =>
                                                           x.MessageID == dataId).FirstOrDefault();

                if (message == null)
                {
                    var msg = string.Format("No message found with id {0}.", dataId);
                    log.Info(msg);
                    throw CreateHttpResponseException(HttpStatusCode.NotFound, msg);
                }
                else
                {
                    // Delete subscriptions
                    var subscriptions = _visSubscriptionService.Get(x => x.MessageID == dataId);
                    if (subscriptions != null)
                    {
                        foreach (var subscription in subscriptions)
                        {
                            _visSubscriptionService.Delete(subscription);
                        }
                    }

                    // Delete ACL
                    var acls = _aclObjectService.Get(x => x.MessageID == dataId);
                    if (acls != null)
                    {
                        foreach (var acl in acls)
                        {
                            _aclObjectService.Delete(acl);
                        }
                    }

                    // Delete message
                    _publishedMessageService.Delete(message);
                    var msg = string.Format("Published message with id {0} was removed.", dataId);
                    log.Info(msg);

                    SetLastInteractionTime();

                    _context.SaveChanges();
                    return(new ResponseObj(dataId));
                }
            }
            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);

                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                string msg = "VIS internal server error. " + ex.Message;
                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }