Ejemplo n.º 1
0
        public object Get(GetStorageFilesRequestTep request)
        {
            var    context = string.IsNullOrEmpty(request.apikey) ? TepWebContext.GetWebContext(PagePrivileges.UserView) : TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            string result  = null;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/store/{0}/{1} GET", request.repoKey, request.path));

                var apikey  = request.apikey ?? UserTep.FromId(context, context.UserId).GetSessionApiKey();
                var factory = new StoreFactory(context, apikey);

                Artifactory.Response.FileInfo info = factory.GetItemInfo(request.repoKey, request.path);
                info.Uri = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
                result   = factory.Serializer.Serialize(info);

                context.Close();
            }catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new HttpResult(result, Request.ContentType));
        }
Ejemplo n.º 2
0
        public object Delete(ShareDeleteRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            context.Open();
            context.LogInfo(this, string.Format("/share DELETE self='{0}'", request.self));

            var settings   = MasterCatalogue.OpenSearchFactorySettings;
            var entitySelf = new UrlBasedOpenSearchable(context, new OpenSearchUrl(request.self), settings).Entity;

            if (entitySelf is EntityList <WpsJob> )
            {
                var entitylist = entitySelf as EntityList <WpsJob>;
                var items      = entitylist.GetItemsAsList();
                if (items.Count > 0)
                {
                    foreach (var item in items)
                    {
                        item.RevokePermissionsFromAll(true, false);
                        if (item.Owner != null && item.DomainId != item.Owner.DomainId)
                        {
                            item.DomainId = item.Owner.DomainId;
                            item.Store();
                        }

                        //share on store
                        try {
                            DataGatewayFactory.ShareOnStore(context.GetConfigValue("SiteName"), item.StatusLocation, "results", "private");
                        }catch (Exception e) {
                            context.LogError(this, "Unable to share on STORE : " + e.Message, e);
                        }

                        //unpublish on community index
                        item.UnPublishFromIndex(context.GetConfigValue("catalog-communityIndex"), context.GetConfigValue("catalog-communityUsername"), context.GetConfigValue("catalog-communityApikey"));
                    }
                }
            }
            else if (entitySelf is EntityList <DataPackage> )
            {
                var entitylist = entitySelf as EntityList <DataPackage>;
                var items      = entitylist.GetItemsAsList();
                if (items.Count > 0)
                {
                    foreach (var item in items)
                    {
                        item.RevokePermissionsFromAll(true, false);
                        if (item.Owner != null && item.DomainId != item.Owner.DomainId)
                        {
                            item.DomainId = item.Owner.DomainId;
                            item.Store();
                        }
                    }
                }
            }
            else if (entitySelf is EntityList <WpsProcessOffering> )
            {
                var entitylist = entitySelf as EntityList <WpsProcessOffering>;
                var items      = entitylist.GetItemsAsList();
                if (items.Count > 0)
                {
                    foreach (var item in items)
                    {
                        item.RevokePermissionsFromAll(true, false);
                        if (item.Owner != null)
                        {
                            if (item.DomainId != item.Owner.DomainId)
                            {
                                item.DomainId = item.Owner.DomainId;
                                item.Store();
                            }
                        }
                    }
                }
            }

            context.Close();
            return(new WebResponseBool(true));
        }
Ejemplo n.º 3
0
        public object Get(GetStorageRepoRequestTep request)
        {
            var    context = string.IsNullOrEmpty(request.apikey) ? TepWebContext.GetWebContext(PagePrivileges.UserView) : TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            string result  = null;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/store GET"));

                var apikey  = request.apikey ?? UserTep.FromId(context, context.UserId).GetSessionApiKey();
                var factory = new StoreFactory(context, apikey);

                RepositoryInfoList repos = factory.GetRepositoriesToDeploy();
                var children             = new List <FileInfoChildren>();
                if (repos != null && repos.RepoTypesList != null)
                {
                    foreach (var repo in repos.RepoTypesList)
                    {
                        var child = new FileInfoChildren {
                            Uri    = "/" + repo.RepoKey,
                            Folder = true
                        };
                        children.Add(child);
                    }
                }
                FolderInfo info = new FolderInfo {
                    Uri      = System.Web.HttpContext.Current.Request.Url.AbsoluteUri,
                    Repo     = "",
                    Path     = "/",
                    Children = children.ToArray()
                };
                result = factory.Serializer.Serialize(info);

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new HttpResult(result, Request.ContentType));
        }
