예제 #1
0
 /// <summary>Parses the authority for the pre-parsed given Url.</summary>
 /// <remarks>Parses the authority for the pre-parsed given Url.</remarks>
 /// <param name="parsed">the pre-parsed Url.</param>
 private static void ParseAuthority(Url parsed)
 {
     // parse authority for unparsed relative network-path reference
     if (parsed.href.IndexOf(":") == -1 && parsed.href.IndexOf("//") == 0 && string.Empty
         .Equals(parsed.host))
     {
         // must parse authority from pathname
         parsed.pathname = JavaCompat.Substring(parsed.pathname, 2);
         var idx = parsed.pathname.IndexOf("/");
         if (idx == -1)
         {
             parsed.authority = parsed.pathname;
             parsed.pathname  = string.Empty;
         }
         else
         {
             parsed.authority = JavaCompat.Substring(parsed.pathname, 0, idx);
             parsed.pathname  = JavaCompat.Substring(parsed.pathname, idx);
         }
     }
     else
     {
         // construct authority
         parsed.authority = parsed.host;
         if (!string.Empty.Equals(parsed.auth))
         {
             parsed.authority = parsed.auth + "@" + parsed.authority;
         }
     }
 }
예제 #2
0
            /// <exception cref="JsonLD.Core.JsonLdError"></exception>
            private void AdvanceLineNumber()
            {
                var match = Regex.NextEoln.Matcher(line);

                if (match.Find())
                {
                    var split = match.Group(0).Split(string.Empty + Regex.Eoln);
                    lineNumber   += split.Length - 1;
                    linePosition += split[split.Length - 1].Length;
                    line          = JavaCompat.Substring(line, match.Group(0).Length);
                }
            }
예제 #3
0
 public void update(int foo)
 {
     /*
      * byte[] b = JavaCompat.GetBytesBig(foo);
      * Console.Error.Write("HMAC: ");
      * for (int i = 0; i < b.Length; i++)
      * {
      *  Console.Error.Write(b[i].ToString("X2"));
      * }
      * Console.Error.WriteLine(" (" + foo.ToString() + ")");*/
     cs.Write(JavaCompat.GetBytesBig(foo));
 }
예제 #4
0
        private string UnquoteString(string value)
        {
            if (value.StartsWith("\"\"\"") || value.StartsWith("'''"))
            {
                return(JavaCompat.Substring(value, 3, value.Length - 3));
            }

            if (value.StartsWith("\"") || value.StartsWith("'"))
            {
                return(JavaCompat.Substring(value, 1, value.Length - 1));
            }
            return(value);
        }
예제 #5
0
        /// <summary>
        ///     checks the URI for a prefix, and if one is found, set used prefixes to
        ///     true
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        private string GetURI(string uri)
        {
            // check for bnode
            if (uri.StartsWith("_:"))
            {
                return(uri);
            }
            foreach (var prefix in availableNamespaces.Keys)
            {
                if (uri.StartsWith(prefix))
                {
                    usedNamespaces.Add(prefix);

                    // return the prefixed URI
                    return(availableNamespaces[prefix] + ":" + JavaCompat.Substring(uri, prefix.Length));
                }
            }

            // return the full URI
            return("<" + uri + ">");
        }
예제 #6
0
        /// <summary>A helper class to sha1 hash all the strings in a collection</summary>
        /// <param name="nquads"></param>
        /// <returns></returns>
        private static string Sha1hash(ICollection <string> nquads)
        {
#if !PORTABLE
            try
            {
                // create SHA-1 digest
                var md = MessageDigest.GetInstance("SHA-1");
                foreach (var nquad in nquads)
                {
                    md.Update(JavaCompat.GetBytesForString(nquad, "UTF-8"));
                }
                return(EncodeHex(md.Digest()));
            }
            catch
            {
                throw;
            }
#else
            throw new PlatformNotSupportedException();
#endif
        }
예제 #7
0
            /// <exception cref="JsonLD.Core.JsonLdError"></exception>
            public virtual void AdvanceLinePosition(int len)
            {
                if (len > 0)
                {
                    linePosition += len;
                    line          = JavaCompat.Substring(line, len);
                }

                while (!string.Empty.Equals(line))
                {
                    // clear any whitespace
                    var match = Regex.CommentOrWs.Matcher(line);
                    if (match.Find() && match.Group(0).Length > 0)
                    {
                        var eoln = Regex.Eoln.Matcher(match.Group(0));
                        var end  = 0;
                        while (eoln.Find())
                        {
                            lineNumber += 1;
                            end         = eoln.End();
                        }

                        linePosition = match.Group(0).Length - end;
                        line         = JavaCompat.Substring(line, match.Group(0).Length);
                    }
                    else
                    {
                        break;
                    }
                }

                if (string.Empty.Equals(line) && !EndIsOK())
                {
                    throw new JsonLdError(JsonLdError.Error.ParseError,
                                          "Error while parsing Turtle; unexpected end of input. {line: "
                                          + lineNumber + ", position:" + linePosition + "}");
                }
            }
