Exemplo n.º 1
0
        public static string GetUrlLocalUri(XUri confBaseUri, string url, bool includeQuery, bool decode)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(null);
            }

            if (url.StartsWithInvariantIgnoreCase(confBaseUri.ToString()))
            {
                //Remove the wiki path prefix (everything before display generally)
                url = confBaseUri.SchemeHostPort + url.Substring(confBaseUri.ToString().Length);
            }

            XUri uri = XUri.TryParse(url);

            if (uri == null)
            {
                return(null);
            }
            string ret = uri.Path;

            if (decode)
            {
                ret = XUri.Decode(ret);
            }

            if (includeQuery && !string.IsNullOrEmpty(uri.QueryFragment))
            {
                ret += uri.QueryFragment;
            }
            return(ret);
        }
Exemplo n.º 2
0
        public void TestFullServiceLifetime()
        {
            Plug p = Utils.BuildPlugForAdmin();

            string desc = "test service";

            XDoc serviceXml = new XDoc("service");

            serviceXml.Elem("sid", TEST_SERVICE_SID);
            serviceXml.Elem("type", "ext");
            serviceXml.Elem("description", desc);
            serviceXml.Elem("init", "native");

            //create the service
            DreamMessage msg = p.At("site", "services").PostAsync(serviceXml).Wait();

            Assert.IsTrue(msg.IsSuccessful, "service creation failed");
            uint service_id = msg.ToDocument()["@id"].AsUInt ?? 0;

            Assert.IsTrue(service_id > 0);

            //todo: validate the service

            //start the service
            msg = p.At("site", "services", service_id.ToString(), "start").PostAsync().Wait();
            Assert.IsTrue(msg.IsSuccessful, "service startup failed");
            XUri uri = msg.ToDocument()["uri"].AsUri;

            Assert.IsNotNull(uri);
            Assert.IsTrue(!string.IsNullOrEmpty(uri.ToString()));

            //stop the service
            msg = p.At("site", "services", service_id.ToString(), "stop").PostAsync().Wait();
            Assert.IsTrue(msg.IsSuccessful, "service stopping failed");
            Assert.IsTrue(string.IsNullOrEmpty(msg.ToDocument()["uri"].AsText));
            msg = p.At("site", "services", service_id.ToString()).GetAsync().Wait();
            Assert.IsTrue(msg.IsSuccessful);
            serviceXml = msg.ToDocument();

            //start the service
            msg = p.At("site", "services", service_id.ToString(), "start").PostAsync().Wait();
            Assert.IsTrue(msg.IsSuccessful, "service startup failed");
            uri = msg.ToDocument()["uri"].AsUri;
            Assert.IsNotNull(uri);
            Assert.IsTrue(!string.IsNullOrEmpty(uri.ToString()));

            //start the service
            msg = p.At("site", "services", service_id.ToString(), "start").PostAsync().Wait();
            Assert.IsTrue(msg.IsSuccessful, "service refresh failed");
            uri = msg.ToDocument()["uri"].AsUri;
            Assert.IsNotNull(uri);
            Assert.IsTrue(!string.IsNullOrEmpty(uri.ToString()));

            //delete the service
            msg = p.At("site", "services", service_id.ToString()).DeleteAsync().Wait();
            Assert.IsTrue(msg.IsSuccessful, "service deletion failed");
            msg = p.At("site", "services", service_id.ToString()).GetAsync().Wait();
            Assert.AreEqual(DreamStatus.NotFound, msg.Status, "service still exists after deletion");
        }
Exemplo n.º 3
0
        public void XmlAsUri()
        {
            XUri uri = new XUri("http://foo.com/bar");
            XDoc doc = new XDoc("test").Elem("uri", uri.ToString());

            Assert.AreEqual(uri.ToString(), doc["uri"].AsText);
            Assert.AreEqual(uri, doc["uri"].AsUri);
        }
Exemplo n.º 4
0
        public void TestSetPath2()
        {
            XUri uri = new XUri("http://www.dummy.com:8081/first/second?query=arg");

            uri = uri.AtAbsolutePath("/foo/bar?q=a");
            Assert.AreEqual("http://www.dummy.com:8081/foo/bar?q=a", uri.ToString());
        }
Exemplo n.º 5
0
            protected XDoc AsSwfObjectEmbed(string callback)
            {
                // NOTE (steveb): see SWFObject documentation at http://code.google.com/p/swfobject/wiki/documentation

                string id         = StringUtil.CreateAlphaNumericKey(8);
                string javascript = string.Format(
                    @"swfobject.embedSWF('{1}', '{0}', '{2}', '{3}', '9.0.0', '/skins/common/expressInstall.swf', {{ {5} }}, {{ allowScriptAccess: 'always', allowNetworking: 'all', allowFullScreen: 'true', bgcolor: '#000000', movie: '{1}', wmode: 'opaque' }}, {{ id: '{0}', name: '{0}' }}, {4});",
                    id,
                    Uri.ToString().EscapeString(),
                    AsSize(Width ?? 425),
                    AsSize(Height ?? 400),
                    callback ?? "null",
                    AutoPlayText
                    );
                XDoc result = new XDoc("html")
                              .Start("head")
                              .Start("script").Attr("type", "text/javascript").Attr("src", "/skins/common/swfobject.js").End()
                              .Start("script").Attr("type", "text/javascript").Value(javascript).End()
                              .End()
                              .Start("body")
                              .Start("div").Attr("id", id)
                              .Start("p")
                              .Start("a").Attr("href", "http://www.adobe.com/go/getflashplayer")
                              .Start("img").Attr("src", "http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif").Attr("alt", "Get Adobe Flash player").End()
                              .End()
                              .End()
                              .End()
                              .End();

                return(result);
            }