Ejemplo n.º 4
0
        public object Post(ShareCreateRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            context.Open();
            context.LogInfo(this, string.Format("/share POST self='{0}',to='{1}'", request.self, request.to != null ? string.Join("", request.to) : ""));

            var settings   = MasterCatalogue.OpenSearchFactorySettings;
            var entitySelf = new UrlBasedOpenSearchable(context, new OpenSearchUrl(request.self), settings).Entity;

            //case WpsJob
            if (entitySelf is EntityList <WpsJob> )
            {
                var entitylist = entitySelf as EntityList <WpsJob>;
                var wpsjobs    = entitylist.GetItemsAsList();
                if (wpsjobs.Count == 0)
                {
                    return(new WebResponseBool(false));
                }

                //if to is null, we share publicly
                if (request.to == null)
                {
                    foreach (var job in wpsjobs)   //the entitySelf can return several entities
                    //first we remove the current sharing (in case of restricted)
                    {
                        job.RevokePermissionsFromAll(true, false);
                        if (job.Owner != null && job.DomainId != job.Owner.DomainId)
                        {
                            job.DomainId = job.Owner.DomainId;
                            job.Store();
                        }
                        //secondly we share for all
                        job.GrantPermissionsToAll();

                        //share on store
                        try {
                            DataGatewayFactory.ShareOnStore(context.GetConfigValue("SiteName"), job.StatusLocation, "results", "public");
                        } catch (Exception e) {
                            context.LogError(this, "Unable to share on STORE : " + e.Message, e);
                        }

                        //publish on community index
                        if (request.publish)
                        {
                            job.PublishToIndex(context.GetConfigValue("catalog-communityIndex"), context.GetConfigValue("catalog-communityUsername"), context.GetConfigValue("catalog-communityApikey"), request.id);
                        }

                        Activity activity = new Activity(context, job, EntityOperationType.Share);
                        activity.Store();
                    }
                }

                //we share with restriction (community + users)
                else
                {
                    foreach (var job in wpsjobs)   //the entitySelf can return several entities

                    //remove previous visibility sharing
                    {
                        job.RevokePermissionsFromAll(true, false);
                        if (job.Owner != null && job.DomainId != job.Owner.DomainId)
                        {
                            job.DomainId = job.Owner.DomainId;
                            job.Store();
                        }

                        //unpublish on community index
                        job.UnPublishFromIndex(context.GetConfigValue("catalog-communityIndex"), context.GetConfigValue("catalog-communityUsername"), context.GetConfigValue("catalog-communityApikey"));

                        var sharedUsers       = new List <string>();
                        var sharedCommunities = new List <ThematicCommunity>();

                        foreach (var to in request.to)
                        {
                            var entityTo = new UrlBasedOpenSearchable(context, new OpenSearchUrl(to), settings).Entity;

                            //case community
                            if (entityTo is EntityList <ThematicCommunity> )
                            {
                                var entityTolist = entityTo as EntityList <ThematicCommunity>;
                                var communities  = entityTolist.GetItemsAsList();
                                if (communities.Count == 0)
                                {
                                    return(new WebResponseBool(false));
                                }

                                var community = communities[0];

                                //the entitySelflist can return several entities but we only take the first one (we can share with only one community)
                                community.ShareEntity(job);
                                job.DomainId = community.Id;
                                job.Store();

                                sharedCommunities.Add(community);

                                ActivityTep activity = new ActivityTep(context, job, EntityOperationType.Share);
                                activity.AppId    = request.id;
                                activity.DomainId = communities[0].Id;
                                activity.Store();
                            }

                            //case user
                            else if (entityTo is EntityList <UserTep> )
                            {
                                var entityTolist = entityTo as EntityList <UserTep>;
                                var users        = entityTolist.GetItemsAsList();
                                if (users.Count == 0)
                                {
                                    return(new WebResponseBool(false));
                                }
                                job.GrantPermissionsToUsers(users);

                                foreach (var usr in users)
                                {
                                    if (string.IsNullOrEmpty(usr.TerradueCloudUsername))
                                    {
                                        usr.LoadCloudUsername();
                                    }
                                    if (!string.IsNullOrEmpty(usr.TerradueCloudUsername))
                                    {
                                        sharedUsers.Add(usr.TerradueCloudUsername);
                                    }
                                }

                                ActivityTep activity = new ActivityTep(context, job, EntityOperationType.Share);
                                activity.AppId = request.id;
                                activity.Store();
                            }
                        }

                        //share on store
                        try {
                            DataGatewayFactory.ShareOnStore(context.GetConfigValue("SiteName"), job.StatusLocation, "results", "restricted", sharedUsers, sharedCommunities);
                        } catch (Exception e) {
                            context.LogError(this, "Unable to share on STORE : " + e.Message, e);
                        }
                    }
                }
            }

            //case DataPackage
            else if (entitySelf is EntityList <DataPackage> )
            {
                var entitylist   = entitySelf as EntityList <DataPackage>;
                var datapackages = entitylist.GetItemsAsList();
                if (datapackages.Count == 0)
                {
                    return(new WebResponseBool(false));
                }

                //if to is null, we share publicly
                if (request.to == null)
                {
                    foreach (var dp in datapackages)   //the entitySelf can return several entities
                    {
                        dp.GrantPermissionsToAll();

                        Activity activity = new Activity(context, dp, EntityOperationType.Share);
                        activity.Store();
                    }
                }

                //we share with restriction (community + users)
                else
                {
                    foreach (var dp in datapackages)   //the entitySelf can return several entities
                    //remove previous visibility sharing
                    {
                        dp.RevokePermissionsFromAll(true, false);
                        if (dp.Owner != null && dp.DomainId != dp.Owner.DomainId)
                        {
                            dp.DomainId = dp.Owner.DomainId;
                            dp.Store();
                        }

                        foreach (var to in request.to)
                        {
                            var entityTo = new UrlBasedOpenSearchable(context, new OpenSearchUrl(to), settings).Entity;

                            //case community
                            if (entityTo is EntityList <ThematicCommunity> )
                            {
                                var entityTolist = entityTo as EntityList <ThematicCommunity>;
                                var communities  = entityTolist.GetItemsAsList();
                                if (communities.Count == 0)
                                {
                                    return(new WebResponseBool(false));
                                }
                                //the entitySelflist can return several entities but we only take the first one (we can share with only one community)
                                dp.DomainId = communities[0].Id;
                                dp.Store();

                                ActivityTep activity = new ActivityTep(context, dp, EntityOperationType.Share);
                                activity.AppId    = request.id;
                                activity.DomainId = communities[0].Id;
                                activity.Store();
                            }

                            //case user
                            else if (entityTo is EntityList <UserTep> )
                            {
                                var entityTolist = entityTo as EntityList <UserTep>;
                                var users        = entityTolist.GetItemsAsList();
                                if (users.Count == 0)
                                {
                                    return(new WebResponseBool(false));
                                }
                                dp.GrantPermissionsToUsers(users);

                                ActivityTep activity = new ActivityTep(context, dp, EntityOperationType.Share);
                                activity.AppId = request.id;
                                activity.Store();
                            }
                        }
                    }
                }
            }
            else if (entitySelf is EntityList <WpsProcessOffering> )
            {
                var entitylist = entitySelf as EntityList <WpsProcessOffering>;
                var services   = entitylist.GetItemsAsList();
                if (services.Count == 0)
                {
                    return(new WebResponseBool(false));
                }

                //if to is null, we share publicly
                if (request.to == null)
                {
                    foreach (var s in services)   //the entitySelf can return several entities
                    {
                        s.GrantPermissionsToAll();

                        Activity activity = new Activity(context, s, EntityOperationType.Share);
                        activity.Store();
                    }
                }

                //we share with restriction (community + users)
                else
                {
                    foreach (var s in services)   //the entitySelf can return several entities
                    //remove previous visibility sharing
                    {
                        s.RevokePermissionsFromAll(true, false);
                        if (s.Owner != null && s.DomainId != s.Owner.DomainId)
                        {
                            s.DomainId = s.Owner.DomainId;
                            s.Store();
                        }

                        foreach (var to in request.to)
                        {
                            var entityTo = new UrlBasedOpenSearchable(context, new OpenSearchUrl(to), settings).Entity;

                            //case community
                            if (entityTo is EntityList <ThematicCommunity> )
                            {
                                var entityTolist = entityTo as EntityList <ThematicCommunity>;
                                var communities  = entityTolist.GetItemsAsList();
                                if (communities.Count == 0)
                                {
                                    return(new WebResponseBool(false));
                                }
                                //the entitySelflist can return several entities but we only take the first one (we can share with only one community)
                                s.DomainId = communities[0].Id;
                                s.Store();

                                ActivityTep activity = new ActivityTep(context, s, EntityOperationType.Share);
                                activity.AppId    = request.id;
                                activity.DomainId = communities[0].Id;
                                activity.Store();
                            }

                            //case user
                            else if (entityTo is EntityList <UserTep> )
                            {
                                var entityTolist = entityTo as EntityList <UserTep>;
                                var users        = entityTolist.GetItemsAsList();
                                if (users.Count == 0)
                                {
                                    return(new WebResponseBool(false));
                                }
                                s.GrantPermissionsToUsers(users);

                                ActivityTep activity = new ActivityTep(context, s, EntityOperationType.Share);
                                activity.AppId = request.id;
                                activity.Store();
                            }
                        }
                    }
                }
            }

            context.Close();
            return(new WebResponseBool(true));
        }