예제 #8
0
        public static string RemoveBase(JToken baseobj, string iri)
        {
            if (baseobj.IsNull())
            {
                return(iri);
            }
            Url @base;

            if (baseobj.Type == JTokenType.String)
            {
                @base = Parse((string)baseobj);
            }
            else
            {
                throw new Exception("Arrgggghhh!");
            }

            // establish base root
            var root = string.Empty;

            if (!string.Empty.Equals(@base.href))
            {
                root += @base.protocol + "//" + @base.authority;
            }
            else
            {
                // support network-path reference with empty base
                if (iri.IndexOf("//") != 0)
                {
                    root += "//";
                }
            }

            // IRI not relative to base
            if (iri.IndexOf(root) != 0)
            {
                return(iri);
            }

            // remove root from IRI and parse remainder
            var rel = Parse(JavaCompat.Substring(iri, root.Length));

            // remove path segments that match
            IList <string> baseSegments = new List <string>(@base
                                                            .normalizedPath.Split("/").ToList());

            baseSegments = baseSegments.Where(seg => seg != "").ToList();
            if (@base.normalizedPath.EndsWith("/"))
            {
                baseSegments.Add(string.Empty);
            }
            IList <string> iriSegments = new List <string>(rel.normalizedPath
                                                           .Split("/").ToList());

            iriSegments = iriSegments.Where(seg => seg != "").ToList();
            if (rel.normalizedPath.EndsWith("/"))
            {
                iriSegments.Add(string.Empty);
            }
            while (baseSegments.Count > 0 && iriSegments.Count > 0)
            {
                if (!baseSegments[0].Equals(iriSegments[0]))
                {
                    break;
                }
                if (baseSegments.Count > 0)
                {
                    baseSegments.RemoveAt(0);
                }
                if (iriSegments.Count > 0)
                {
                    iriSegments.RemoveAt(0);
                }
            }

            // use '../' for each non-matching base segment
            var rval = string.Empty;

            if (baseSegments.Count > 0)
            {
                // don't count the last segment if it isn't a path (doesn't end in
                // '/')
                // don't count empty first segment, it means base began with '/'
                if ([email protected]("/") || string.Empty.Equals(baseSegments[0]))
                {
                    baseSegments.RemoveAt(baseSegments.Count - 1);
                }
                for (var i = 0; i < baseSegments.Count; ++i)
                {
                    rval += "../";
                }
            }

            // prepend remaining segments
            if (iriSegments.Count > 0)
            {
                rval += iriSegments[0];
            }
            for (var i_1 = 1; i_1 < iriSegments.Count; i_1++)
            {
                rval += "/" + iriSegments[i_1];
            }

            // add query and hash
            if (!string.Empty.Equals(rel.query))
            {
                rval += "?" + rel.query;
            }
            if (!string.Empty.Equals(rel.hash))
            {
                rval += rel.hash;
            }
            if (string.Empty.Equals(rval))
            {
                rval = "./";
            }
            return(rval);
        }
예제 #9
0
 public void update(int foo)
 {
     cs.Write(JavaCompat.GetBytesBig(foo));
 }