Exemplo n.º 6
0
        private XDoc ParseRevMessage(XDoc output, string msg)
        {
            //Parse the log message for bugs
            MatchCollection mc = null;

            if (_bugUri != null)
            {
                mc = BUGLINKREGEX.Matches(msg);
            }

            if (mc == null || mc.Count == 0)
            {
                OutputText(output, msg);
            }
            else
            {
                int index = 0;
                foreach (Match m in mc)
                {
                    OutputText(output, msg.Substring(index, m.Groups[1].Index - index));
                    output.Start("a").Attr("href", new XUri(_bugUri.ToString().Replace("$1", m.Groups[1].Value))).Value(m.Groups[1].Value).End();
                    index = m.Groups[1].Index + m.Groups[1].Length;
                }
                OutputText(output, msg.Substring(index));
            }

            return(output);
        }
Exemplo n.º 7
0
        public void TestAppendPath2()
        {
            XUri uri = new XUri("http://www.dummy.com:8081/first/second");

            uri = uri.AtPath("/foo/bar");
            Assert.AreEqual("http://www.dummy.com:8081/first/second//foo/bar", uri.ToString());
        }
Exemplo n.º 8
0
        public void Can_append_trailing_slash()
        {
            var uri = new XUri("http://foo/bar").WithTrailingSlash();

            Assert.IsTrue(uri.TrailingSlash);
            Assert.AreEqual("http://foo/bar/", uri.ToString());
        }
Exemplo n.º 9
0
        public void TestAppendQuery2()
        {
            XUri uri = new XUri("http://www.dummy.com:8081/first/second?query=arg");

            uri = uri.With("q", "a");
            Assert.AreEqual("http://www.dummy.com:8081/first/second?query=arg&q=a", uri.ToString());
        }
Exemplo n.º 10
0
 public void Get_via_internal_routing_and_AutoRedirect_off_shows_302()
 {
     using (var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
         var mock           = MockService.CreateMockService(hostInfo);
         var redirectCalled = 0;
         var redirectUri    = new XUri("mock://foo/bar");
         mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result <DreamMessage> response) {
             var msg = "nothing here";
             if (context.Uri.LastSegment == "redirect")
             {
                 _log.Debug("called redirect");
                 redirectCalled++;
                 response.Return(DreamMessage.Redirect(redirectUri));
                 return;
             }
             _log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
             response.Return(DreamMessage.NotFound(msg));
         };
         var uri = mock.AtLocalMachine.At("redirect");
         _log.DebugFormat("calling redirect service at {0}", uri);
         var r = Plug.New(uri).WithHeader("h", "y").WithoutAutoRedirects().Get(new Result <DreamMessage>()).Wait();
         Assert.AreEqual(DreamStatus.Found, r.Status, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
         Assert.AreEqual(1, redirectCalled, "redirect called incorrectly");
         Assert.AreEqual(redirectUri.ToString(), r.Headers.Location.ToString());
     }
 }
Exemplo n.º 11
0
        public void Can_remove_trailing_slash()
        {
            var uri = new XUri("http://foo/bar/").WithoutTrailingSlash();

            Assert.IsFalse(uri.TrailingSlash);
            Assert.AreEqual("http://foo/bar", uri.ToString());
        }
Exemplo n.º 12
0
        public Yield ExpandFolder(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            if (_directoryInfo == null)
            {
                throw new DreamBadRequestException("folder is misconfigured");
            }

            // Extract the folder to expand
            string foldername = context.GetParam("foldername", String.Empty);

            foldername = XUri.Decode(foldername);
            if (foldername.Contains(".."))
            {
                response.Return(DreamMessage.Forbidden("Relative paths are not allowed"));
                yield break;
            }

            // Extract the search pattern
            string pattern = context.GetParam("pattern", null);

            DirectoryInfo currentDirectory = new DirectoryInfo(_directoryInfo.FullName + Path.DirectorySeparatorChar + foldername);
            XDoc          result           = new XDoc("results");

            // If specified, retrieve all the directories under the current directory
            bool topDirectoryOnly = context.GetParam("topDirectoryOnly", false);

            if (!topDirectoryOnly)
            {
                foreach (DirectoryInfo directory in currentDirectory.GetDirectories())
                {
                    string encodedDirectoryName = XUri.DoubleEncodeSegment((foldername + Path.DirectorySeparatorChar + directory.Name).Replace("+", "%2b"));
                    XUri   dynamicExpandUri     = DreamContext.Current.AsPublicUri(Self.At("expand", encodedDirectoryName)).With("dream.out.format", "json");
                    if (null != pattern)
                    {
                        dynamicExpandUri = dynamicExpandUri.With("pattern", pattern);
                    }
                    result.Start("result").Elem("name", directory.Name).Elem("dynamicexpanduri", dynamicExpandUri.ToString()).End();
                }
            }

            // Retrieve files according to the search pattern
            FileInfo[] files;
            if (null != pattern)
            {
                files = currentDirectory.GetFiles(pattern, SearchOption.TopDirectoryOnly);
            }
            else
            {
                files = currentDirectory.GetFiles();
            }
            foreach (FileInfo file in files)
            {
                string encodedFileName = XUri.DoubleEncodeSegment((foldername + Path.DirectorySeparatorChar + file.Name).Replace("+", "%2b"));
                XUri   href            = DreamContext.Current.AsPublicUri(Self.At("doc", encodedFileName));
                result.Start("result").Elem("name", file.Name).Elem("href", href.ToString()).Elem("labelstyle", "iconitext-16 ext-" + file.Extension.TrimStart('.').ToLowerInvariant()).End();
            }

            response.Return(DreamMessage.Ok(result));
            yield break;
        }
Exemplo n.º 13
0
        public Yield Invoke(Plug plug, string verb, XUri uri, DreamMessage request, Result <DreamMessage> response)
        {
            Result <DreamMessage> res;

            // register activity
            DreamContext    context = DreamContext.CurrentOrNull;
            Action <string> activity;

            if (context != null)
            {
                activity = new ActivityState(context.Env, verb, uri.ToString()).Message;
            }
            else
            {
                activity = delegate(string message) { };
            }
            activity("pre Invoke");
            yield return(res = Coroutine.Invoke(HandleInvoke, activity, plug, verb, uri, request, new Result <DreamMessage>(response.Timeout)).Catch());

            activity("post Invoke");

            // unregister activity
            activity(null);

            // return response
            response.Return(res);
        }
