コード例 #1
0
        //private static bool isFileSystemUri(string uriString)
        //{
        //    Uri uriResult;

        //    return result;
        //}

        public static bool FetchSingle(string url, out object resource)
        {
            //TODO: how to handle relative files/paths?
            // use cd to determine exactly how to process relative paths
            Uri uri;

            if (string.IsNullOrEmpty(url))
            {
                resource = null;
                return(false);
            }

            if (url.StartsWith(X3DTypeConverters.URN_WEB3D_MEDIA))
            {
                //TODO: database drive common URNs
                //TODO: make an assett store making use of URNs

                url = url.Remove(0, X3DTypeConverters.URN_WEB3D_MEDIA.Length);
                url = url.TrimStart();

                url = "http://www.web3d.org/WorkingGroups/media/" + url; // bad to hard code URNs
            }
            else if (url.StartsWith(X3DTypeConverters.URN))
            {
                Console.WriteLine("TODO: cant handle this URN {0}", url);
                resource = null;
                return(false);
            }

            string tmp = X3DTypeConverters.removeQuotes(url);

            if (tmp.StartsWith(X3DTypeConverters.DATA_TEXT_PLAIN))
            {
                //TODO: complete implementation of data:uri as seen in https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs

                string dataTextPlain = tmp.Remove(0, X3DTypeConverters.DATA_TEXT_PLAIN.Length);
                dataTextPlain = dataTextPlain.TrimStart();

                MemoryStream stream = new MemoryStream();
                StreamWriter writer = new StreamWriter(stream);
                writer.Write(dataTextPlain);
                writer.Flush();
                stream.Position = 0;

                resource = stream;

                return(true);
            }

            url = X3DTypeConverters.removeQuotes(url);

            if (!CapabilityEnabled(System.IO.Path.GetExtension(url)))
            {
                switch (System.Windows.Forms.MessageBox.Show("File Extension of type " + System.IO.Path.GetExtension(url) + " is not implemented yet", "Not imp", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Information))
                {
                case System.Windows.Forms.DialogResult.Yes:
                    break;

                case System.Windows.Forms.DialogResult.No:
                    System.Windows.Forms.MessageBox.Show("Perhaps this feature will be implemented soon");
                    break;
                }
                resource = null;
                return(false);
            }

            if (url.ToLower().StartsWith("file://"))
            {
                if (url.ToLower().StartsWith("file:///"))
                {
                    url = url.Remove(0, 8);
                }
                else
                {
                    url = url.Remove(0, 7);
                }
                url.Replace('/', '\\');
            }

            if (GetMIMETypeByURL(url) != X3DMIMEType.UNKNOWN)
            {
                // File is an X3D compatible Scene Graph .x3d, .x3db, .vrml etc

                //if (string.IsNullOrEmpty(SceneManager.CurrentLocation))
                //{
                //SceneManager.CurrentLocation = (new System.IO.DirectoryInfo(url)).Parent.FullName;
                //}

                // get the current path to the html document
                set_cd(BaseURL);
                // what if the *.x3d file is a relative address and no CurrentLocation can be found??? SEE THIS X3D example:
                // http://www.web3d.org/x3d/content/examples/Conformance/Appearance/ImageTexture/_pages/page13.html
                //http://www.web3d.org/x3d/content/examples/Conformance/Appearance/ImageTexture/ElevationGrid.x3d
            }

            //if(GetMIMETypeByURL(url)!=X3DMIMEType.UNKNOWN) {
            //CurrentLocation=url.TrimEnd().TrimEnd(System.IO.Path.GetFileName(url).ToCharArray());
            //}
            Uri www_url;
            Uri base_uri;

            //MessageBox.Show("for debugging purposes..");

            if (isrelative(url))
            {
                if (isWebUrl(CurrentLocation))
                {
                    url = url.Replace("\\", "/");
                }
                else
                {
                    url = url.Replace("/", "\\");
                }


                if (url.StartsWith("/"))
                {
                    url = "." + url;
                }


                if (!isWebUrl(CurrentLocation) && isrelative(url))
                {
                    // Is on the file system. Unix or Windows.

                    url = SceneManager.CurrentLocation
                          + (SceneManager.CurrentLocation.EndsWith("\\") ? "" : "\\")
                          + url;
                }
                else if (isWebUrl(CurrentLocation) && isrelative(url))
                {
                    if (string.IsNullOrEmpty(SceneManager.CurrentLocation))
                    {
                        SceneManager.CurrentLocation = (new System.IO.DirectoryInfo(url)).Parent.FullName;
                    }

                    base_uri = new Uri(CurrentLocation);

                    if (Uri.TryCreate(base_uri, url, out www_url))
                    {
                        url = www_url.ToString();
                        if (System.IO.Path.GetFileName(url) == System.IO.Path.GetFileName(BaseURL))
                        {
                            url = BaseURL;
                        }
                    }
                    else
                    {
                        Console.WriteLine("** panic ** cant handle this url {0}", url);
                        resource = null;
                        return(false);
                    }
                }
            }

            if (url.ToLower().StartsWith("file://"))
            {
                if (url.ToLower().StartsWith("file:///"))
                {
                    url = url.Remove(0, 8);
                }
                else
                {
                    url = url.Remove(0, 7);
                }
                url.Replace('/', '\\');
            }


            uri = new Uri(url);

            if (uri.IsFile)
            {
                // it should be a file on the local file system

                if (File.Exists(url))
                {
                    //FileStream fs = File.OpenRead(url);
                    //string txt = File.ReadAllText(url);

                    // Replace line endings because XDocument, and XMLDocument dont handle them well inside attribute values
                    //txt = txt.Replace("\r\n", "\n")
                    //         .Replace("\r", "\n")
                    //         .Replace("\n", "
"); // 
   




                    byte[] bytes;

                    //bytes = UTF8Encoding.UTF8.GetBytes(txt);
                    bytes = File.ReadAllBytes(url);

                    // Read all bytes now so that we quickly loose lock to file
                    MemoryStream ms = new MemoryStream(bytes);

                    X3DMIMEType mimeType = GetMIMETypeByURL(url);

                    switch (mimeType)
                    {
                    case X3DMIMEType.UNKNOWN:
                        resource = (Stream)ms;
                        break;

                    case X3DMIMEType.X3D:
                        resource = fromStream((Stream)ms);
                        break;

                    case X3DMIMEType.X3DBinary:
                        resource = fromStream((Stream)ms, mimeType);
                        break;

                    default:
                        resource = null;
                        break;
                    }
                    return(true);
                }
                else
                {
                    resource = null;
                    return(false);
                }
            }
            else
            {
                HttpWebRequest  request;
                HttpWebResponse response;
                X3DMIMEType     m;

                request = (HttpWebRequest)WebRequest.Create(url);

                request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
                request.CachePolicy         = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
                request.KeepAlive           = true;
                request.Timeout             = 10000;
                request.ReadWriteTimeout    = 32000;
                request.Method = "GET";
                //request.Method="post";
                //request.ContentType = "text/plain";
                //request.UserAgent = "x3d-finely-sharpened-3.3";

                byte[]       lnBuffer, lnFile;
                MemoryStream fileStream  = null;
                string       contentType = string.Empty;

                try
                {
                    using (response = (HttpWebResponse)request.GetResponse())
                    {
                        // Handle the response now and buffer quickly into local cache ..
                        contentType = response.ContentType;

                        using (BinaryReader lxBR = new BinaryReader(response.GetResponseStream()))
                        {
                            using (MemoryStream lxMS = new MemoryStream())
                            {
                                lnBuffer = lxBR.ReadBytes(1024);
                                while (lnBuffer.Length > 0)
                                {
                                    lxMS.Write(lnBuffer, 0, lnBuffer.Length);
                                    lnBuffer = lxBR.ReadBytes(1024);
                                }
                                lnFile        = new byte[(int)lxMS.Length];
                                lxMS.Position = 0;
                                lxMS.Read(lnFile, 0, lnFile.Length);
                            }
                        }

                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            fileStream = new MemoryStream(lnFile, false);
                        }
                        else
                        {
                            resource = null;
                            return(false);
                        }
                    }


                    // Response is closed off and we have now a cached copy of it in a MemoryStream
                    // This process usually avoids timeouts when requesting say Images or larger files.

                    if (fileStream == null)
                    {
                        resource = null;
                        return(false);
                    }

                    m = GetMIMETypeByURL(url);

                    if (string.IsNullOrEmpty(contentType) || m == X3DMIMEType.UNKNOWN)
                    {
                        if (m == X3DMIMEType.UNKNOWN)
                        {
                            // response is a generic resource
                            resource = fileStream;
                        }
                        else
                        {
                            // response is a scene
                            resource = fromStream(fileStream, m);

                            set_cd(url);
                        }
                    }
                    else
                    {
                        // response is a scene
                        resource = fromStream(fileStream, m);

                        set_cd(url);
                    }
                    return(true);
                }
                catch (WebException wex)
                {
                    if (wex.Status == WebExceptionStatus.Timeout)
                    {
                        Console.WriteLine(string.Format("Timed out requesting resource '{0}'", url));
                        resource = null;
                        return(false);
                    }
                    else
                    {
                        // Skip download. If MFString was used, there should hopefully be a URL that works

                        Console.WriteLine("** skipping ** url {0}", url);

                        resource = null;
                        return(false);
                    }
                }
            }
        }