예제 #10
0
        /// <summary>
        ///     Produces a hash for the paths of adjacent bnodes for a bnode,
        ///     incorporating all information about its subgraph of bnodes.
        /// </summary>
        /// <remarks>
        ///     Produces a hash for the paths of adjacent bnodes for a bnode,
        ///     incorporating all information about its subgraph of bnodes. This method
        ///     will recursively pick adjacent bnode permutations that produce the
        ///     lexicographically-least 'path' serializations.
        /// </remarks>
        /// <param name="id">the ID of the bnode to hash paths for.</param>
        /// <param name="bnodes">the map of bnode quads.</param>
        /// <param name="namer">the canonical bnode namer.</param>
        /// <param name="pathNamer">the namer used to assign names to adjacent bnodes.</param>
        /// <param name="callback">(err, result) called once the operation completes.</param>
        private static HashResult HashPaths(string id,
                                            IDictionary <string, IDictionary <string, object> > bnodes,
                                            UniqueNamer namer,
                                            UniqueNamer pathNamer)
        {
#if !PORTABLE
            MessageDigest md = null;

            try
            {
                // create SHA-1 digest
                md = MessageDigest.GetInstance("SHA-1");
                var            groups = new JObject();
                IList <string> groupHashes;
                var            quads = (IList <RdfDataset.Quad>)bnodes[id]["quads"];
                for (var hpi = 0;; hpi++)
                {
                    if (hpi == quads.Count)
                    {
                        // done , hash groups
                        groupHashes = new List <string>(groups.GetKeys());
                        ((List <string>)groupHashes).Sort(StringComparer.CurrentCultureIgnoreCase);
                        for (var hgi = 0;; hgi++)
                        {
                            if (hgi == groupHashes.Count)
                            {
                                var res = new HashResult();
                                res.hash      = EncodeHex(md.Digest());
                                res.pathNamer = pathNamer;
                                return(res);
                            }

                            // digest group hash
                            var groupHash = groupHashes[hgi];
                            md.Update(JavaCompat.GetBytesForString(groupHash, "UTF-8"));

                            // choose a path and namer from the permutations
                            string      chosenPath  = null;
                            UniqueNamer chosenNamer = null;
                            var         permutator  = new Permutator((JArray)groups[groupHash]);
                            while (true)
                            {
                                var contPermutation = false;
                                var breakOut        = false;
                                var permutation     = permutator.Next();
                                var pathNamerCopy   = pathNamer.Clone();

                                // build adjacent path
                                var path    = string.Empty;
                                var recurse = new JArray();
                                foreach (string bnode in permutation)
                                {
                                    // use canonical name if available
                                    if (namer.IsNamed(bnode))
                                    {
                                        path += namer.GetName(bnode);
                                    }
                                    else
                                    {
                                        // recurse if bnode isn't named in the path
                                        // yet
                                        if (!pathNamerCopy.IsNamed(bnode))
                                        {
                                            recurse.Add(bnode);
                                        }
                                        path += pathNamerCopy.GetName(bnode);
                                    }

                                    // skip permutation if path is already >= chosen
                                    // path
                                    if (chosenPath != null && path.Length >= chosenPath.Length && string.CompareOrdinal(path, chosenPath) > 0)
                                    {
                                        // return nextPermutation(true);
                                        if (permutator.HasNext())
                                        {
                                            contPermutation = true;
                                        }
                                        else
                                        {
                                            // digest chosen path and update namer
                                            md.Update(JavaCompat.GetBytesForString(chosenPath, "UTF-8"));
                                            pathNamer = chosenNamer;

                                            // hash the nextGroup
                                            breakOut = true;
                                        }

                                        break;
                                    }
                                }

                                // if we should do the next permutation
                                if (contPermutation)
                                {
                                    continue;
                                }

                                // if we should stop processing this group
                                if (breakOut)
                                {
                                    break;
                                }

                                // does the next recursion
                                for (var nrn = 0;; nrn++)
                                {
                                    if (nrn == recurse.Count)
                                    {
                                        // return nextPermutation(false);
                                        if (chosenPath == null || string.CompareOrdinal(path, chosenPath) < 0)
                                        {
                                            chosenPath  = path;
                                            chosenNamer = pathNamerCopy;
                                        }

                                        if (!permutator.HasNext())
                                        {
                                            // digest chosen path and update namer
                                            md.Update(JavaCompat.GetBytesForString(chosenPath, "UTF-8"));
                                            pathNamer = chosenNamer;

                                            // hash the nextGroup
                                            breakOut = true;
                                        }

                                        break;
                                    }

                                    // do recursion
                                    var bnode_1 = (string)recurse[nrn];
                                    var result  = HashPaths(bnode_1, bnodes, namer, pathNamerCopy);
                                    path         += pathNamerCopy.GetName(bnode_1) + "<" + result.hash + ">";
                                    pathNamerCopy = result.pathNamer;

                                    // skip permutation if path is already >= chosen
                                    // path
                                    if (chosenPath != null && path.Length >= chosenPath.Length && string.CompareOrdinal(path, chosenPath) > 0)
                                    {
                                        // return nextPermutation(true);
                                        if (!permutator.HasNext())
                                        {
                                            // digest chosen path and update namer
                                            md.Update(JavaCompat.GetBytesForString(chosenPath, "UTF-8"));
                                            pathNamer = chosenNamer;

                                            // hash the nextGroup
                                            breakOut = true;
                                        }

                                        break;
                                    }
                                }

                                // do next recursion
                                // if we should stop processing this group
                                if (breakOut)
                                {
                                    break;
                                }
                            }
                        }
                    }

                    // get adjacent bnode
                    var quad    = (IDictionary <string, object>)quads[hpi];
                    var bnode_2 = GetAdjacentBlankNodeName((IDictionary <string, object>)quad["subject"
                                                           ],
                                                           id);
                    string direction = null;
                    if (bnode_2 != null)
                    {
                        // normal property
                        direction = "p";
                    }
                    else
                    {
                        bnode_2 = GetAdjacentBlankNodeName((IDictionary <string, object>)quad["object"],
                                                           id
                                                           );
                        if (bnode_2 != null)
                        {
                            direction = "r";
                        }
                    }

                    if (bnode_2 != null)
                    {
                        // get bnode name (try canonical, path, then hash)
                        string name;
                        if (namer.IsNamed(bnode_2))
                        {
                            name = namer.GetName(bnode_2);
                        }
                        else
                        {
                            if (pathNamer.IsNamed(bnode_2))
                            {
                                name = pathNamer.GetName(bnode_2);
                            }
                            else
                            {
                                name = HashQuads(bnode_2, bnodes, namer);
                            }
                        }

                        // hash direction, property, end bnode name/hash
                        using (var md1 = MessageDigest.GetInstance("SHA-1"))
                        {
                            // String toHash = direction + (String) ((Map<String,
                            // Object>) quad.get("predicate")).get("value") + name;
                            md1.Update(JavaCompat.GetBytesForString(direction, "UTF-8"));
                            md1.Update(JavaCompat.GetBytesForString((string)((IDictionary <string, object>)quad["predicate"])["value"], "UTF-8"));
                            md1.Update(JavaCompat.GetBytesForString(name, "UTF-8"));
                            var groupHash = EncodeHex(md1.Digest());
                            if (groups.ContainsKey(groupHash))
                            {
                                ((JArray)groups[groupHash]).Add(bnode_2);
                            }
                            else
                            {
                                var tmp = new JArray();
                                tmp.Add(bnode_2);
                                groups[groupHash] = tmp;
                            }
                        }
                    }
                }
            }
            catch
            {
                // TODO: i don't expect that SHA-1 is even NOT going to be
                // available?
                // look into this further
                throw;
            }
            finally
            {
                md?.Dispose();
            }
#else
            throw new PlatformNotSupportedException();
#endif
        }