Exemplo n.º 14
0
        public void TestAppendPath8()
        {
            XUri uri = new XUri("http:///").AtAbsolutePath("foo/bar/");

            Assert.AreEqual("/foo/bar/", uri.Path);
            Assert.AreEqual(2, uri.Segments.Length);
            Assert.AreEqual("http:///foo/bar/", uri.ToString());
        }
Exemplo n.º 15
0
 private void AddRequest(string method, XUri href, string data)
 {
     _requestDoc.Start("request")
     .Attr("method", method)
     .Attr("href", href.ToString())
     .Attr("dataid", data)
     .End();
 }
Exemplo n.º 16
0
        private void AddUri(XmlNode context, DekiScriptUri uri)
        {
            if (context == null)
            {
                ConvertStateToHtml(null);
            }

            // NOTE (steveb): URIs have special embedding rules; either embed it as a <img> and <a> document base on the URI file extension on the last segment

            XUri     url  = uri.Value.AsPublicUri();
            MimeType mime = (url.Segments.Length > 0) ? MimeType.FromFileExtension(url.LastSegment ?? string.Empty) : MimeType.BINARY;
            XDoc     item = mime.MainType.EqualsInvariant("image") ?
                            DekiScriptLibrary.WebImage(url.ToString(), null, null, null) :
                            DekiScriptLibrary.WebLink(url.ToString(), null, null, null);

            AddXDoc(context, item);
        }
Exemplo n.º 17
0
        public void TestAppendPath6()
        {
            XUri uri = new XUri("http:///").At("path");

            Assert.AreEqual("/path", uri.Path);
            Assert.AreEqual(1, uri.Segments.Length);
            Assert.AreEqual("http:///path", uri.ToString());
        }
Exemplo n.º 18
0
        public void WithTrailingSlash_only_adds_when_needed()
        {
            var uri = new XUri("http://foo/bar/");

            Assert.IsTrue(uri.TrailingSlash);
            uri = uri.WithTrailingSlash();
            Assert.IsTrue(uri.TrailingSlash);
            Assert.AreEqual("http://foo/bar/", uri.ToString());
        }
Exemplo n.º 19
0
        public void TestFragmentEncoding()
        {
            XUri uri = new XUri("http://foo/bar#baz=10");

            Assert.AreEqual("baz=10", uri.Fragment);
            XUri uri2 = new XUri(uri.ToString());

            Assert.AreEqual("baz=10", uri2.Fragment);
        }
Exemplo n.º 20
0
        public void Can_roundtrip_GetRelativePathTo_via_AtPath_with_trailing_slash_on_base()
        {
            var uri       = new XUri("http://foo/a/b/c");
            var baseUri   = new XUri("http://foo/a/");
            var relative  = uri.GetRelativePathTo(baseUri);
            var roundtrip = baseUri.AtPath(relative);

            Assert.AreEqual(uri.ToString(), roundtrip.ToString());
        }
Exemplo n.º 21
0
        public void WithoutTrailingSlash_only_removes_when_needed()
        {
            var uri = new XUri("http://foo/bar");

            Assert.IsFalse(uri.TrailingSlash);
            uri = uri.WithoutTrailingSlash();
            Assert.IsFalse(uri.TrailingSlash);
            Assert.AreEqual("http://foo/bar", uri.ToString());
        }
Exemplo n.º 22
0
        private void PropertyChanged(DateTime eventTime, ResourceBE prop, UserBE user, ResourceBE.ParentType parentType, XUri parentUri, params string[] path)
        {
            try {
                string parent = string.Empty;
                switch (parentType)
                {
                case ResourceBE.ParentType.PAGE:
                    parent = PAGES;
                    break;

                case ResourceBE.ParentType.FILE:
                    parent = FILES;
                    break;

                case ResourceBE.ParentType.USER:
                    parent = USERS;
                    break;

                case ResourceBE.ParentType.SITE:
                    parent = SITE;
                    break;
                }
                XUri     channel  = _channel.At(parent).At(PROPERTY).At(path);
                XUri     resource = prop.PropertyInfoUri(parentUri);
                string[] origin   = new string[] { resource.ToString() };
                XDoc     doc      = new XDoc("deki-event")
                                    .Elem("channel", channel)
                                    .Elem("name", prop.Name)
                                    .Elem("uri", resource)
                                    .Start("content")
                                    .Attr("mime-type", prop.MimeType.FullType)
                                    .Attr("size", prop.Size)
                                    .Attr("href", prop.PropertyContentUri(parentUri));
                if (prop.MimeType.MainType == MimeType.TEXT.MainType && prop.Size < 256)
                {
                    doc.Value(ResourceContentBL.Instance.Get(prop).ToText());
                }
                doc.End();
                if (parentType == ResourceBE.ParentType.PAGE)
                {
                    doc.Elem("pageid", prop.ParentPageId ?? 0);
                }
                else if (parentType == ResourceBE.ParentType.USER)
                {
                    doc.Elem("userid", prop.ParentUserId ?? 0);
                }
                else if (parentType == ResourceBE.ParentType.FILE)
                {
                    ResourceBE attachment = ResourceBL.Instance.GetResource(prop.ParentId.Value);
                    doc.Elem("fileid", attachment.MetaXml.FileId ?? 0);
                    PageDependentChanged(eventTime, PageBL.GetPageById(attachment.ParentPageId.Value), user, ArrayUtil.Concat(new string[] { FILES, PROPERTY }, path));
                }
                Queue(eventTime, channel, resource, origin, doc);
            } catch (Exception e) {
                _log.WarnExceptionMethodCall(e, "PropertyChanged", "event couldn't be created");
            }
        }
Exemplo n.º 23
0
        public void TestQueryEncoding()
        {
            XUri uri = new XUri("http://foo/bar");

            uri = uri.With("x", "a=b");
            Assert.AreEqual("a=b", uri.GetParam("x"));
            XUri uri2 = new XUri(uri.ToString());

            Assert.AreEqual("a=b", uri2.GetParam("x"));
        }