Ejemplo n.º 5
0
        public object Get(ShareGetRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            context.Open();
            context.LogInfo(this, string.Format("/share GET url='{0}'", request.url));

            var AppSettings = System.Configuration.ConfigurationManager.AppSettings;

            var redirect = new UriBuilder(context.BaseUrl);

            redirect.Path = "geobrowser";
            string redirectUrl = redirect.Uri.AbsoluteUri + (!string.IsNullOrEmpty(request.id) ? "/?id=" + request.id : "/") + "#!";

            var   pathUrl = new Uri(request.url).LocalPath.Replace(new Uri(context.BaseUrl).LocalPath, "");
            Match match   = Regex.Match(pathUrl, @"(\/?.*)search(\/?.*)");

            if (match.Success)
            {
                var resultType = match.Groups[1].Value.Trim('/');
                if (resultType.Equals(EntityType.GetEntityType(typeof(Series)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(Series)).Keyword;
                }
                else if (resultType.Equals(EntityType.GetEntityType(typeof(DataPackage)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(DataPackage)).Keyword;
                }
                else if (resultType.Contains(EntityType.GetEntityType(typeof(DataPackage)).Keyword))
                {
                    redirectUrl += "resultType=" + "data";//in this case it is a search (over a data package) so we use data keyword
                }
                else if (resultType.Equals(EntityType.GetEntityType(typeof(WpsJob)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(WpsJob)).Keyword;
                }
                else if (resultType.Equals(EntityType.GetEntityType(typeof(WpsProvider)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(WpsProvider)).Keyword;
                }
                else if (resultType.Equals(EntityType.GetEntityType(typeof(WpsProcessOffering)).Keyword))
                {
                    redirectUrl += "resultType=" + EntityType.GetEntityType(typeof(WpsProcessOffering)).Keyword;
                }
                else
                {
                    if (CatalogueFactory.IsCatalogUrl(new Uri(request.url)) || request.url.StartsWith(AppSettings["RecastBaseUrl"]))
                    {
                        redirectUrl += "resultType=" + "data";
                    }
                    else
                    {
                        try {
                            var settings = MasterCatalogue.OpenSearchFactorySettings;
                            var os       = new GenericOpenSearchable(new OpenSearchUrl(request.url), settings);
                            redirectUrl += "resultType=" + "data";
                        } catch (Exception) {
                            redirectUrl += "resultType=" + "na";
                        }
                    }
                }
                redirectUrl += "&url=" + HttpUtility.UrlEncode(request.url);
            }
            else
            {
                context.LogError(this, "Wrong format shared url");
                throw new Exception("Wrong format shared url");
            }

            var        keyword    = match.Groups[1].Value.StartsWith("/") ? match.Groups[1].Value.Substring(1) : match.Groups[1].Value;
            EntityType entityType = EntityType.GetEntityTypeFromKeyword(keyword);

            context.Close();

            return(new HttpResult()
            {
                StatusCode = System.Net.HttpStatusCode.Redirect, Headers = { { HttpHeaders.Location, redirectUrl } }
            });
        }
Ejemplo n.º 6
0
        /*				!
         * \fn Get(Getseries request)
         * \brief Response to the Get request with a Getseries object (get the complete list of series)
         * \param request request content
         * \return the series list
         */
        public object Get(GetOpensearchDescription request)
        {
            OpenSearchDescription OSDD;
            var context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            try{
                context.Open();
                context.LogInfo(this, string.Format("/data/collection/{{serieId}}/description GET serieId='{0}'", request.serieId));

                UriBuilder baseUrl = new UriBuilder(context.BaseUrl);

                if (request.serieId == null)
                {
                    throw new ArgumentNullException(Terradue.Tep.WebServer.CustomErrorMessages.WRONG_IDENTIFIER);
                }

                Terradue.Tep.Collection serie = Terradue.Tep.Collection.FromIdentifier(context, request.serieId);

                // The new URL template list
                Hashtable           newUrls = new Hashtable();
                UriBuilder          urib;
                NameValueCollection query = new NameValueCollection();

                urib = new UriBuilder(baseUrl.ToString());

                OSDD = serie.GetOpenSearchDescription();

                foreach (var url in OSDD.Url)
                {
                    string path = "";
                    switch (url.Type)
                    {
                    case "application/opensearchdescription+xml":
                        path = baseUrl.Path + "/data/collection/" + serie.Identifier + "/description";
                        break;

                    case "application/tdensity+json":
                        path = baseUrl.Path + "/data/collection/" + serie.Identifier + "/tdensity";
                        break;

                    default:
                        path = baseUrl.Path + "/data/collection/" + serie.Identifier + "/search";
                        break;
                    }

                    var queryUrl = url.Template != null && url.Template.IndexOf("?") >= 0 ? url.Template.Substring(url.Template.IndexOf("?")) : "";

                    var urlB = new UriBuilder(context.BaseUrl);
                    urlB.Path    = path;
                    url.Template = urlB.Uri.AbsoluteUri + queryUrl;
                }

                context.Close();
            }catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            HttpResult hr = new HttpResult(OSDD, "application/opensearchdescription+xml");

            return(hr);
        }
Ejemplo n.º 7
0
        public object Post(UploadDomainImageRequest request)
        {
            var    context   = TepWebContext.GetWebContext(PagePrivileges.AdminOnly);
            string img       = "";
            string uid       = Guid.NewGuid().ToString();
            string extension = ".png";

            WebDomain result = null;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/domain/{{Id}}/image POST Id='{0}'", request.Id));

                if (request.Id == 0)
                {
                    var segments = base.Request.PathInfo.Split(new [] { '/' },
                                                               StringSplitOptions.RemoveEmptyEntries);
                    request.Id = System.Int32.Parse(segments [1]);
                }

                Terradue.Portal.Domain domain = Terradue.Portal.Domain.FromId(context, request.Id);
                string oldImg = domain.IconUrl;
                if (this.RequestContext.Files.Length > 0)
                {
                    var uploadedFile = this.RequestContext.Files [0];
                    extension = uploadedFile.FileName.Substring(uploadedFile.FileName.LastIndexOf("."));
                    img       = "/files/" + uid + extension;

                    string path = AppDomain.CurrentDomain.BaseDirectory;
                    if (!path.EndsWith("/"))
                    {
                        path += "/";
                    }

                    context.LogInfo(this, string.Format("Uploading image to {0}", path + img));
                    uploadedFile.SaveTo(path + img);
                }
                else
                {
                    using (var fileStream = File.Create("files/" + uid + extension)) {
                        img = "files/" + uid + extension;
                        request.RequestStream.CopyTo(fileStream);
                    }
                }
                domain.IconUrl = img;
                domain.Store();

                result = new WebDomain(domain);

                try {
                    if (oldImg != null)
                    {
                        File.Delete("files/" + oldImg);
                    }
                } catch (Exception) { }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Get the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        public object Get(DataPackageSearchRequest request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            IOpenSearchResultCollection result = null;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/data/package/{{DataPackageId}}/search GET DataPackageId='{0}'", request.DataPackageId));

                Terradue.Tep.DataPackage datapackage;

                try{
                    datapackage = DataPackage.FromIdentifier(context, request.DataPackageId);
                }catch (Exception) {
                    if (request.Key != null) //or if public
                    {
                        context.AccessLevel = EntityAccessLevel.Administrator;
                        datapackage         = DataPackage.FromIdentifier(context, request.DataPackageId);
                        if (request.Key != null && !request.Key.Equals(datapackage.AccessKey))
                        {
                            throw new UnauthorizedAccessException(CustomErrorMessages.WRONG_ACCESSKEY);
                        }
                    }
                    else
                    {
                        datapackage = DataPackage.FromIdentifier(context, request.DataPackageId);
                    }
                }

                if (Request.QueryString != null && Request.QueryString["cache"] == "false")
                {
                    datapackage.SetOpenSearchEngine(MasterCatalogue.GetNewOpenSearchEngine());
                }
                else if (Request.QueryString != null && Request.QueryString["clearcache"] == "true")
                {
                    datapackage.SetOpenSearchEngine(MasterCatalogue.ClearOpenSearchEngine());
                }
                else
                {
                    datapackage.SetOpenSearchEngine(MasterCatalogue.OpenSearchEngine);
                }

                OpenSearchEngine ose = MasterCatalogue.OpenSearchEngine;

                Type responseType = OpenSearchFactory.ResolveTypeFromRequest(HttpContext.Current.Request.QueryString, HttpContext.Current.Request.Headers, ose);

                result = ose.Query(datapackage, Request.QueryString, responseType);

                var openSearchDescription = datapackage.GetLocalOpenSearchDescription();
                var uri_s = datapackage.GetSearchBaseUrl();
                OpenSearchDescriptionUrl openSearchUrlByRel = OpenSearchFactory.GetOpenSearchUrlByRel(openSearchDescription, "self");
                Uri uri_d;
                if (openSearchUrlByRel != null)
                {
                    uri_d = new Uri(openSearchUrlByRel.Template);
                }
                else
                {
                    uri_d = openSearchDescription.Originator;
                }
                if (uri_d != null)
                {
                    result.Links.Add(new SyndicationLink(uri_d, "search", "OpenSearch Description link", "application/opensearchdescription+xml", 0));
                }
                if (uri_s != null)
                {
                    result.Links.Add(new SyndicationLink(uri_s, "self", "OpenSearch Search link", "application/atom+xml", 0));
                }

                MasterCatalogue.ReplaceSelfLinksFormat(result, Request.QueryString);

                ActivityTep activity = new ActivityTep(context, datapackage, EntityOperationType.Search);
                activity.SetParam("items", result.TotalResults + "");
                activity.Store();

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new HttpResult(result.SerializeToString(), result.ContentType));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// This method allows user to confirm its email adress with a token key
        /// </summary>
        /// <param name="request">Request.</param>
        public object Get(ConfirmUserEmail request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            // Let's try to open context
            try {
                context.LogInfo(this, string.Format("/user/emailconfirm GET"));
                context.Open();
                context.LogError(this, string.Format("Email already confirmed for user {0}", context.Username));
                context.Close();
                return(new HttpError(System.Net.HttpStatusCode.MethodNotAllowed, new InvalidOperationException("Email already confirmed")));
            } catch (Exception e) {
                AuthenticationType authType      = IfyWebContext.GetAuthenticationType(typeof(TokenAuthenticationType));
                AuthenticationType umssoauthType = IfyWebContext.GetAuthenticationType(typeof(UmssoAuthenticationType));

                var umssoUser = umssoauthType.GetUserProfile(context, HttpContext.Current.Request, false);

                if (umssoUser == null)
                {
                    context.LogError(this, string.Format("User not logged in EOSSO"));
                    throw new ResourceNotFoundException("Not logged in EO-SSO");
                }

                if (e is PendingActivationException)
                {
                    context.LogDebug(this, string.Format("Pending activation for user {0}", context.Username));
                    // User is logged, now we confirm the email with the token
                    context.LogDebug(this, string.Format("User now logged -- Confirm email with token"));
                    User tokenUser = ((TokenAuthenticationType)authType).AuthenticateUser(context, request.Token);

                    // We must check that the logged user if the one that received the email
                    // If not, we rollback to previous status
                    if (tokenUser.Email != Request.Headers["Umsso-Person-Email"])
                    {
                        tokenUser.AccountStatus = AccountStatusType.PendingActivation;
                        tokenUser.Store();
                        context.LogError(this, string.Format("Confirmation email and UM-SSO email do not match"));
                        return(new HttpError(System.Net.HttpStatusCode.BadRequest, new UnauthorizedAccessException("Confirmation email and UM-SSO email do not match")));
                    }

                    context.LogDebug(this, string.Format("User now logged -- Email confirmed"));

                    //send an email to Support to warn them
                    try {
                        string emailFrom = context.GetConfigValue("MailSenderAddress");
                        string subject   = string.Format("[{0}] - Email verification for user {1}", context.GetConfigValue("SiteName"), umssoUser.Username);
                        string body      = context.GetConfigValue("EmailConfirmedNotification");
                        body = body.Replace("$(USERNAME)", umssoUser.Username);
                        body = body.Replace("$(EMAIL)", umssoUser.Email);
                        context.SendMail(emailFrom, emailFrom, subject, body);
                    } catch (Exception e1) {
                        context.LogError(this, e1.Message, e1);
                    }
                }
                else
                {
                    context.LogError(this, e.Message, e);
                    throw e;
                }
            }

            context.Close();
            return(new WebResponseBool(true));
        }
Ejemplo n.º 10
0
        public object Put(AnalyticsServicesCommunityRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            var result  = new List <WebAnalyticsService>();

            try {
                context.Open();
                context.LogInfo(this, string.Format("/analytics/service/community/{0} PUT", request.Identifier));

                if (string.IsNullOrEmpty(request.Usernames))
                {
                    return(new List <WebAnalyticsService>());
                }
                var usernames  = request.Usernames.Split(',');
                var usernamesS = "'" + string.Join("','", usernames) + "'";

                string sql = string.Format("SELECT id FROM usr WHERE username IN ({0});", usernamesS);
                context.LogDebug(this, sql);
                var requestids = context.GetQueryIntegerValues(sql);
                context.LogDebug(this, "found " + requestids.Length);

                ServiceAnalytics analytics = new ServiceAnalytics(context);
                var community = ThematicCommunity.FromIdentifier(context, request.Identifier);
                if (!community.CanUserManage(context.UserId))
                {
                    return(new List <WebAnalyticsService>());
                }
                var userids = community.GetUsersIds();
                context.LogDebug(this, "found " + userids.Count);

                var ids = new List <int>();
                foreach (var id in requestids)
                {
                    if (userids.Contains(id))
                    {
                        if (!ids.Contains(id))
                        {
                            ids.Add(id);
                        }
                    }
                }

                context.LogDebug(this, ids.Count + " in common");

                var apps       = new List <string>();
                var cachedapps = community.GetThematicApplicationsCached();
                foreach (var app in cachedapps)
                {
                    apps.Add(app.UId);
                }

                context.LogDebug(this, "found " + apps.Count + " apps");

                analytics.AddServices(request.startdate, request.enddate, ids, apps);
                foreach (var service in analytics.Services)
                {
                    result.Add(new WebAnalyticsService(service));
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Ejemplo n.º 11
0
        public object Post(GeometryPostRequestTep request)
        {
            var    context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            string wkt     = "";

            try {
                context.Open();
                context.LogInfo(this, string.Format("/geometry/{0} GET", request.points));

                if (request.points == 0)
                {
                    var segments = base.Request.PathInfo.Split(new[] { '/' },
                                                               StringSplitOptions.RemoveEmptyEntries);
                    request.points = System.Int32.Parse(segments[segments.Count() - 1]);
                }

                var points = request.points > 0 ? request.points : 3000;

                if (this.RequestContext.Files != null && this.RequestContext.Files.Length > 0)
                {
                    var extension = this.RequestContext.Files[0].FileName.Substring(this.RequestContext.Files[0].FileName.LastIndexOf("."));
                    switch (extension)
                    {
                    case ".zip":
                        using (var stream = new MemoryStream()) {
                            this.RequestContext.Files[0].InputStream.CopyTo(stream);
                            wkt = ExtractWKTFromShapefileZip(stream, points);
                        }
                        break;

                    case ".kml":
                        using (var stream = new MemoryStream()) {
                            this.RequestContext.Files[0].InputStream.CopyTo(stream);
                            wkt = ExtractWKTFromKML(stream, points);
                        }
                        break;

                    case ".kmz":
                        using (var stream = new MemoryStream()) {
                            this.RequestContext.Files[0].InputStream.CopyTo(stream);
                            ZipArchive archive = new ZipArchive(stream);
                            foreach (ZipArchiveEntry entry in archive.Entries)
                            {
                                if (entry.FullName.EndsWith(".kml", StringComparison.OrdinalIgnoreCase))
                                {
                                    using (var unzippedEntryStream = entry.Open()) {
                                        wkt = ExtractWKTFromKML(unzippedEntryStream, points);
                                        break;
                                    }
                                }
                            }
                        }
                        break;

                    case ".json":
                    case ".geojson":
                        using (var stream = new MemoryStream()) {
                            this.RequestContext.Files[0].InputStream.CopyTo(stream);
                            wkt = ExtractWKTFromGeoJson(stream, points);
                        }
                        break;

                    default:
                        throw new Exception("Invalid file type");
                    }
                }

                context.Close();
            }catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            if (!string.IsNullOrEmpty(wkt))
            {
                return(new WebResponseString(wkt));
            }
            else
            {
                throw new Exception("Unable to get WKT");
            }
        }
Ejemplo n.º 12
0
        public object Get(ProxyWpsJobSearchRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            context.Open();
            context.LogInfo(this, string.Format("/proxy/wps/{{jobid}}/search GET jobid='{0}'", request.jobid));

            WpsJob wpsjob = WpsJob.FromIdentifier(context, request.jobid);

            if (string.IsNullOrEmpty(wpsjob.StatusLocation))
            {
                throw new Exception("Invalid Status Location");
            }

            context.LogDebug(this, string.Format("Wps Proxy search for wpsjob {0}", wpsjob.Identifier));

            HttpWebRequest executeHttpRequest;

            if (wpsjob.Provider != null)
            {
                executeHttpRequest = wpsjob.Provider.CreateWebRequest(wpsjob.StatusLocation);
            }
            else
            {
                NetworkCredential credentials = null;
                var uri = new UriBuilder(wpsjob.StatusLocation);
                if (!string.IsNullOrEmpty(uri.UserName) && !string.IsNullOrEmpty(uri.Password))
                {
                    credentials = new NetworkCredential(uri.UserName, uri.Password);
                }
                executeHttpRequest = WpsProvider.CreateWebRequest(wpsjob.StatusLocation, credentials, context.Username);
            }

            if (wpsjob.StatusLocation.Contains("gpod.eo.esa.int"))
            {
                executeHttpRequest.Headers.Add("X-UserID", context.GetConfigValue("GpodWpsUser"));
            }
            OpenGis.Wps.ExecuteResponse execResponse = null;
            try {
                context.LogDebug(this, string.Format("Wps proxy - exec response requested - {0}", executeHttpRequest.Address.AbsoluteUri));
                using (var response = executeHttpRequest.GetResponse())
                    using (var stream = response.GetResponseStream())
                        execResponse = (OpenGis.Wps.ExecuteResponse) new System.Xml.Serialization.XmlSerializer(typeof(OpenGis.Wps.ExecuteResponse)).Deserialize(stream);
                context.LogDebug(this, string.Format("Wps proxy - exec response OK"));
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
            }
            if (execResponse == null)
            {
                throw new Exception("Unable to get execute response from proxied job");
            }

            execResponse.statusLocation = context.BaseUrl + "/wps/RetrieveResultServlet?id=" + wpsjob.Identifier;
            context.LogDebug(this, string.Format("Proxy WPS - uri: " + execResponse.statusLocation));

            AtomFeed feed = new AtomFeed();

            if (execResponse.ProcessOutputs != null)
            {
                foreach (OutputDataType output in execResponse.ProcessOutputs)
                {
                    if (output.Identifier != null && output.Identifier.Value != null && output.Identifier.Value.Equals("result_metadata"))
                    {
                        context.LogDebug(this, string.Format("Wps proxy - metadata"));
                        if (output.Item is OutputReferenceType)
                        {
                            var            reference = output.Item as OutputReferenceType;
                            HttpWebRequest atomRequest;
                            if (wpsjob.Provider != null)
                            {
                                atomRequest = wpsjob.Provider.CreateWebRequest(reference.href);
                            }
                            else
                            {
                                NetworkCredential credentials = null;
                                var uri = new UriBuilder(reference.href);
                                if (!string.IsNullOrEmpty(uri.UserName) && !string.IsNullOrEmpty(uri.Password))
                                {
                                    credentials = new NetworkCredential(uri.UserName, uri.Password);
                                }
                                atomRequest = WpsProvider.CreateWebRequest(reference.href, credentials, context.Username);
                            }
                            feed = CreateFeedForMetadata(atomRequest);
                        }
                        else if (output.Item is DataType)
                        {
                            var            item      = ((DataType)(output.Item)).Item as ComplexDataType;
                            var            reference = item.Reference as OutputReferenceType;
                            HttpWebRequest atomRequest;
                            if (wpsjob.Provider != null)
                            {
                                atomRequest = wpsjob.Provider.CreateWebRequest(reference.href);
                            }
                            else
                            {
                                NetworkCredential credentials = null;
                                var uri = new UriBuilder(reference.href);
                                if (!string.IsNullOrEmpty(uri.UserName) && !string.IsNullOrEmpty(uri.Password))
                                {
                                    credentials = new NetworkCredential(uri.UserName, uri.Password);
                                }
                                atomRequest = WpsProvider.CreateWebRequest(reference.href, credentials, context.Username);
                            }
                            feed = CreateFeedForMetadata(atomRequest);
                        }
                    }
                    else
                    {
                        if (output.Item is DataType && ((DataType)(output.Item)).Item != null)
                        {
                            var item = ((DataType)(output.Item)).Item as ComplexDataType;
                            if (item.Any != null && item.Any [0].LocalName != null)
                            {
                                if (item.Any [0].LocalName.Equals("RDF"))
                                {
                                    context.LogDebug(this, string.Format("Wps proxy - RDF"));
                                    feed = CreateFeedForRDF(item.Any [0], request.jobid, context.BaseUrl);
                                }
                                else if (item.Any [0].LocalName.Equals("metalink"))
                                {
                                    context.LogDebug(this, string.Format("Wps proxy - metalink"));
                                    feed = CreateFeedForMetalink(item.Any [0], request.jobid, context.BaseUrl, context);
                                }
                            }
                        }
                    }
                }
            }

            /* Proxy id + add self */
            foreach (var item in feed.Items)
            {
                var self   = context.BaseUrl + "/proxy/wps/" + wpsjob.Identifier + "/search?uid=" + HttpUtility.UrlEncode(item.Id);
                var search = context.BaseUrl + "/proxy/wps/" + wpsjob.Identifier + "/description";
                item.Id = self;
                item.Links.Add(Terradue.ServiceModel.Syndication.SyndicationLink.CreateSelfLink(new Uri(self), "application/atom+xml"));
                item.Links.Add(new Terradue.ServiceModel.Syndication.SyndicationLink(new Uri(search), "search", "OpenSearch Description link", "application/opensearchdescription+xml", 0));
            }

            feed.Id = wpsjob.StatusLocation;

            var  ose          = MasterCatalogue.OpenSearchEngine;
            Type responseType = OpenSearchFactory.ResolveTypeFromRequest(HttpContext.Current.Request.QueryString, HttpContext.Current.Request.Headers, ose);
            var  ext          = ose.GetFirstExtensionByTypeAbility(responseType);

            var osfeed = new AtomFeedOpenSearchable(feed);
            IOpenSearchResultCollection osr = ose.Query(osfeed, HttpContext.Current.Request.QueryString, responseType);

            var osrDesc = new Uri(context.BaseUrl + "/proxy/wps/" + wpsjob.Identifier + "/description");

            osr.Links.Add(new Terradue.ServiceModel.Syndication.SyndicationLink(osrDesc, "search", "OpenSearch Description link", "application/opensearchdescription+xml", 0));

            context.Close();
            return(new HttpResult(osr.SerializeToString(), osr.ContentType));
        }