예제 #11
0
        /// <summary>Removes a base IRI from the given absolute IRI.</summary>
        /// <remarks>Removes a base IRI from the given absolute IRI.</remarks>
        /// <param name="base">the base IRI.</param>
        /// <param name="iri">the absolute IRI.</param>
        /// <returns>the relative IRI if relative to base, otherwise the absolute IRI.</returns>
        private static string RemoveBase(JToken baseobj, string iri)
        {
            Url @base;

            if (IsString(baseobj))
            {
                @base = Url.Parse((string)baseobj);
            }
            else
            {
                @base = baseobj.Value <Url>();
            }

            // establish base root
            var root = string.Empty;

            if (!string.Empty.Equals(@base.href))
            {
                root += @base.protocol + "//" + @base.authority;
            }
            else
            {
                // support network-path reference with empty base
                if (iri.IndexOf("//") != 0)
                {
                    root += "//";
                }
            }

            // IRI not relative to base
            if (iri.IndexOf(root) != 0)
            {
                return(iri);
            }

            // remove root from IRI and parse remainder
            var rel = Url.Parse(JavaCompat.Substring(iri, root.Length));

            // remove path segments that match
            var baseSegments = _split(@base.normalizedPath, "/");
            var iriSegments  = _split(rel.normalizedPath, "/");

            while (baseSegments.Count > 0 && iriSegments.Count > 0)
            {
                if (!baseSegments[0].Equals(iriSegments[0]))
                {
                    break;
                }
                if (baseSegments.Count > 0)
                {
                    baseSegments.RemoveAt(0);
                }
                if (iriSegments.Count > 0)
                {
                    iriSegments.RemoveAt(0);
                }
            }

            // use '../' for each non-matching base segment
            var rval = string.Empty;

            if (baseSegments.Count > 0)
            {
                // don't count the last segment if it isn't a path (doesn't end in
                // '/')
                // don't count empty first segment, it means base began with '/'
                if ([email protected]("/") || string.Empty.Equals(baseSegments[0]))
                {
                    baseSegments.RemoveAt(baseSegments.Count - 1);
                }
                for (var i = 0; i < baseSegments.Count; ++i)
                {
                    rval += "../";
                }
            }

            // prepend remaining segments
            rval += _join(iriSegments, "/");

            // add query and hash
            if (!string.Empty.Equals(rel.query))
            {
                rval += "?" + rel.query;
            }
            if (!string.Empty.Equals(rel.hash))
            {
                rval += rel.hash;
            }
            if (string.Empty.Equals(rval))
            {
                rval = "./";
            }
            return(rval);
        }