Exemplo n.º 24
0
        //--- Methods ---
        public void Startup()
        {
            _log.InfoMethodCall("Startup", _uri.ToString(false));

            // create listener and make it listen to the uri
            _listener = new HttpListener {
                IgnoreWriteExceptions = true,
                AuthenticationSchemes = _authenticationSheme
            };
            _listener.Prefixes.Add(_uri.ToString());
            try {
                _listener.Start();
            } catch (Exception x) {
                _log.WarnExceptionFormat(x, "Unable to start listening on '{0}'", _uri.ToString(false));
                throw;
            }
            _listener.BeginGetContext(RequestHandler, _listener);

            // register plug factory for this uri
            Plug.AddEndpoint(this);
        }
Exemplo n.º 25
0
 private void AddBodyRequest(string method, XUri href, XDoc body, string type)
 {
     _requestDoc.Start("request")
     .Attr("method", method)
     .Attr("href", href.ToString())
     .Attr("type", type)
     .Start("body")
     .Attr("type", "xml")
     .Add(body)
     .End()
     .End();
 }
Exemplo n.º 26
0
 private XDoc OutputRevLink(XDoc output, string rev)
 {
     if (_svnRevUri == null)
     {
         output.Value("r" + rev);
     }
     else
     {
         output.Start("a").Attr("href", new XUri(_svnRevUri.ToString().Replace("$1", rev))).Value(rev).End();
     }
     return(output);
 }
Exemplo n.º 27
0
        //--- Methods ---
        private Yield FetchResult(string name, XUri input, Hashtable args, Result <XDoc> response)
        {
            // build uri
            XUri uri = new XUri("http://www.dapper.net/RunDapp?v=1").With("dappName", name);

            if (input != null)
            {
                uri = uri.With("applyToUrl", input.ToString());
            }
            if (args != null)
            {
                foreach (DictionaryEntry entry in args)
                {
                    uri = uri.With(VARIABLE_PREFIX + SysUtil.ChangeType <string>(entry.Key), SysUtil.ChangeType <string>(entry.Value));
                }
            }

            // check if we have a cached result
            XDoc   result;
            string key = uri.ToString();

            lock (_cache) {
                if (_cache.TryGetValue(key, out result))
                {
                    response.Return(result);
                    yield break;
                }
            }

            // fetch result
            Result <DreamMessage> res;

            yield return(res = Plug.New(uri).GetAsync());

            if (!res.Value.IsSuccessful)
            {
                throw new DreamInternalErrorException(string.Format("Unable to process Dapp: ", input));
            }
            if (!res.Value.HasDocument)
            {
                throw new DreamInternalErrorException(string.Format("Dapp response is not XML: ", input));
            }

            // add result to cache and start a clean-up timer
            lock (_cache) {
                _cache[key] = res.Value.ToDocument();
            }
            TaskTimer.New(TimeSpan.FromSeconds(CACHE_TTL), RemoveCachedEntry, key, TaskEnv.None);
            response.Return(res.Value.ToDocument());
            yield break;
        }
 public static string UriAppendQuery(
     [DekiScriptParam("base uri")] XUri uri,
     [DekiScriptParam("query parameters to append")] Hashtable args
     )
 {
     foreach (DictionaryEntry entry in args)
     {
         string value = SysUtil.ChangeType <string>(entry.Value);
         if (value != null)
         {
             uri = uri.With((string)entry.Key, value);
         }
     }
     return(uri.ToString());
 }
Exemplo n.º 29
0
 public void TestXUriFromUriConstruction2()
 {
     string[] evilSegments = new string[] {
         // Escaped version of "Iñtërnâtiônàlizætiøn" (should look similar to "Internationalization" but with extended characteres)
         "I\u00f1t\u00ebrn\u00e2ti\u00f4n\u00e0liz\u00e6ti\u00f8n"
     };
     foreach (string evil in evilSegments)
     {
         XUri original    = new XUri("http://" + evil);
         XUri fromDecoded = new XUri(original.ToString());
         XUri uri1        = new XUri(original);
         XUri uri2        = new XUri(fromDecoded);
         // just making sure they actually parse
     }
 }
Exemplo n.º 30
0
 //--- Constructors ---
 public HttpTransport(IDreamEnvironment env, XUri uri, AuthenticationSchemes authenticationSheme)
 {
     if(env == null) {
         throw new ArgumentNullException("env");
     }
     if(uri == null) {
         throw new ArgumentNullException("uri");
     }
     _env = env;
     _uri = uri.WithoutCredentialsPathQueryFragment();
     _minSimilarity = _uri.MaxSimilarity;
     _sourceInternal = _uri + " (internal)";
     _sourceExternal = _uri.ToString();
     _authenticationSheme = authenticationSheme;
 }
Exemplo n.º 31
0
 //--- Constructors ---
 public HttpTransport(IDreamEnvironment env, XUri uri, AuthenticationSchemes authenticationSheme, string dreamInParamAuthtoken)
 {
     if(env == null) {
         throw new ArgumentNullException("env");
     }
     if(uri == null) {
         throw new ArgumentNullException("uri");
     }
     _env = env;
     _uri = uri.WithoutCredentialsPathQueryFragment();
     _minSimilarity = _uri.MaxSimilarity;
     _sourceInternal = _uri + " (internal)";
     _sourceExternal = _uri.ToString();
     _authenticationSheme = authenticationSheme;
     _dreamInParamAuthtoken = dreamInParamAuthtoken;
     this.ServerSignature = "Dream-HTTPAPI/" + DreamUtil.DreamVersion;
 }
Exemplo n.º 32
0
 //--- Constructors ---
 public HttpTransport(IDreamEnvironment env, XUri uri, AuthenticationSchemes authenticationSheme)
 {
     if (env == null)
     {
         throw new ArgumentNullException("env");
     }
     if (uri == null)
     {
         throw new ArgumentNullException("uri");
     }
     _env                 = env;
     _uri                 = uri.WithoutCredentialsPathQueryFragment();
     _minSimilarity       = _uri.MaxSimilarity;
     _sourceInternal      = _uri + " (internal)";
     _sourceExternal      = _uri.ToString();
     _authenticationSheme = authenticationSheme;
 }
