public static List <OwsContextAtomEntry> GetRemoteWpsServiceEntriesFromUrl(IfyContext context, string href) { var result = new List <OwsContextAtomEntry>(); var httpRequest = (HttpWebRequest)WebRequest.Create(href); if (context.UserId != 0) { var user = UserTep.FromId(context, context.UserId); var apikey = user.GetSessionApiKey(); if (!string.IsNullOrEmpty(user.Username) && !string.IsNullOrEmpty(apikey)) { httpRequest.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(user.Username + ":" + apikey))); } } //TODO: manage case of /description //TODO: manage case of total result > 20 using (var resp = httpRequest.GetResponse()) { using (var stream = resp.GetResponseStream()) { var feed = ThematicAppCachedFactory.GetOwsContextAtomFeed(stream); if (feed.Items != null) { foreach (OwsContextAtomEntry item in feed.Items) { result.Add(item); } } } } return(result); }
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)); }
public object Get(GetDownloadStorageFileRequestTep request) { //var context = string.IsNullOrEmpty(request.apikey) ? TepWebContext.GetWebContext(PagePrivileges.UserView) : TepWebContext.GetWebContext(PagePrivileges.EverybodyView); var context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView); Stream result = null; try { context.Open(); context.LogInfo(this, string.Format("/store/download/{0}/{1} GET", request.repoKey, request.path)); var apikey = request.apikey ?? (context.UserId > 0 ? UserTep.FromId(context, context.UserId).GetSessionApiKey() : null); var factory = new StoreFactory(context, apikey); result = factory.DownloadItem(request.repoKey, request.path); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } var filename = request.path.Substring(request.path.LastIndexOf('/') + 1); Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename)); return(new HttpResult(result, "application/octet")); }
public object Get(AnalyticsCurrentUserRequestTep request) { var context = TepWebContext.GetWebContext(PagePrivileges.UserView); WebAnalytics result = new WebAnalytics(); try { context.Open(); context.LogInfo(this, string.Format("/analytics/user/current GET")); Analytics analytics = new Analytics(context, UserTep.FromId(context, context.UserId)); analytics.AnalyseCollections = false; analytics.AnalyseDataPackages = false; analytics.AnalyseJobs = true; analytics.AnalyseServices = false; analytics.Load(request.startdate, request.enddate); result = new WebAnalytics(analytics); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
/// <summary> /// Get the current user. /// </summary> /// <param name="request">Request.</param> /// <returns>the current user</returns> public object Get(UserGetCurrentRequestTep request) { WebUserTep result; var context = TepWebContext.GetWebContext(PagePrivileges.UserView); try { context.Open(); context.LogInfo(this, string.Format("/user/current GET")); UserTep user = UserTep.FromId(context, context.UserId); try { user.PrivateSanityCheck();//we do it here, because we do not want to do on each Load(), and we are sure users always pass by here }catch (Exception e) { context.LogError(this, e.Message, e); } result = new WebUserTep(context, user, false); try{ var cookie = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-access")); result.Token = cookie.Value; TimeSpan span = cookie.Expire.Subtract(DateTime.UtcNow); result.TokenExpire = span.TotalSeconds; }catch (Exception) {} context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public object Put(PutMoveStorageItemRequestTep 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/move/{0}/{1}?to={2}&dry={3} PUT", request.srcRepoKey, request.srcPath, request.to, request.dry)); var apikey = request.apikey ?? UserTep.FromId(context, context.UserId).GetSessionApiKey(); var factory = new StoreFactory(context, apikey); var to = request.to.Trim('/'); var toRepo = to.Substring(0, to.IndexOf('/')); var toPath = to.Substring(to.IndexOf('/') + 1); var info = factory.MoveItem(request.srcRepoKey, request.srcPath, toRepo, toPath, request.dry); 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)); }
/// <summary> /// Post the specified request. /// </summary> /// <param name="request">Request.</param> public object Post(UserCreateRequestTep request) { var context = TepWebContext.GetWebContext(PagePrivileges.UserView); WebUserTep result; try{ context.Open(); UserTep user = (request.Id == 0 ? null : UserTep.FromId(context, request.Id)); user = request.ToEntity(context, user); if (request.Id != 0 && context.UserLevel == UserLevel.Administrator) { user.AccountStatus = AccountStatusType.Enabled; } else { user.AccountStatus = AccountStatusType.PendingActivation; } user.IsNormalAccount = true; user.Level = UserLevel.User; user.Store(); context.LogInfo(this, string.Format("/user POST Id='{0}'", user.Id)); context.LogDebug(this, string.Format("User '{0}' has been created", user.Username)); result = new WebUserTep(context, user); context.Close(); }catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public void RefreshCachedApp(string uid) { this.LogInfo(string.Format("RefreshCachedApps -- Get public apps")); var apps = new EntityList <ThematicApplicationCached>(context); apps.SetFilter("UId", uid); apps.Load(); if (apps.Count == 1) { var app = apps.GetItemsAsList()[0]; var entries = app.Feed; if (entries == null) { entries = ThematicAppCachedFactory.GetOwsContextAtomFeed(app.TextFeed); } var itemFeed = entries.Items.First(); var link = itemFeed.Links.FirstOrDefault(l => l.RelationshipType == "self"); if (link == null) { return; } var url = link.Uri.AbsoluteUri; var urib = new UriBuilder(url); var query = HttpUtility.ParseQueryString(urib.Query); //add user apikey var user = UserTep.FromId(context, context.UserId); var apikey = user.GetSessionApiKey(); if (!string.IsNullOrEmpty(apikey)) { query.Set("apikey", apikey); } //add random for cache var random = new Random(); query.Set("random", random.Next() + ""); var queryString = Array.ConvertAll(query.AllKeys, key => string.Format("{0}={1}", key, query[key])); urib.Query = string.Join("&", queryString); url = urib.Uri.AbsoluteUri; HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); using (var resp = httpRequest.GetResponse()) { using (var stream = resp.GetResponseStream()) { var feed = GetOwsContextAtomFeed(stream); var entry = feed.Items.First(); if (feed.Items != null && feed.Items.Count() == 1) { app.Feed = feed; app.TextFeed = GetOwsContextAtomFeedAsString(feed); app.Searchable = GetSearchableTextFromAtomEntry(entry); app.LastUpdate = entry.LastUpdatedTime.DateTime == DateTime.MinValue ? DateTime.UtcNow : entry.LastUpdatedTime.DateTime; app.Store(); this.LogInfo(string.Format("ThematicAppCachedFactory -- Cached '{0}'", app.UId)); } } } } }
public object Post(AddGithubSSHKeyToCurrentUser request) { var context = TepWebContext.GetWebContext(PagePrivileges.UserView); WebGithubProfile result; try { context.Open(); context.LogInfo(this, string.Format("/github/sshkey POST")); GithubProfile user = GithubProfile.FromId(context, context.UserId); UserTep userTep = UserTep.FromId(context, context.UserId); userTep.LoadSSHPubKey(); user.PublicSSHKey = userTep.SshPubKey; GithubClient githubClient = new GithubClient(context); if (!user.IsAuthorizationTokenValid()) { throw new UnauthorizedAccessException("Invalid token"); } if (user.PublicSSHKey == null) { throw new UnauthorizedAccessException("No available public ssh key"); } githubClient.AddSshKey("Terradue ssh key", user.PublicSSHKey, user.Name, user.Token); context.LogDebug(this, string.Format("User {0} added Terradue ssh key to his github account", userTep.Username)); result = new WebGithubProfile(user); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public object Put(UpdateGithubUser request) { var context = TepWebContext.GetWebContext(PagePrivileges.UserView); WebGithubProfile result; try { context.Open(); context.LogInfo(this, string.Format("/github/user PUT Id='{0}'", request.Id)); GithubProfile user = GithubProfile.FromId(context, request.Id); user = request.ToEntity(context, user); user.Store(); user.Load(); //to get information from Github UserTep userTep = UserTep.FromId(context, context.UserId); userTep.LoadSSHPubKey(); user.PublicSSHKey = userTep.SshPubKey; context.LogDebug(this, string.Format("Github account of user {0} has been updated", userTep.Username)); result = new WebGithubProfile(user); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public object Post(PostDiscourseTopic request) { var context = TepWebContext.GetWebContext(PagePrivileges.UserView); string result; try { context.Open(); context.LogInfo(this, string.Format("/discourse/posts POST community='{0}'{1}{2}", request.communityIdentifier, !string.IsNullOrEmpty(request.subject) ? ", subject='" + request.subject + "'" : "", !string.IsNullOrEmpty(request.body) ? ", body='" + request.body + "'" : "" )); if (string.IsNullOrEmpty(request.subject)) { throw new Exception("Unable to post new topic, subject is null"); } if (string.IsNullOrEmpty(request.body)) { throw new Exception("Unable to post new topic, body is null"); } var community = ThematicCommunity.FromIdentifier(context, request.communityIdentifier); var discussCategory = community.DiscussCategory; if (string.IsNullOrEmpty(discussCategory)) { throw new Exception("Unable to post new topic, the selected community has no Discuss category associated"); } var user = UserTep.FromId(context, context.UserId); if (string.IsNullOrEmpty(user.TerradueCloudUsername)) { throw new Exception("Unable to post new topic, please set first your Terradue Cloud username"); } var discussClient = new DiscussClient(context.GetConfigValue("discussBaseUrl"), context.GetConfigValue("discussApiKey"), user.TerradueCloudUsername); var category = discussClient.GetCategory(discussCategory); if (category == null) { throw new Exception("Unable to post new topic, the selected community has no valid Discuss category associated"); } var catId = category.id; var response = discussClient.PostTopic(catId, request.subject, request.body); result = string.Format("{0}/t/{1}/{2}", discussClient.Host, response.topic_slug, response.topic_id); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(new WebService.Model.WebResponseString(result)); }
public object Post(PostStorageFilesRequestTep request) { if (request.repoKey == null) { var segments = base.Request.PathInfo.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); request.repoKey = segments[1]; request.path = base.Request.PathInfo.Substring(base.Request.PathInfo.IndexOf(request.repoKey + "/") + request.repoKey.Length + 1); } if (request.apikey == null) { request.apikey = base.Request.QueryString["apikey"]; } var context = string.IsNullOrEmpty(request.apikey) ? TepWebContext.GetWebContext(PagePrivileges.UserView) : TepWebContext.GetWebContext(PagePrivileges.EverybodyView); context.LogInfo(this, string.Format("/store/{0}/{1} POST", request.repoKey, request.path)); string path = System.Configuration.ConfigurationManager.AppSettings["UploadTmpPath"] ?? "/tmp"; try { context.Open(); var apikey = request.apikey ?? UserTep.FromId(context, context.UserId).GetSessionApiKey(); var factory = new StoreFactory(context, apikey); var filename = path + "/" + request.path.Substring(request.path.LastIndexOf("/") + 1); using (var stream = new MemoryStream()) { if (this.RequestContext.Files.Length > 0) { var uploadedFile = this.RequestContext.Files[0]; uploadedFile.SaveTo(filename); } else { using (var fileStream = File.Create(filename)) { request.RequestStream.CopyTo(fileStream); } } factory.UploadFile(request.repoKey, request.path, filename); } } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } context.Close(); return(new WebResponseBool(true)); }
/// <summary> /// Get the specified request. /// </summary> /// <param name="request">Request.</param> public object Get(UserGetCurrentSSORequestTep request) { WebUserTep result; var context = TepWebContext.GetWebContext(PagePrivileges.UserView); try { context.Open(); context.LogInfo(this, string.Format("/user/current/sso GET")); UserTep user = UserTep.FromId(context, context.UserId); //user.FindTerradueCloudUsername(); result = new WebUserTep(context, user); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public object Post(UserCurrentCreateSSORequestTep request) { WebUserTep result; var context = TepWebContext.GetWebContext(PagePrivileges.UserView); try { context.Open(); context.LogInfo(this, string.Format("/user/current/sso POST")); UserTep user = UserTep.FromId(context, context.UserId); user.CreateSSOAccount(request.Password); result = new WebUserTep(context, user); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public object Get(ThematicAppCheckAvailabilityRequest request) { var context = TepWebContext.GetWebContext(PagePrivileges.UserView); bool result = false; context.Open(); try { context.LogInfo(this, string.Format("/apps/available GET")); var user = UserTep.FromId(context, context.UserId); var apikey = user.GetSessionApiKey(); result = !CatalogueFactory.CheckIdentifierExists(context, request.Index, request.Uid, apikey); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(new WebResponseBool(result)); }
/// <summary> /// Put the specified request. /// </summary> /// <param name="request">Request.</param> public object Put(DataPackageExportRequestTep request) { var context = TepWebContext.GetWebContext(PagePrivileges.UserView); WebDataPackageTep result; try{ context.Open(); context.LogInfo(this, string.Format("/data/package/export PUT Id='{0}'", request.Id == 0 ? request.Identifier : request.Id.ToString())); DataPackage tmp; if (request.Id != 0) { tmp = DataPackage.FromId(context, request.Id); } else if (!string.IsNullOrEmpty(request.Identifier)) { tmp = DataPackage.FromIdentifier(context, request.Identifier); } else { throw new Exception("Undefined data package, set at least Id or Identifier"); } var serie = new Collection(context); serie.Identifier = tmp.Identifier; serie.Name = tmp.Name; var entityType = EntityType.GetEntityType(typeof(DataPackage)); var description = new UriBuilder(context.BaseUrl + "/" + entityType.Keyword + "/" + tmp.Identifier + "/description"); description.Query = "key=" + tmp.AccessKey; serie.CatalogueDescriptionUrl = description.Uri.AbsoluteUri; var user = UserTep.FromId(context, context.UserId); serie.Domain = user.Domain; serie.Store(); result = new WebDataPackageTep(tmp); context.Close(); }catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
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)); }
/// <summary> /// Get the specified request. /// </summary> /// <param name="request">Request.</param> public object Get(UserGetRequestTep request) { WebUserTep result; var context = TepWebContext.GetWebContext(PagePrivileges.UserView); try { context.Open(); context.LogInfo(this, string.Format("/user/{{Id}} GET Id='{0}'", request.Id)); UserTep user = UserTep.FromId(context, request.Id); result = new WebUserTep(context, user); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
/// <summary> /// Get the specified request. /// </summary> /// <param name="request">Request.</param> public object Get(UserGetProfileAdminRequestTep request) { WebUserTep result; var context = TepWebContext.GetWebContext(PagePrivileges.AdminOnly); try { context.Open(); context.LogInfo(this, string.Format("/user/{{id}}/admin GET Id='{0}'", request.id)); UserTep user = UserTep.FromId(context, request.id); result = new WebUserProfileTep(context, user); context.LogDebug(this, string.Format("Get public profile (admin view) for user '{0}'", user.Username)); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public object Put(UserUpdateAdminRequestTep request) { var context = TepWebContext.GetWebContext(PagePrivileges.AdminOnly); WebUserTep result; try { context.Open(); context.LogInfo(this, string.Format("/user/admin PUT Id='{0}'", request.Id)); UserTep user = (request.Id == 0 ? null : UserTep.FromId(context, request.Id)); user.Level = request.Level; user.Store(); context.LogDebug(this, string.Format("Level of user '{0}' has been updated to Level {1}", user.Username, request.Level)); result = new WebUserTep(context, user); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public object Get(GetGithubUser request) { var context = TepWebContext.GetWebContext(PagePrivileges.UserView); WebGithubProfile result; try { context.Open(); context.LogInfo(this, string.Format("/github/user/current GET")); GithubProfile user = GithubProfile.FromId(context, context.UserId); UserTep userTep = UserTep.FromId(context, context.UserId); userTep.LoadSSHPubKey(); user.PublicSSHKey = userTep.SshPubKey; result = new WebGithubProfile(user); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public object Delete(DeleteStorageFileRequestTep request) { var context = string.IsNullOrEmpty(request.apikey) ? TepWebContext.GetWebContext(PagePrivileges.UserView) : TepWebContext.GetWebContext(PagePrivileges.EverybodyView); try { context.Open(); context.LogInfo(this, string.Format("/store/{0}/{1} DELETE", request.repoKey, request.path)); var apikey = request.apikey ?? UserTep.FromId(context, context.UserId).GetSessionApiKey(); var factory = new StoreFactory(context, apikey); factory.DeleteFile(request.repoKey, request.path); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(new WebResponseBool(true)); }
public object Delete(UserDeleteApiKeyRequestTep request) { var context = TepWebContext.GetWebContext(PagePrivileges.UserView); WebUserTep result; try { context.Open(); context.LogInfo(this, string.Format("/user/key DELETE Id='{0}'", context.UserId)); UserTep user = UserTep.FromId(context, context.UserId); user.ApiKey = null; user.Store(); result = new WebUserTep(context, user); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
/// <summary> /// Post the specified request. /// </summary> /// <param name="request">Request.</param> public object Post(CreateDomainOwnerRequest request) { var context = TepWebContext.GetWebContext(PagePrivileges.AdminOnly); WebDomain result; try { context.Open(); context.LogInfo(this, string.Format("/domain/{{id}}/owner POST Id='{0}', UserId='{1}'", request.Id, request.UserId)); ThematicCommunity domain = ThematicCommunity.FromId(context, request.Id); UserTep owner = UserTep.FromId(context, request.UserId); domain.SetOwner(owner); result = new WebDomain(domain); context.Close(); } catch (Exception e) { context.LogError(this, e.Message, e); context.Close(); throw e; } return(result); }
public object Get(GetQgisIPRequest request) { string url = ""; TepWebContext context = new TepWebContext(PagePrivileges.UserView); try { context.Open(); context.LogInfo(this, string.Format("/user/current/qgis GET")); var user = UserTep.FromId(context, context.UserId); k8sFactory = new KubernetesFactory(context); url = GetUserVncUrl(context, user, null); context.Close(); } catch (Exception e) { context.LogError(this, e.Message + " - " + e.StackTrace); context.Close(); throw e; } return(new WebResponseString(url ?? "")); }
public object Post(CreateQgisRequest request) { string url = ""; TepWebContext context = new TepWebContext(PagePrivileges.EverybodyView); try { context.Open(); context.LogInfo(this, string.Format("/user/current/qgis POST")); var user = UserTep.FromId(context, context.UserId); k8sFactory = new KubernetesFactory(context); var k8srequest = CreateK8sRequest(k8sFactory, user); url = GetUserVncUrl(context, user, k8srequest); context.Close(); } catch (Exception e) { context.LogError(this, e.Message + " - " + e.StackTrace); context.Close(); throw e; } return(new WebResponseString(url)); }
public object Put(PutStorageFolderRequestTep 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} PUT", request.repoKey, request.path)); var apikey = request.apikey ?? UserTep.FromId(context, context.UserId).GetSessionApiKey(); var factory = new StoreFactory(context, apikey); var info = factory.CreateFolder(request.repoKey, request.path); 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)); }
private static List <WpsServiceOverview> GetWpsServiceOverview(IfyContext context, OwcOffering offering, string appUid, string appTitle, string appIcon) { List <WpsServiceOverview> wpsOverviews = new List <WpsServiceOverview>(); if (offering != null) { if (offering.Operations != null) { foreach (var ops in offering.Operations) { if (ops.Code == "ListProcess") { var href = ops.Href; //replace usernames in apps try { var user = UserTep.FromId(context, context.UserId); href = href.Replace("${USERNAME}", user.Username); href = href.Replace("${T2USERNAME}", user.TerradueCloudUsername); href = href.Replace("${T2APIKEY}", user.GetSessionApiKey()); } catch (Exception e) { context.LogError(context, e.Message); } var uri = new Uri(href.Replace("file://", context.BaseUrl)); var nvc = HttpUtility.ParseQueryString(uri.Query); nvc.Set("count", "100"); Terradue.OpenSearch.Engine.OpenSearchEngine ose = MasterCatalogue.OpenSearchEngine; var responseType = ose.GetExtensionByExtensionName("atom").GetTransformType(); EntityList <WpsProcessOffering> wpsProcesses = new EntityList <WpsProcessOffering>(context); wpsProcesses.SetFilter("Available", "true"); wpsProcesses.OpenSearchEngine = ose; wpsProcesses.Identifier = string.Format("servicewps-{0}", context.Username); CloudWpsFactory wpsOneProcesses = new CloudWpsFactory(context); wpsOneProcesses.OpenSearchEngine = ose; wpsProcesses.Identifier = "service/wps"; var entities = new List <IOpenSearchable> { wpsProcesses, wpsOneProcesses }; var settings = MasterCatalogue.OpenSearchFactorySettings; MultiGenericOpenSearchable multiOSE = new MultiGenericOpenSearchable(entities, settings); IOpenSearchResultCollection osr = ose.Query(multiOSE, nvc, responseType); OpenSearchFactory.ReplaceOpenSearchDescriptionLinks(wpsProcesses, osr); foreach (var itemWps in osr.Items) { string uid = ""; var identifiers = itemWps.ElementExtensions.ReadElementExtensions <string>("identifier", "http://purl.org/dc/elements/1.1/"); if (identifiers.Count > 0) { uid = identifiers[0]; } string description = ""; if (itemWps.Content is TextSyndicationContent) { var content = itemWps.Content as TextSyndicationContent; description = content.Text; } string version = ""; var versions = itemWps.ElementExtensions.ReadElementExtensions <string>("version", "https://www.terradue.com/"); if (versions.Count > 0) { version = versions[0]; } string publisher = ""; var publishers = itemWps.ElementExtensions.ReadElementExtensions <string>("publisher", "http://purl.org/dc/elements/1.1/"); if (publishers.Count > 0) { publisher = publishers[0]; } var serviceUrl = new UriBuilder(context.GetConfigValue("BaseUrl")); serviceUrl.Path = "/t2api/service/wps/search"; serviceUrl.Query = "id=" + uid; var url = new UriBuilder(context.GetConfigValue("BaseUrl")); url.Path = "t2api/share"; url.Query = "url=" + HttpUtility.UrlEncode(serviceUrl.Uri.AbsoluteUri) + "&id=" + appUid; var icon = itemWps.Links.FirstOrDefault(l => l.RelationshipType == "icon"); //entry.Links.Add(new SyndicationLink(new Uri(this.IconUrl), "icon", null, null, 0)); wpsOverviews.Add(new WpsServiceOverview { Identifier = uid, App = new AppOverview { Icon = appIcon ?? "", Title = appTitle, Uid = appUid }, Name = itemWps.Title != null ? itemWps.Title.Text : uid, Description = description, Version = version, Provider = publisher, Url = url.Uri.AbsoluteUri, Icon = icon != null ? icon.Uri.AbsoluteUri : "" }); } } } } } return(wpsOverviews); }
/// <summary> /// Creates the wps provider from VM (OpenNebula). /// </summary> /// <returns>The wps provider</returns> /// <param name="vm">Virtual machine object.</param> public static WpsProvider CreateWpsProviderForOne(IfyContext context, VM vm, NameValueCollection parameters = null) { context.LogDebug(context, "VM id = " + vm.ID); context.LogDebug(context, "VM name = " + vm.GNAME); WpsProvider wps = new WpsProvider(context); wps.Name = vm.NAME; wps.Identifier = "one-" + vm.ID; wps.Description = vm.NAME + " by " + vm.UNAME + " from laboratory " + vm.GNAME; wps.Proxy = true; wps.IsSandbox = true; wps.Tags = ""; try { var user = UserTep.FromId(context, context.UserId); wps.Domain = user.GetPrivateDomain(); } catch (Exception e) { context.LogError(wps, e.Message); } XmlNode[] user_template = (XmlNode[])vm.USER_TEMPLATE; bool isWPS = false; string wpsPort = "8080", wpsPath = "wps/WebProcessingService", nic = ""; context.LogDebug(wps, "Loading user template"); foreach (XmlNode nodeUT in user_template) { switch (nodeUT.Name) { case "WPS": context.LogDebug(wps, string.Format("WPS found : {0} - {1}", vm.ID, vm.GNAME)); isWPS = true; break; case "OPERATIONAL": context.LogDebug(wps, string.Format("Operational VM found : {0} - {1}", vm.ID, vm.GNAME)); wps.IsSandbox = false; break; case "TAGS": context.LogDebug(wps, string.Format("Tags found : {0} - {1} : {2}", vm.ID, vm.GNAME, nodeUT.InnerText)); var tags = nodeUT.InnerText.Split(',').ToList(); if (tags != null) { foreach (var tag in tags) { wps.AddTag(tag); } } break; case "LOGO": context.LogDebug(wps, string.Format("Logo found : {0} - {1} : {2}", vm.ID, vm.GNAME, nodeUT.InnerText)); wps.IconUrl = nodeUT.InnerText; break; case "WPS_PORT": context.LogDebug(wps, string.Format("Wps Port found : {0} - {1} : {2}", vm.ID, vm.GNAME, nodeUT.InnerText)); wpsPort = nodeUT.InnerText; break; case "WPS_PATH": context.LogDebug(wps, string.Format("Wps Path found : {0} - {1} : {2}", vm.ID, vm.GNAME, nodeUT.InnerText)); wpsPath = nodeUT.InnerText; break; default: break; } } context.LogDebug(wps, "Loading template"); foreach (XmlNode nodeT in (XmlNode[])vm.TEMPLATE) { context.LogDebug(context, "node name = " + nodeT.Name); switch (nodeT.Name) { case "NIC": nic = nodeT["IP"].InnerText; break; default: break; } } wps.BaseUrl = String.Format("http://{0}:{1}/{2}", nic, wpsPort, wpsPath); context.LogDebug(context, "wpsbaseurl = " + wps.BaseUrl); if (isWPS) { //check query parameters if (parameters != null) { //case sandbox if (parameters["sandbox"] != null) { switch (parameters["sandbox"]) { case "true": if (!wps.IsSandbox) { return(null); } break; case "false": if (wps.IsSandbox) { return(null); } break; default: break; } } //case hostname if (parameters["hostname"] != null) { var uriHost = new UriBuilder(nic); var r = new System.Text.RegularExpressions.Regex(parameters["hostname"]); var m = r.Match(uriHost.Host); if (!m.Success) { return(null); } } //case tags if (parameters["tag"] != null) { if (wps.Tags == null || !wps.Tags.Contains(parameters["tag"])) { return(null); } } } } return(wps); }
/// <summary> /// Get the specified request. /// </summary> /// <param name="request">Request.</param> /// /apps/{identifier}/search GET public object Get(ThematicAppSearchRequestTep request) { IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView); context.Open(); context.LogInfo(this, string.Format("/apps/search GET -- cache = {0}", request.cache)); IOpenSearchResultCollection result; OpenSearchEngine ose = MasterCatalogue.OpenSearchEngine; HttpRequest httpRequest = HttpContext.Current.Request; Type responseType = OpenSearchFactory.ResolveTypeFromRequest(httpRequest.QueryString, httpRequest.Headers, ose); //first we get the communities the user can see var communities = new EntityList <ThematicCommunity>(context); if (context.UserId == 0) { communities.SetFilter("Kind", (int)DomainKind.Public + ""); } else { communities.SetFilter("Kind", (int)DomainKind.Public + "," + (int)DomainKind.Hidden + "," + (int)DomainKind.Private); communities.AddSort("Kind", SortDirection.Ascending); } communities.Load(); if (request.cache) { List <int> ids = new List <int>(); foreach (var c in communities) { if (c.IsUserJoined(context.UserId)) { ids.Add(c.Id); } } EntityList <ThematicApplicationCached> appsCached = new EntityList <ThematicApplicationCached>(context); var filterValues = new List <object>(); filterValues.Add(string.Join(",", ids)); filterValues.Add(SpecialSearchValue.Null); appsCached.SetFilter("DomainId", filterValues.ToArray()); appsCached.SetGroupFilter("UId"); appsCached.AddSort("LastUpdate", SortDirection.Descending); result = ose.Query(appsCached, httpRequest.QueryString, responseType); OpenSearchFactory.ReplaceOpenSearchDescriptionLinks(appsCached, result); } else { List <Terradue.OpenSearch.IOpenSearchable> osentities = new List <Terradue.OpenSearch.IOpenSearchable>(); var settings = MasterCatalogue.OpenSearchFactorySettings; var specsettings = (OpenSearchableFactorySettings)settings.Clone(); if (context.UserId != 0) { var user = UserTep.FromId(context, context.UserId); var apikey = user.GetSessionApiKey(); var t2userid = user.TerradueCloudUsername; if (!string.IsNullOrEmpty(apikey)) { specsettings.Credentials = new System.Net.NetworkCredential(t2userid, apikey); } } //get apps link from the communities the user can see foreach (var community in communities.Items) { if (community.IsUserJoined(context.UserId)) { var app = community.GetThematicApplication(); if (app != null) { app.LoadItems(); foreach (var item in app.Items) { if (!string.IsNullOrEmpty(item.Location)) { try { var ios = OpenSearchFactory.FindOpenSearchable(specsettings, new OpenSearchUrl(item.Location)); osentities.Add(ios); context.LogDebug(this, string.Format("Apps search -- Add '{0}'", item.Location)); } catch (Exception e) { context.LogError(this, e.Message, e); } } } } } } //get thematic apps without any domain var apps = new EntityList <ThematicApplication>(context); apps.SetFilter("DomainId", SpecialSearchValue.Null); apps.SetFilter("Kind", ThematicApplication.KINDRESOURCESETAPPS + ""); apps.Load(); foreach (var app in apps) { app.LoadItems(); foreach (var item in app.Items) { if (!string.IsNullOrEmpty(item.Location)) { try { var ios = OpenSearchFactory.FindOpenSearchable(specsettings, new OpenSearchUrl(item.Location)); osentities.Add(ios); context.LogDebug(this, string.Format("Apps search -- Add '{0}'", item.Location)); } catch (Exception e) { context.LogError(this, e.Message, e); } } } } MultiGenericOpenSearchable multiOSE = new MultiGenericOpenSearchable(osentities, specsettings); result = ose.Query(multiOSE, httpRequest.QueryString, responseType); } var sresult = result.SerializeToString(); //replace usernames in apps try { var user = UserTep.FromId(context, context.UserId); sresult = sresult.Replace("${USERNAME}", user.Username); sresult = sresult.Replace("${T2USERNAME}", user.TerradueCloudUsername); sresult = sresult.Replace("${T2APIKEY}", user.GetSessionApiKey()); } catch (Exception e) { context.LogError(this, e.Message, e); } if (!string.IsNullOrEmpty(httpRequest.QueryString["uid"])) { try{ var user = UserTep.FromId(context, context.UserId); EventUserLoggerTep eventLogger = new EventUserLoggerTep(context); eventLogger.GetLogEvent(user, "portal_user_access_workspace", "User workspace access").ContinueWith <Event>( usrevent => { if (usrevent != null) { var callId = httpRequest.QueryString["uid"]; usrevent.Result.Item.Properties.Add("app_id", callId); EventFactory.Log(context, usrevent.Result); } return(usrevent.Result); } ); }catch (Exception) {} } context.Close(); return(new HttpResult(sresult, result.ContentType)); }