예제 #12
0
        /// <summary>Prepends a base IRI to the given relative IRI.</summary>
        /// <remarks>Prepends a base IRI to the given relative IRI.</remarks>
        /// <param name="base">the base IRI.</param>
        /// <param name="iri">the relative IRI.</param>
        /// <returns>
        ///     the absolute IRI.
        ///     TODO: the Url class isn't as forgiving as the Node.js url parser,
        ///     we may need to re-implement the parser here to support the
        ///     flexibility required
        /// </returns>
        private static string PrependBase(JToken baseobj, string iri)
        {
            // already an absolute IRI
            if (iri.IndexOf(":") != -1)
            {
                return(iri);
            }

            // parse base if it is a string
            Url @base;

            if (IsString(baseobj))
            {
                @base = Url.Parse((string)baseobj);
            }
            else
            {
                @base = baseobj.Value <Url>();
            }
            var rel = Url.Parse(iri);

            // start hierarchical part
            var hierPart = @base.protocol;

            if (!string.Empty.Equals(rel.authority))
            {
                hierPart += "//" + rel.authority;
            }
            else
            {
                if (!string.Empty.Equals(@base.href))
                {
                    hierPart += "//" + @base.authority;
                }
            }

            // per RFC3986 normalize
            string path;

            // IRI represents an absolute path
            if (rel.pathname.IndexOf("/") == 0)
            {
                path = rel.pathname;
            }
            else
            {
                path = @base.pathname;

                // append relative path to the end of the last directory from base
                if (!string.Empty.Equals(rel.pathname))
                {
                    path = JavaCompat.Substring(path, 0, path.LastIndexOf("/") + 1);
                    if (path.Length > 0 && !path.EndsWith("/"))
                    {
                        path += "/";
                    }
                    path += rel.pathname;
                }
            }

            // remove slashes anddots in path
            path = Url.RemoveDotSegments(path, !string.Empty.Equals(hierPart));

            // add query and hash
            if (!string.Empty.Equals(rel.query))
            {
                path += "?" + rel.query;
            }
            if (!string.Empty.Equals(rel.hash))
            {
                path += rel.hash;
            }
            var rval = hierPart + path;

            if (string.Empty.Equals(rval))
            {
                return("./");
            }
            return(rval);
        }
예제 #13
0
        public static string Unescape(string str)
        {
            var rval = str;

            if (str != null)
            {
                var m = UcharMatched.Matcher(str);
                while (m.Find())
                {
                    var uni = m.Group(0);
                    if (m.Group(1) == null)
                    {
                        var hex = m.Group(2) != null?m.Group(2) : m.Group(3);

                        var v = Convert.ToInt32(hex, 16);

                        // hex =
                        // hex.replaceAll("^(?:00)+",
                        // "");
                        if (v > 0xFFFF)
                        {
                            // deal with UTF-32
                            // Integer v = Integer.parseInt(hex, 16);
                            var vt = v - 0x10000;
                            var vh = vt >> 10;
                            var v1 = vt & 0x3FF;
                            var w1 = 0xD800 + vh;
                            var w2 = 0xDC00 + v1;
                            var b  = new StringBuilder();
                            b.AppendCodePoint(w1);
                            b.AppendCodePoint(w2);
                            uni = b.ToString();
                        }
                        else
                        {
                            uni = char.ToString((char)v);
                        }
                    }
                    else
                    {
                        var c = m.Group(1)[0];
                        switch (c)
                        {
                        case 'b':
                        {
                            uni = "\b";
                            break;
                        }

                        case 'n':
                        {
                            uni = "\n";
                            break;
                        }

                        case 't':
                        {
                            uni = "\t";
                            break;
                        }

                        case 'f':
                        {
                            uni = "\f";
                            break;
                        }

                        case 'r':
                        {
                            uni = "\r";
                            break;
                        }

                        case '\'':
                        {
                            uni = "'";
                            break;
                        }

                        case '\"':
                        {
                            uni = "\"";
                            break;
                        }

                        case '\\':
                        {
                            uni = "\\";
                            break;
                        }

                        default:
                        {
                            // do nothing
                            continue;
                        }
                        }
                    }

                    var pat = Pattern.Quote(m.Group(0));
                    var x   = JavaCompat.ToHexString(uni[0]);
                    rval = rval.Replace(pat, uni);
                }
            }

            return(rval);
        }