Exemplo n.º 33
0
 public void TestQueryEncoding()
 {
     XUri uri = new XUri("http://foo/bar");
     uri = uri.With("x", "a=b");
     Assert.AreEqual("a=b", uri.GetParam("x"));
     XUri uri2 = new XUri(uri.ToString());
     Assert.AreEqual("a=b", uri2.GetParam("x"));
 }
Exemplo n.º 34
0
 public void TestUriConstructor12()
 {
     string original = "http://*****:*****@domain.org:81/path/foo%20bar/path//@blah/?ready&set=&go=foo/bar#yo";
     XUri uri = new XUri(original);
     Assert.AreEqual("http", uri.Scheme);
     Assert.AreEqual("domain.org", uri.Host);
     Assert.AreEqual(81, uri.Port);
     Assert.AreEqual(false, uri.UsesDefaultPort);
     Assert.AreEqual("user", uri.User);
     Assert.AreEqual("password", uri.Password);
     Assert.AreEqual("/path/foo%20bar/path//@blah/", uri.Path);
     Assert.AreEqual(4, uri.Segments.Length);
     Assert.AreEqual(true, uri.TrailingSlash);
     Assert.AreEqual("ready&set=&go=foo/bar", uri.Query);
     Assert.AreEqual("yo", uri.Fragment);
     Assert.AreEqual(original, uri.ToString());
 }
Exemplo n.º 35
0
 public void Can_remove_trailing_slash()
 {
     var uri = new XUri("http://foo/bar/").WithoutTrailingSlash();
     Assert.IsFalse(uri.TrailingSlash);
     Assert.AreEqual("http://foo/bar", uri.ToString());
 }
Exemplo n.º 36
0
 public void TestAppendPath6()
 {
     XUri uri = new XUri("http:///").At("path");
     Assert.AreEqual("/path", uri.Path);
     Assert.AreEqual(1, uri.Segments.Length);
     Assert.AreEqual("http:///path", uri.ToString());
 }
Exemplo n.º 37
0
 public void TestAppendPath2()
 {
     XUri uri = new XUri("http://www.dummy.com:8081/first/second");
     uri = uri.AtPath("/foo/bar");
     Assert.AreEqual("http://www.dummy.com:8081/first/second//foo/bar", uri.ToString());
 }
Exemplo n.º 38
0
        public Yield Invoke(Plug plug, string verb, XUri uri, DreamMessage request, Result<DreamMessage> response)
        {
            Result<DreamMessage> res;

            // register activity
            DreamContext context = DreamContext.CurrentOrNull;
            Action<string> activity;
            if(context != null) {
                activity = new ActivityState(context.Env, verb, uri.ToString()).Message;
            } else {
                activity = delegate(string message) { };
            }
            activity("pre Invoke");
            yield return res = Coroutine.Invoke(HandleInvoke, activity, plug, verb, uri, request, new Result<DreamMessage>(response.Timeout)).Catch();
            activity("post Invoke");

            // unregister activity
            activity(null);

            // return response
            response.Return(res);
        }
Exemplo n.º 39
0
 public void TestAppendQuery2()
 {
     XUri uri = new XUri("http://www.dummy.com:8081/first/second?query=arg");
     uri = uri.With("q", "a");
     Assert.AreEqual("http://www.dummy.com:8081/first/second?query=arg&q=a", uri.ToString());
 }
Exemplo n.º 40
0
 public void TestUriConstructor4()
 {
     string original = "http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]:81/";
     XUri uri = new XUri(original);
     Assert.AreEqual("http", uri.Scheme);
     Assert.AreEqual("[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]", uri.Host);
     Assert.AreEqual(81, uri.Port);
     Assert.AreEqual(false, uri.UsesDefaultPort);
     Assert.AreEqual(null, uri.User);
     Assert.AreEqual(null, uri.Password);
     Assert.AreEqual("/", uri.Path);
     Assert.AreEqual(0, uri.Segments.Length);
     Assert.AreEqual(true, uri.TrailingSlash);
     Assert.AreEqual(null, uri.Query);
     Assert.AreEqual(null, uri.Fragment);
     Assert.AreEqual(original, uri.ToString());
 }
Exemplo n.º 41
0
 public void TestUriConstructor7()
 {
     string original = "http://*****:*****@domain.org:81/path";
     XUri uri = new XUri(original);
     Assert.AreEqual("http", uri.Scheme);
     Assert.AreEqual("domain.org", uri.Host);
     Assert.AreEqual(81, uri.Port);
     Assert.AreEqual(false, uri.UsesDefaultPort);
     Assert.AreEqual("user", uri.User);
     Assert.AreEqual("password", uri.Password);
     Assert.AreEqual("/path", uri.Path);
     Assert.AreEqual(1, uri.Segments.Length);
     Assert.AreEqual(false, uri.TrailingSlash);
     Assert.AreEqual(null, uri.Query);
     Assert.AreEqual(null, uri.Fragment);
     Assert.AreEqual(original, uri.ToString());
 }
Exemplo n.º 42
0
 public void TestUriConstructor24()
 {
     string original = "http://host/seg^ment?qu^ery=a|b^c#fo|o#b^ar";
     XUri uri = new XUri(original);
     Assert.AreEqual("http", uri.Scheme);
     Assert.AreEqual("host", uri.Host);
     Assert.AreEqual(80, uri.Port);
     Assert.AreEqual(true, uri.UsesDefaultPort);
     Assert.AreEqual(null, uri.User);
     Assert.AreEqual(null, uri.Password);
     Assert.AreEqual("/seg^ment", uri.Path);
     Assert.AreEqual(1, uri.Segments.Length);
     Assert.AreEqual(false, uri.TrailingSlash);
     Assert.AreEqual("qu^ery=a|b^c", uri.Query);
     Assert.AreEqual("a|b^c", uri.GetParam("qu^ery"));
     Assert.AreEqual("fo|o#b^ar", uri.Fragment);
     Assert.AreEqual(original, uri.ToString());
 }
Exemplo n.º 43
0
 public void TestUriConstructor23()
 {
     string original = "http:///path";
     XUri uri = new XUri(original);
     Assert.AreEqual("http", uri.Scheme);
     Assert.AreEqual("", uri.Host);
     Assert.AreEqual(80, uri.Port);
     Assert.AreEqual(true, uri.UsesDefaultPort);
     Assert.AreEqual(null, uri.User);
     Assert.AreEqual(null, uri.Password);
     Assert.AreEqual("/path", uri.Path);
     Assert.AreEqual(1, uri.Segments.Length);
     Assert.AreEqual(false, uri.TrailingSlash);
     Assert.AreEqual(null, uri.Query);
     Assert.AreEqual(null, uri.Fragment);
     Assert.AreEqual(original, uri.ToString());
 }
Exemplo n.º 44
0
 public void TestUriConstructor22()
 {
     string original = "http://www.ietf.org/;15/rfc2396.txt;";
     XUri uri = new XUri(original);
     Assert.AreEqual("http", uri.Scheme);
     Assert.AreEqual("www.ietf.org", uri.Host);
     Assert.AreEqual(80, uri.Port);
     Assert.AreEqual(true, uri.UsesDefaultPort);
     Assert.AreEqual(null, uri.User);
     Assert.AreEqual(null, uri.Password);
     Assert.AreEqual("/;15/rfc2396.txt;", uri.Path);
     Assert.AreEqual(2, uri.Segments.Length);
     Assert.AreEqual(";15", uri.Segments[0]);
     Assert.AreEqual("rfc2396.txt;", uri.Segments[1]);
     Assert.AreEqual(false, uri.TrailingSlash);
     Assert.AreEqual(null, uri.Query);
     Assert.AreEqual(null, uri.Fragment);
     Assert.AreEqual(original, uri.ToString());
 }
Exemplo n.º 45
0
 public void TestFragmentEncoding()
 {
     XUri uri = new XUri("http://foo/bar#baz=10");
     Assert.AreEqual("baz=10", uri.Fragment);
     XUri uri2 = new XUri(uri.ToString());
     Assert.AreEqual("baz=10", uri2.Fragment);
 }
Exemplo n.º 46
0
        //--- Constructors ---
        /// <summary>
        /// Create new handler instance
        /// </summary>
        public HttpHandler()
        {
            if(_env == null) {
                lock(SyncRoot) {
                    if(_env == null) {
                        _log.InfoMethodCall("Startup");
                        try {
                            _log.InfoMethodCall("ctor: initializing HttpHandler");
                            NameValueCollection settings = System.Configuration.ConfigurationManager.AppSettings;

                            // determine storage locations
                            string basePath = HttpContext.Current.ApplicationInstance.Server.MapPath("~");
                            string storagePath = settings["storage-dir"] ?? settings["service-dir"];
                            if(string.IsNullOrEmpty(storagePath)) {
                                storagePath = Path.Combine(basePath, "storage");
                            } else if(!Path.IsPathRooted(storagePath)) {
                                storagePath = Path.Combine(basePath, storagePath);
                            }

                            // read configuration
                            string apikey = settings["apikey"];
                            _uri = new XUri(settings["public-uri"] ?? settings["root-uri"] ?? "http://localhost/@api");
                            _minSimilarity = _uri.MaxSimilarity;

                            // start dreamhost
                            XDoc config = new XDoc("config")
                                .Elem("guid", settings["guid"])
                                .Elem("uri.public", _uri.ToString())
                                .Elem("storage-dir", storagePath)
                                .Elem("host-path", settings["host-path"])
                                .Elem("connect-limit", settings["connect-limit"])
                                .Elem("apikey", apikey);
                            IDreamEnvironment env = new DreamHostService();
                            env.Initialize(config);

                            // load assemblies in 'services' folder
                            string servicesFolder = settings["service-dir"] ?? Path.Combine("bin", "services");
                            if(!Path.IsPathRooted(servicesFolder)) {
                                servicesFolder = Path.Combine(basePath, servicesFolder);
                            }
                            _log.DebugFormat("examining services directory '{0}'", servicesFolder);
                            if(Directory.Exists(servicesFolder)) {
                                Plug host = env.Self.With("apikey", apikey);
                                foreach(string file in Directory.GetFiles(servicesFolder, "*.dll")) {
                                    string assembly = Path.GetFileNameWithoutExtension(file);
                                    _log.DebugFormat("attempting to load '{0}'", assembly);

                                    // register assembly blueprints
                                    DreamMessage response = host.At("load").With("name", assembly).Post(new Result<DreamMessage>(TimeSpan.MaxValue)).Wait();
                                    if(!response.IsSuccessful) {
                                        _log.WarnFormat("DreamHost: ERROR: assembly '{0}' failed to load", file);
                                    }
                                }
                            } else {
                                _log.WarnFormat("DreamHost: WARN: no services directory '{0}'", servicesFolder);
                            }

                            // execute script
                            string scriptFilename = settings["script"];
                            if(!string.IsNullOrEmpty(scriptFilename)) {
                                string filename = scriptFilename;
                                if(!Path.IsPathRooted(filename)) {
                                    filename = Path.Combine(basePath, filename);
                                }

                                // execute xml script file
                                XDoc script = XDocFactory.LoadFrom(filename, MimeType.XML);
                                Plug host = env.Self.With("apikey", apikey);
                                host.At("execute").Post(script);
                            }

                            // register plug factory for this uri
                            Plug.AddEndpoint(this);

                            // set _env variable so other constructors don't initialize it anymore
                            _env = env;
                        } catch(Exception e) {
                            _log.ErrorExceptionMethodCall(e, "ctor");
                            throw;
                        }
                    }
                }
            }
        }
Exemplo n.º 47
0
        public void Can_aggregate_from_multiple_dream_hosts()
        {
            // set up hosts
            _log.DebugFormat("---- creating upstream hosts");
            var sourceHost1 = DreamTestHelper.CreateRandomPortHost();
            var source1PubSub = Plug.New(sourceHost1.LocalHost.At("host", "$pubsub").With("apikey", sourceHost1.ApiKey));
            var sourceHost2 = DreamTestHelper.CreateRandomPortHost();
            var source2PubSub = Plug.New(sourceHost2.LocalHost.At("host", "$pubsub").With("apikey", sourceHost2.ApiKey));

            // create aggregator
            _log.DebugFormat("---- creating downstream host");
            var aggregatorPath = "pubsubaggregator";
            var aggregatorHost = DreamTestHelper.CreateRandomPortHost();
            aggregatorHost.Host.RunScripts(new XDoc("config")
                .Start("script").Start("action")
                    .Attr("verb", "POST")
                    .Attr("path", "/host/services")
                    .Start("config")
                        .Elem("path", aggregatorPath)
                        .Elem("sid", "sid://mindtouch.com/dream/2008/10/pubsub")
                        .Elem("apikey", "abc")
                        .Start("upstream")
                            .Elem("uri", source1PubSub.At("subscribers"))
                            .Elem("uri", source2PubSub.At("subscribers"))
                    .End()
                .End().End(), null);
            var aggregatorPubSub = aggregatorHost.LocalHost.At(aggregatorPath).With("apikey", "abc");

            // create subscription
            _log.DebugFormat("---- create downstream subscription");
            var testUri = new XUri("http://mock/aggregator");
            var serviceKey = "1234";
            var accessCookie = DreamCookie.NewSetCookie("service-key", serviceKey, testUri);
            var subscriberApiKey = "xyz";
            var set = new XDoc("subscription-set")
                .Elem("uri.owner", "http:///owner1")
                .Start("subscription")
                    .Attr("id", "1")
                    .Add(accessCookie.AsSetCookieDocument)
                    .Elem("channel", "channel:///foo/*")
                    .Start("recipient")
                        .Attr("authtoken", subscriberApiKey)
                        .Elem("uri", testUri)
                    .End()
                .End();
            var r = aggregatorPubSub.At("subscribers").PostAsync(set).Wait();
            Assert.IsTrue(r.IsSuccessful, r.Status.ToString());
            Assert.AreEqual(DreamStatus.Created, r.Status);

            // Verify that upstream host pubsub services have the subscription
            Func<DreamMessage, bool> waitFunc = response => {
                var sub = response.ToDocument()["subscription-set/subscription[channel='channel:///foo/*']"];
                return (!sub.IsEmpty
                        && sub["recipient/uri"].AsText.EqualsInvariantIgnoreCase(testUri.ToString())
                        && sub["recipient/@authtoken"].AsText.EqualsInvariant(subscriberApiKey));
            };
            Assert.IsTrue(WaitFor(source1PubSub.At("diagnostics", "subscriptions"), waitFunc, TimeSpan.FromSeconds(5)), "source 1 didn't get the subscription");
            Assert.IsTrue(WaitFor(source2PubSub.At("diagnostics", "subscriptions"), waitFunc, TimeSpan.FromSeconds(5)), "source 2 didn't get the subscription");

            // set up destination mock
            DispatcherEvent aggregatorEvent = new DispatcherEvent(
                new XDoc("aggregator"),
                new XUri("channel:///foo/bar"),
                new XUri("http://foobar.com/some/page"));
            DispatcherEvent source1Event = new DispatcherEvent(
                new XDoc("source1"),
                new XUri("channel:///foo/bar"),
                new XUri("http://foobar.com/some/page"));
            DispatcherEvent source2Event = new DispatcherEvent(
                new XDoc("source2"),
                new XUri("channel:///foo/bar"),
                new XUri("http://foobar.com/some/page"));
            var mock = MockPlug.Register(testUri);

            // Publish event into aggregator
            mock.Expect().Verb("POST").RequestDocument(aggregatorEvent.AsDocument());
            r = aggregatorPubSub.At("publish").PostAsync(aggregatorEvent.AsMessage()).Wait();
            Assert.IsTrue(r.IsSuccessful, r.Status.ToString());
            Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(10)), mock.VerificationFailure);

            // Publish event into source1
            mock.Reset();
            mock.Expect().Verb("POST").RequestDocument(source1Event.AsDocument());
            r = source1PubSub.At("publish").PostAsync(source1Event.AsMessage()).Wait();
            Assert.IsTrue(r.IsSuccessful, r.Status.ToString());
            Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(10)), mock.VerificationFailure);

            // Publish event into source2
            mock.Reset();
            mock.Expect().Verb("POST").RequestDocument(source2Event.AsDocument());
            r = source2PubSub.At("publish").PostAsync(source2Event.AsMessage()).Wait();
            Assert.IsTrue(r.IsSuccessful, r.Status.ToString());
            Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(10)), mock.VerificationFailure);
        }
Exemplo n.º 48
0
 public void Can_append_trailing_slash()
 {
     var uri = new XUri("http://foo/bar").WithTrailingSlash();
     Assert.IsTrue(uri.TrailingSlash);
     Assert.AreEqual("http://foo/bar/", uri.ToString());
 }
Exemplo n.º 49
0
 public void TestAppendPath8()
 {
     XUri uri = new XUri("http:///").AtAbsolutePath("foo/bar/");
     Assert.AreEqual("/foo/bar/", uri.Path);
     Assert.AreEqual(2, uri.Segments.Length);
     Assert.AreEqual("http:///foo/bar/", uri.ToString());
 }
Exemplo n.º 50
0
 public void WithTrailingSlash_only_adds_when_needed()
 {
     var uri = new XUri("http://foo/bar/");
     Assert.IsTrue(uri.TrailingSlash);
     uri = uri.WithTrailingSlash();
     Assert.IsTrue(uri.TrailingSlash);
     Assert.AreEqual("http://foo/bar/", uri.ToString());
 }
Exemplo n.º 51
0
 public void TestAppendPath4()
 {
     XUri uri = new XUri("http://www.dummy.com:8081/first/second?query=arg");
     uri = uri.AtPath("foo/bar?q=a");
     Assert.AreEqual("http://www.dummy.com:8081/first/second/foo/bar?query=arg&q=a", uri.ToString());
 }
Exemplo n.º 52
0
 public void Windows_network_file_path_uri_with_backslashes()
 {
     XUri uri = new XUri(@"file:///\\deki-hayes\drive");
     Assert.AreEqual("file://///deki-hayes/drive", uri.ToString());
 }
Exemplo n.º 53
0
 public void Can_roundtrip_GetRelativePathTo_via_AtPath_with_trailing_slash_on_uri()
 {
     var uri = new XUri("http://foo/a/b/c/");
     var baseUri = new XUri("http://foo/a");
     var relative = uri.GetRelativePathTo(baseUri);
     var roundtrip = baseUri.AtPath(relative);
     Assert.AreEqual(uri.ToString(), roundtrip.ToString());
 }
Exemplo n.º 54
0
 public void TestUriConstructor17()
 {
     string original = "ftp://cnn.example.com&[email protected]/top_story.htm#";
     XUri uri = new XUri(original);
     Assert.AreEqual("ftp", uri.Scheme);
     Assert.AreEqual("10.0.0.1", uri.Host);
     Assert.AreEqual(21, uri.Port);
     Assert.AreEqual(true, uri.UsesDefaultPort);
     Assert.AreEqual("cnn.example.com&story=breaking_news", uri.User);
     Assert.AreEqual(null, uri.Password);
     Assert.AreEqual("/top_story.htm", uri.Path);
     Assert.AreEqual(1, uri.Segments.Length);
     Assert.AreEqual(false, uri.TrailingSlash);
     Assert.AreEqual(null, uri.Query);
     Assert.AreEqual("", uri.Fragment);
     Assert.AreEqual(original, uri.ToString());
 }
Exemplo n.º 55
0
 public void WithoutTrailingSlash_only_removes_when_needed()
 {
     var uri = new XUri("http://foo/bar");
     Assert.IsFalse(uri.TrailingSlash);
     uri = uri.WithoutTrailingSlash();
     Assert.IsFalse(uri.TrailingSlash);
     Assert.AreEqual("http://foo/bar", uri.ToString());
 }
Exemplo n.º 56
0
 public void Get_via_internal_routing_and_AutoRedirect_off_shows_302()
 {
     using(var hostInfo = DreamTestHelper.CreateRandomPortHost()) {
         var mock = MockService.CreateMockService(hostInfo);
         var redirectCalled = 0;
         var redirectUri = new XUri("mock://foo/bar");
         mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
             var msg = "nothing here";
             if(context.Uri.LastSegment == "redirect") {
                 _log.Debug("called redirect");
                 redirectCalled++;
                 response.Return(DreamMessage.Redirect(redirectUri));
                 return;
             }
             _log.DebugFormat("called uri: {0} => {1}", context.Uri, msg);
             response.Return(DreamMessage.NotFound(msg));
         };
         var uri = mock.AtLocalMachine.At("redirect");
         _log.DebugFormat("calling redirect service at {0}", uri);
         var r = Plug.New(uri).WithHeader("h", "y").WithoutAutoRedirects().GetAsync().Wait();
         Assert.AreEqual(DreamStatus.Found, r.Status, r.HasDocument ? r.ToDocument()["message"].AsText : "request failed: " + r.Status);
         Assert.AreEqual(1, redirectCalled, "redirect called incorrectly");
         Assert.AreEqual(redirectUri.ToString(), r.Headers.Location.ToString());
     }
 }
Exemplo n.º 57
0
 public void TestToStringFalse()
 {
     XUri uri = new XUri("http://*****:*****@hostname/path");
     Assert.AreEqual("http://*****:*****@hostname/path", uri.ToString(false), "ToString(false)");
 }
Exemplo n.º 58
0
 public void TestSetPath2()
 {
     XUri uri = new XUri("http://www.dummy.com:8081/first/second?query=arg");
     uri = uri.AtAbsolutePath("/foo/bar?q=a");
     Assert.AreEqual("http://www.dummy.com:8081/foo/bar?q=a", uri.ToString());
 }
Exemplo n.º 59
0
 public void TestUriConstructor16()
 {
     string original = "telnet://192.0.2.16:80/";
     XUri uri = new XUri(original);
     Assert.AreEqual("telnet", uri.Scheme);
     Assert.AreEqual("192.0.2.16", uri.Host);
     Assert.AreEqual(80, uri.Port);
     Assert.AreEqual(false, uri.UsesDefaultPort);
     Assert.AreEqual(null, uri.User);
     Assert.AreEqual(null, uri.Password);
     Assert.AreEqual("/", uri.Path);
     Assert.AreEqual(0, uri.Segments.Length);
     Assert.AreEqual(true, uri.TrailingSlash);
     Assert.AreEqual(null, uri.Query);
     Assert.AreEqual(null, uri.Fragment);
     Assert.AreEqual(original, uri.ToString());
 }
Exemplo n.º 60
0
 public void TestUriConstructor13()
 {
     string original = "ftp://ftp.is.co.za/rfc/rfc1808.txt";
     XUri uri = new XUri(original);
     Assert.AreEqual("ftp", uri.Scheme);
     Assert.AreEqual("ftp.is.co.za", uri.Host);
     Assert.AreEqual(21, uri.Port);
     Assert.AreEqual(true, uri.UsesDefaultPort);
     Assert.AreEqual(null, uri.User);
     Assert.AreEqual(null, uri.Password);
     Assert.AreEqual("/rfc/rfc1808.txt", uri.Path);
     Assert.AreEqual(2, uri.Segments.Length);
     Assert.AreEqual(false, uri.TrailingSlash);
     Assert.AreEqual(null, uri.Query);
     Assert.AreEqual(null, uri.Fragment);
     Assert.AreEqual(original, uri.ToString());
 }