http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/e387fc92/JSLib/tests/code/jsdate.cs ---------------------------------------------------------------------- diff --git a/JSLib/tests/code/jsdate.cs b/JSLib/tests/code/jsdate.cs index 40996d0..4f57fe6 100644 --- a/JSLib/tests/code/jsdate.cs +++ b/JSLib/tests/code/jsdate.cs @@ -1,40 +1,40 @@ -/// <summary> -/// The oracle's representation of a Javascript date object as deserialized by the library -/// </summary> - -namespace DataJS.Tests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Runtime.Serialization; - using System.ServiceModel; - using System.ServiceModel.Activation; - using System.ServiceModel.Syndication; - using System.ServiceModel.Web; - using System.Xml; - using System.Xml.Linq; - using System.Spatial; - using Microsoft.Data.OData; - - [Serializable] - public class JsDate : JsonObject - { - private static readonly DateTime JsEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - - public JsDate(DateTime dateTime) - : base() - { - this["milliseconds"] = dateTime.Subtract(JsEpoch).TotalMilliseconds; - } - - public JsDate(DateTimeOffset dateTimeOffset) - : this(dateTimeOffset.UtcDateTime) - { - this["__edmType"] = "Edm.DateTimeOffset"; - this["__offset"] = (dateTimeOffset.Offset < TimeSpan.Zero ? "-" : "+") + dateTimeOffset.Offset.ToString("hh':'mm"); - } - } +/// <summary> +/// The oracle's representation of a Javascript date object as deserialized by the library +/// </summary> + +namespace DataJS.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Runtime.Serialization; + using System.ServiceModel; + using System.ServiceModel.Activation; + using System.ServiceModel.Syndication; + using System.ServiceModel.Web; + using System.Xml; + using System.Xml.Linq; + using Microsoft.Spatial; + using Microsoft.OData.Core; + + [Serializable] + public class JsDate : JsonObject + { + private static readonly DateTime JsEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + public JsDate(DateTime dateTime) + : base() + { + this["milliseconds"] = dateTime.Subtract(JsEpoch).TotalMilliseconds; + } + + public JsDate(DateTimeOffset dateTimeOffset) + : this(dateTimeOffset.UtcDateTime) + { + this["__edmType"] = "Edm.DateTimeOffset"; + this["__offset"] = (dateTimeOffset.Offset < TimeSpan.Zero ? "-" : "+") + dateTimeOffset.Offset.ToString("hh':'mm"); + } + } } \ No newline at end of file
http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/e387fc92/JSLib/tests/code/jsonobject.cs ---------------------------------------------------------------------- diff --git a/JSLib/tests/code/jsonobject.cs b/JSLib/tests/code/jsonobject.cs index 79b914e..35b080c 100644 --- a/JSLib/tests/code/jsonobject.cs +++ b/JSLib/tests/code/jsonobject.cs @@ -1,80 +1,80 @@ -/// <summary> -/// A weakly typed representation of a JSON object using a dictionary implementation -/// </summary> -/// <typeparam name="T">The CLR type of the values of the properties</typeparam> - -namespace DataJS.Tests -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Runtime.Serialization; - - [Serializable] - [KnownType(typeof(JsonObject))] - [KnownType(typeof(JsonObject[]))] - [KnownType(typeof(JsDate))] - [KnownType(typeof(List<object>))] - public class JsonObject : ISerializable, IEnumerable<KeyValuePair<string, object>> - { - Dictionary<string, object> dictionary = new Dictionary<string, object>(); - - public void Remove(string key) - { - dictionary.Remove(key); - } - - public object this[string key] - { - get - { - return this.dictionary[key]; - } - set - { - this.dictionary[key] = value; - } - } - - public bool ContainsKey(string key) - { - return this.dictionary.ContainsKey(key); - } - - public static JsonObject Merge(JsonObject first, JsonObject second) - { - if (first == null) - { - return second; - } - - if (second != null) - { - JsonObject merged = new JsonObject(); - merged.dictionary = new Dictionary<string, object>(first.dictionary); - foreach (var pair in second.dictionary) - { - merged.dictionary[pair.Key] = pair.Value; - } - return merged; - } - return first; - } - - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - this.dictionary.ToList().ForEach(pair => info.AddValue(pair.Key, pair.Value)); - } - - public IEnumerator<KeyValuePair<string, object>> GetEnumerator() - { - return this.dictionary.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return this.dictionary.GetEnumerator(); - } - } +/// <summary> +/// A weakly typed representation of a JSON object using a dictionary implementation +/// </summary> +/// <typeparam name="T">The CLR type of the values of the properties</typeparam> + +namespace DataJS.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Runtime.Serialization; + + [Serializable] + [KnownType(typeof(JsonObject))] + [KnownType(typeof(JsonObject[]))] + [KnownType(typeof(JsDate))] + [KnownType(typeof(List<object>))] + public class JsonObject : ISerializable, IEnumerable<KeyValuePair<string, object>> + { + Dictionary<string, object> dictionary = new Dictionary<string, object>(); + + public void Remove(string key) + { + dictionary.Remove(key); + } + + public object this[string key] + { + get + { + return this.dictionary[key]; + } + set + { + this.dictionary[key] = value; + } + } + + public bool ContainsKey(string key) + { + return this.dictionary.ContainsKey(key); + } + + public static JsonObject Merge(JsonObject first, JsonObject second) + { + if (first == null) + { + return second; + } + + if (second != null) + { + JsonObject merged = new JsonObject(); + merged.dictionary = new Dictionary<string, object>(first.dictionary); + foreach (var pair in second.dictionary) + { + merged.dictionary[pair.Key] = pair.Value; + } + return merged; + } + return first; + } + + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + this.dictionary.ToList().ForEach(pair => info.AddValue(pair.Key, pair.Value)); + } + + public IEnumerator<KeyValuePair<string, object>> GetEnumerator() + { + return this.dictionary.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return this.dictionary.GetEnumerator(); + } + } } \ No newline at end of file http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/e387fc92/JSLib/tests/code/readerutils.cs ---------------------------------------------------------------------- diff --git a/JSLib/tests/code/readerutils.cs b/JSLib/tests/code/readerutils.cs index 35b98ba..6d12978 100644 --- a/JSLib/tests/code/readerutils.cs +++ b/JSLib/tests/code/readerutils.cs @@ -1,48 +1,68 @@ -using System.Net; -namespace DataJS.Tests -{ - public static class ReaderUtils - { - public static JsonObject CreateEntryPropertyMetadata(string type) - { - return CreateEntryPropertyMetadata(type, true); - } - - public static JsonObject CreateEntryPropertyMetadata(string type, bool withExtensions) - { - JsonObject json = new JsonObject(); - json["type"] = type; - - - // TODO: add proper support for property extensions - if (withExtensions) - { - json["extensions"] = new JsonObject[] { }; - } - - return json; - } - - public static JsonObject CreateExtension(string name, string nameSpace, string value) - { - JsonObject json = new JsonObject(); - json["name"] = name; - json["namespaceURI"] = nameSpace; - json["value"] = value; - return json; - } - - public static WebRequest CreateRequest(string url, string user = null, string password = null) - { - WebRequest request = WebRequest.Create(url); - if (user != null || password != null) - { - request.Credentials = new NetworkCredential(user, password); - request.PreAuthenticate = true; - } - - return request; - } - - } +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Web.Script.Serialization; + +namespace DataJS.Tests +{ + public static class ReaderUtils + { + public static JsonObject CreateEntryPropertyMetadata(string type) + { + return CreateEntryPropertyMetadata(type, true); + } + + public static JsonObject CreateEntryPropertyMetadata(string type, bool withExtensions) + { + JsonObject json = new JsonObject(); + json["type"] = type; + + + // TODO: add proper support for property extensions + if (withExtensions) + { + json["extensions"] = new JsonObject[] { }; + } + + return json; + } + + public static JsonObject CreateExtension(string name, string nameSpace, string value) + { + JsonObject json = new JsonObject(); + json["name"] = name; + json["namespaceURI"] = nameSpace; + json["value"] = value; + return json; + } + + public static WebRequest CreateRequest(string url, string user = null, string password = null) + { + WebRequest request = WebRequest.Create(url); + if (user != null || password != null) + { + request.Credentials = new NetworkCredential(user, password); + request.PreAuthenticate = true; + } + + return request; + } + + public static Stream ConvertDictionarytoJsonlightStream(Dictionary<string, object> dict) + { + MemoryStream stream = new MemoryStream(); + if (dict == null) + { + return stream; + } + + string jsonString = new JavaScriptSerializer().Serialize(dict); + StreamWriter writer = new StreamWriter(stream); + writer.Write(jsonString); + writer.Flush(); + stream.Position = 0; + return stream; + } + + } } \ No newline at end of file http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/e387fc92/JSLib/tests/common/ODataReadOracle.js ---------------------------------------------------------------------- diff --git a/JSLib/tests/common/ODataReadOracle.js b/JSLib/tests/common/ODataReadOracle.js index a0c0bbc..a507028 100644 --- a/JSLib/tests/common/ODataReadOracle.js +++ b/JSLib/tests/common/ODataReadOracle.js @@ -1,275 +1,205 @@ -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. -// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, -// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE -// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Client for the odata.read oracle service - -(function (window, undefined) { - var jsonMime = "application/json;odata=verbose"; - var universalMime = "*/*"; - var atomMime = "application/atom+xml"; - - var readFeed = function (url, success, mimeType, recognizeDates) { - /// <summary>Calls the ReadFeed endpoint with the specified URL</summary> - /// <param name="url" type="String">The URL to read the feed from</param> - /// <param name="success" type="Function">The success callback function</param> - /// <param name="mimeType" type="String">The MIME media type in the Accept header</param> - var readMethod = getReadMethod(mimeType, "ReadFeed"); - oracleRequest("GET", readMethod, typeof url === "string" ? { url: url} : url, mimeType, recognizeDates, function (data) { - if (!data.results) { - data = { results: data }; - } - success(data); - }); - }; - - var readEntry = function (url, success, mimeType, recognizeDates) { - /// <summary>Calls the ReadEntry endpoint with the specified URL</summary> - /// <param name="url" type="String">The URL to read the entry from</param> - /// <param name="success" type="Function">The success callback function</param> - /// <param name="mimeType" type="String">The MIME media type in the Accept header</param> - var readMethod = getReadMethod(mimeType, "ReadEntry"); - oracleRequest("GET", readMethod, typeof url === "string" ? { url: url} : url, mimeType, recognizeDates, success); - }; - - var readFeedLoopback = function (atomFeedXml, success, recognizeDates) { - /// <summary>Calls the ReadFeedLoopback endpoint with the specified atom feed xml</summary> - /// <param name="atomFeedXml" type="String">The atom feed xml</param> - /// <param name="success" type="Function">The success callback function</param> - oracleRequest("POST", "ReadFeedLoopback", atomFeedXml, atomMime, recognizeDates, success); - }; - - var readEntryLoopback = function (atomEntryXml, success, recognizeDates) { - /// <summary>Calls the ReadEntryLoopback endpoint with the specified atom entry xml</summary> - /// <param name="atomEntryXml" type="String">The atom entry xml</param> - /// <param name="success" type="Function">The success callback function</param> - oracleRequest("POST", "ReadEntryLoopback", atomEntryXml, atomMime, recognizeDates, success); - }; - - var readLinksEntry = function (url, success) { - /// <summary>Calls the ReadMetadata endpoint with the specified URL</summary> - /// <param name="url" type="String">The URL to read the metadata from</param> - /// <param name="success" type="Function">The success callback function</param> - readJson( - url, - success - ); - }; - - var readLinksFeed = function (url, success) { - /// <summary>Calls the ReadMetadata endpoint with the specified URL</summary> - /// <param name="url" type="String">The URL to read the metadata from</param> - /// <param name="success" type="Function">The success callback function</param> - readJson( - url, - function (data) { - if (!data.results) { - data = { results: data }; - } - success(data); - } - ); - }; - - var readMetadata = function (url, success) { - /// <summary>Calls the ReadMetadata endpoint with the specified URL</summary> - /// <param name="url" type="String">The URL to read the metadata from</param> - /// <param name="success" type="Function">The success callback function</param> - $.getJSON( - "./common/ODataReadOracle.svc/ReadMetadata?url=" + escape(url), - function (data) { - removeProperty(data.d, "__type"); - success(data.d); - } - ); - }; - - var readServiceDocument = function (url, success, mimeType) { - /// <summary>Calls the ReadServiceDocument endpoint with the specified URL</summary> - /// <param name="url" type="String">The URL to the service</param> - /// <param name="success" type="Function">The success callback function</param> - /// <param name="mimeType" type="String">The MIME type being tested</param> - - $.getJSON( - "./common/ODataReadOracle.svc/ReadServiceDocument?url=" + escape(url) + "&mimeType=" + mimeType, - function (data) { - removeProperty(data.d, "__type"); - if (mimeType == jsonMime) { - removeProperty(data.d, "extensions"); - $.each(data.d["workspaces"], function (_, workspace) { - delete workspace["title"]; - }); - } - success(data.d); - } - ); - }; - - var readJson = function (url, success) { - $.ajax({ - url: url, - accepts: null, - dataType: "json", - beforeSend: function (xhr) { - xhr.setRequestHeader("Accept", jsonMime); - xhr.setRequestHeader("MaxDataServiceVersion", "3.0"); - }, - success: function (data) { - success(data.d); - } - }); - }; - - var readJsonAcrossServerPages = function (url, success) { - var data = []; - var readPage = function (url) { - readJson(url, function (feedData) { - var results = feedData.results || feedData; - var next = feedData.__next; - - data = data.concat(results); - if (next) { - readPage(next); - } else { - success(data); - } - }); - }; - - readPage(url); - } - - var getReadMethod = function (mimeType, defaultEndpoint) { - switch (mimeType) { - case universalMime: - case atomMime: - return defaultEndpoint; - case jsonMime: - default: - return "ReadJson"; - } - } - - var oracleRequest = function (method, endpoint, data, mimeType, recognizeDates, success) { - /// <summary>Requests a JSON object from the oracle service, removing WCF-specific artifacts</summary> - /// <param name="method" type="String">The HTTP method (GET or POST)</param> - /// <param name="endpoint" type="String">The oracle endpoint</param> - /// <param name="data" type="Object">The data to send with the request</param> - /// <param name="reviver" type="Function">The reviver function to run on each deserialized object</param> - /// <param name="success" type="Function">Success callback</param> - var reviver = mimeType === jsonMime || mimeType === undefined ? (recognizeDates ? odataDateReviver : undefined) : oracleDateReviver; - var url = "./common/ODataReadOracle.svc/" + endpoint; - $.ajax({ - type: method, - url: url, - data: data, - dataType: "text", - success: function (data) { - var json = JSON.parse(data, reviver); - removeProperty(json.d, "__type"); - success(json.d); - } - }); - }; - - var removeProperty = function (data, property) { - /// <summary>Removes the specified property recursively from the given object</summary> - /// <param name="data" type="Object">The object to operate on</param> - /// <param name="property" type="String">The name of the property to remove</param> - if (typeof data === "object" && data !== null) { - if (data[property]) { - delete data[property]; - } - - for (prop in data) { - removeProperty(data[prop], property); - } - } - } - - var oracleDateReviver = function (key, value) { - /// <summary>Revives date objects received from the oracle service</summary> - if (value && value["__type"] && value["__type"].search("JsDate") > -1) { - var data = new Date(value.milliseconds); - if (value["__edmType"]) { - data["__edmType"] = value["__edmType"]; - } - - if (value["__offset"]) { - data["__offset"] = value["__offset"]; - } - - return data; - } - - return value; - } - - var odataDateReviver = function (key, value) { - /// <summary>Revives date objects received from OData JSON payloads</summary> - var regexp = /^\/Date\((-?\d+)(\+|-)?(\d+)?\)\/$/; - var matches = regexp.exec(value); - if (matches) { - var milliseconds = parseInt(matches[1], 10); - if (!isNaN(milliseconds)) { - var result = new Date(milliseconds); - if (matches[2]) { - var sign = matches[2]; - var offsetMinutes = parseInt(matches[3], 10); - if (sign === "-") { - offsetMinutes = -offsetMinutes; - } - - result.setUTCMinutes(result.getUTCMinutes() - offsetMinutes); - result["__edmType"] = "Edm.DateTimeOffset"; - result["__offset"] = minutesToOffset(offsetMinutes); - } - return result; - } - } - - return value; - } - - var minutesToOffset = function (minutes) { - var padIfNeeded = function (value) { - var result = value.toString(10); - return result.length < 2 ? "0" + result : result; - }; - - var sign; - if (minutes < 0) { - sign = "-"; - minutes = -minutes; - } else { - sign = "+"; - } - - var hours = Math.floor(minutes / 60); - minutes = minutes - (60 * hours); - - return sign + padIfNeeded(hours) + ":" + padIfNeeded(minutes); - }; - - window.ODataReadOracle = { - readFeed: readFeed, - readEntry: readEntry, - readFeedLoopback: readFeedLoopback, - readEntryLoopback: readEntryLoopback, - readLinksEntry: readLinksEntry, - readLinksFeed: readLinksFeed, - readJson: readJson, - readJsonAcrossServerPages: readJsonAcrossServerPages, - readMetadata: readMetadata, - readServiceDocument: readServiceDocument - }; +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, +// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Client for the odata.read oracle service + +(function (window, undefined) { + var jsonMime = "application/json"; + var universalMime = "*/*"; + var atomMime = "application/atom+xml"; + + var readFeed = function (url, success, mimeType, recognizeDates) { + /// <summary>Calls the ReadFeed endpoint with the specified URL</summary> + /// <param name="url" type="String">The URL to read the feed from</param> + /// <param name="success" type="Function">The success callback function</param> + /// <param name="mimeType" type="String">The MIME media type in the Accept header</param> + var readMethod = getReadMethod(mimeType, "ReadFeed"); + oracleRequest("GET", readMethod, typeof url === "string" ? { url: url} : url, mimeType, recognizeDates, function (data) { + success(data); + }); + }; + + var readEntry = function (url, success, mimeType, recognizeDates) { + /// <summary>Calls the ReadEntry endpoint with the specified URL</summary> + /// <param name="url" type="String">The URL to read the entry from</param> + /// <param name="success" type="Function">The success callback function</param> + /// <param name="mimeType" type="String">The MIME media type in the Accept header</param> + var readMethod = getReadMethod(mimeType, "ReadEntry"); + oracleRequest("GET", readMethod, typeof url === "string" ? { url: url} : url, mimeType, recognizeDates, success); + }; + + var readFeedLoopback = function (atomFeedXml, success, recognizeDates) { + /// <summary>Calls the ReadFeedLoopback endpoint with the specified atom feed xml</summary> + /// <param name="atomFeedXml" type="String">The atom feed xml</param> + /// <param name="success" type="Function">The success callback function</param> + oracleRequest("POST", "ReadFeedLoopback", atomFeedXml, atomMime, recognizeDates, success); + }; + + var readEntryLoopback = function (atomEntryXml, success, recognizeDates) { + /// <summary>Calls the ReadEntryLoopback endpoint with the specified atom entry xml</summary> + /// <param name="atomEntryXml" type="String">The atom entry xml</param> + /// <param name="success" type="Function">The success callback function</param> + oracleRequest("POST", "ReadEntryLoopback", atomEntryXml, atomMime, recognizeDates, success); + }; + + var readLinksEntry = function (url, success) { + /// <summary>Calls the ReadMetadata endpoint with the specified URL</summary> + /// <param name="url" type="String">The URL to read the metadata from</param> + /// <param name="success" type="Function">The success callback function</param> + readJson( + url, + success + ); + }; + + var readLinksFeed = function (url, success) { + /// <summary>Calls the ReadMetadata endpoint with the specified URL</summary> + /// <param name="url" type="String">The URL to read the metadata from</param> + /// <param name="success" type="Function">The success callback function</param> + readJson( + url, + function (data) { + success(data); + } + ); + }; + + var readMetadata = function (url, success) { + /// <summary>Calls the ReadMetadata endpoint with the specified URL</summary> + /// <param name="url" type="String">The URL to read the metadata from</param> + /// <param name="success" type="Function">The success callback function</param> + oracleRequest("GET", "ReadMetadata", typeof url === "string" ? { url: url} : url, null, null, success); + }; + + var readServiceDocument = function (url, success, mimeType) { + /// <summary>Calls the ReadServiceDocument endpoint with the specified URL</summary> + /// <param name="url" type="String">The URL to the service</param> + /// <param name="success" type="Function">The success callback function</param> + /// <param name="mimeType" type="String">The MIME type being tested</param> + var readMethod = getReadMethod(mimeType, "ReadServiceDocument"); + oracleRequest("GET", readMethod, typeof url === "string" ? { url: url} : url, mimeType, null, success); + }; + + var readJson = function (url, success) { + $.ajax({ + url: url, + accepts: null, + dataType: "json", + beforeSend: function (xhr) { + xhr.setRequestHeader("Accept", jsonMime); + xhr.setRequestHeader("OData-MaxVersion", "4.0"); + }, + success: function (data) { + success(data); + } + }); + }; + + var readJsonAcrossServerPages = function (url, success) { + var data = {}; + var readPage = function (url) { + readJson(url, function (feedData) { + var nextLink = feedData["@odata.nextLink"]; + if (nextLink) { + var index = url.indexOf(".svc/", 0); + if (index != -1) { + nextLink = url.substring(0, index + 5) + nextLink; + } + } + + if (data.value && feedData.value) { + data.value = data.value.concat(feedData.value); + } + else { + for (var property in feedData) { + if (property != "@odata.nextLink") { + data[property] = feedData[property]; + } + } + } + + if (nextLink) { + readPage(nextLink); + } + else { + success(data); + } + }); + }; + + readPage(url); + }; + + var getReadMethod = function (mimeType, defaultEndpoint) { + switch (mimeType) { + case atomMime: + return defaultEndpoint; + case jsonMime: + case universalMime: + default: + return "ReadJson"; + } + }; + + var oracleRequest = function (method, endpoint, data, mimeType, recognizeDates, success) { + /// <summary>Requests a JSON object from the oracle service, removing WCF-specific artifacts</summary> + /// <param name="method" type="String">The HTTP method (GET or POST)</param> + /// <param name="endpoint" type="String">The oracle endpoint</param> + /// <param name="data" type="Object">The data to send with the request</param> + /// <param name="reviver" type="Function">The reviver function to run on each deserialized object</param> + /// <param name="success" type="Function">Success callback</param> + var url = "./common/ODataReadOracle.svc/" + endpoint; + if (mimeType) { + data.mimeType = mimeType; + } + + $.ajax({ + type: method, + url: url, + data: data, + dataType: "text", + success: function (data) { + var json = JSON.parse(data); + success(json); + } + }); + }; + + var removeProperty = function (data, property) { + /// <summary>Removes the specified property recursively from the given object</summary> + /// <param name="data" type="Object">The object to operate on</param> + /// <param name="property" type="String">The name of the property to remove</param> + if (typeof data === "object" && data !== null) { + if (data[property]) { + delete data[property]; + } + + for (prop in data) { + removeProperty(data[prop], property); + } + } + }; + + window.ODataReadOracle = { + readFeed: readFeed, + readEntry: readEntry, + readFeedLoopback: readFeedLoopback, + readEntryLoopback: readEntryLoopback, + readLinksEntry: readLinksEntry, + readLinksFeed: readLinksFeed, + readJson: readJson, + readJsonAcrossServerPages: readJsonAcrossServerPages, + readMetadata: readMetadata, + readServiceDocument: readServiceDocument + }; })(window); \ No newline at end of file http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/e387fc92/JSLib/tests/common/ODataReadOracle.svc ---------------------------------------------------------------------- diff --git a/JSLib/tests/common/ODataReadOracle.svc b/JSLib/tests/common/ODataReadOracle.svc index 32b4d50..6a4c6f7 100644 --- a/JSLib/tests/common/ODataReadOracle.svc +++ b/JSLib/tests/common/ODataReadOracle.svc @@ -1,182 +1,189 @@ -<%@ ServiceHost Language="C#" Debug="true" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" - Service="DataJS.Tests.ODataReadOracle" %> - -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. -// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, -// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE -// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -//uncomment this line to debug JSON serialization. -//#define DEBUG_SERIALIZATION - -namespace DataJS.Tests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Runtime.Serialization; - using System.ServiceModel; - using System.ServiceModel.Activation; - using System.ServiceModel.Syndication; - using System.ServiceModel.Web; - using System.Xml; - using System.Xml.Linq; - using System.Spatial; - using Microsoft.Data.OData; - - /// <summary> - /// Oracle for the OData.read library function - /// </summary> - [ServiceContract] - [ServiceBehavior(IncludeExceptionDetailInFaults = true)] - [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] - public class ODataReadOracle - { - const string jsonVerboseMediaType = "application/json;odata=verbose"; - - /// <summary> - /// Reads a URI that will return an OData ATOM feed - /// </summary> - /// <param name="url">The URL to send the request to</param> - /// <param name="user">The username for basic authentication</param> - /// <param name="password">The password for basic authentication</param> - /// <returns>JSON object expected to be returned by OData.read (plus type metadata markers that will need to be removed)</returns> - [OperationContract] - [WebGet(ResponseFormat = WebMessageFormat.Json)] - public JsonObject ReadFeed(string url, string user, string password) - { - WebResponse response = ReaderUtils.CreateRequest(ResolveUri(url, UriKind.Absolute), user, password).GetResponse(); - return AtomReader.ReadFeed(new StreamReader(response.GetResponseStream())); - } - - /// <summary> - /// Reads a URI that will return an OData ATOM feed entry - /// </summary> - /// <param name="url">URL of the entry</param> - /// <param name="user">The username for basic authentication</param> - /// <param name="password">The password for basic authentication</param> - /// <returns>JSON object expected to be returned by OData.read</returns> - [OperationContract] - [WebGet(ResponseFormat = WebMessageFormat.Json)] - public JsonObject ReadEntry(string url, string user, string password) - { - WebResponse response = ReaderUtils.CreateRequest(ResolveUri(url, UriKind.Absolute), user, password).GetResponse(); - return AtomReader.ReadEntry(new StreamReader(response.GetResponseStream())); - } - - /// <summary> - /// Reads a URI that will return a metadata object - /// </summary> - /// <param name="url">The URL to send the request to</param> - /// <returns>JSON object expected to be returned by OData.read (plus type metadata markers that will need to be removed)</returns> - [OperationContract] - [WebGet(ResponseFormat = WebMessageFormat.Json)] - public JsonObject ReadMetadata(string url) - { - WebResponse response = WebRequest.Create(ResolveUri(url, UriKind.Absolute)).GetResponse(); - return CsdlReader.ReadCsdl(new StreamReader(response.GetResponseStream())); - } - - /// <summary> - /// Reads a URI that will return a metadata object - /// </summary> - /// <param name="url">The URL to send the request to</param> - /// <param name="mimeType">Mime type being tested to determine base URI</param> - /// <returns>JSON object expected to be returned by OData.read (plus type metadata markers that will need to be removed)</returns> - [OperationContract] - [WebGet(ResponseFormat = WebMessageFormat.Json)] - public JsonObject ReadServiceDocument(string url, string mimeType) - { - WebResponse response = WebRequest.Create(ResolveUri(url, UriKind.Absolute)).GetResponse(); - string baseUri = string.Empty; - - // With JSON responses only relative path passed to the library is available - if (mimeType.Equals(jsonVerboseMediaType)) - { - baseUri = ResolveUri(url, UriKind.Relative).ToString(); - } - else - { - baseUri = response.ResponseUri.AbsoluteUri; - } - - return AtomReader.ReadServiceDocument(new StreamReader(response.GetResponseStream()), baseUri); - } - - /// <summary> - /// Reads a URI that will get the Json response and return the stream - /// </summary> - /// <param name="url">URL of the entry</param> - /// <param name="user">The username for basic authentication</param> - /// <param name="password">The password for basic authentication</param> - /// <returns>Stream of the Json response expected to be returned by OData.read</returns> - [OperationContract] - [WebGet(ResponseFormat = WebMessageFormat.Json)] - public Stream ReadJson(string url, string user, string password) - { - HttpWebRequest request = (HttpWebRequest)ReaderUtils.CreateRequest(ResolveUri(url, UriKind.Absolute), user, password); - request.Accept = jsonVerboseMediaType + "; charset=utf-8"; - WebResponse response = request.GetResponse(); - - return response.GetResponseStream(); - } - - - /// <summary> - /// Loops back an ATOM feed passed to the webservice in JSON format. - /// </summary> - /// <param name="content">The ATOM feed xml stream to loopback as JSON</param> - /// <returns>JSON object expected to be returned by OData.read (plus type metadata markers that will need to be removed)</returns> - [OperationContract] - [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] - public JsonObject ReadFeedLoopback(Stream content) - { - return AtomReader.ReadFeed(new StreamReader(content)); - } - - /// <summary> - /// Loops back an ATOM entry passed to the webservice in JSON format. - /// </summary> - /// <param name="content">The ATOM entry xml stream to loopback as JSON</param> - /// <returns>JSON object expected to be returned by OData.read (plus type metadata markers that will need to be removed)</returns> - [OperationContract] - [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] - public JsonObject ReadEntryLoopback(Stream content) - { - return AtomReader.ReadEntry(new StreamReader(content)); - } - - /// <summary> - /// Resolves the given url string to a URI - /// </summary> - /// <param name="url">The given URL string</param> - /// <param name="urlKind">URI kind to resolve to</param> - /// <returns>The resolved URI</returns> - private static string ResolveUri(string url, UriKind uriKind) - { - Uri resolvedUri = new Uri(url, UriKind.RelativeOrAbsolute); - if (!resolvedUri.IsAbsoluteUri) - { - // If the given URI is relative, then base it on the Referer URI - Uri baseUri = new Uri(WebOperationContext.Current.IncomingRequest.Headers["Referer"]); - resolvedUri = new Uri(baseUri, resolvedUri); - if (uriKind == UriKind.Relative) - { - resolvedUri = baseUri.MakeRelativeUri(resolvedUri); - } - } - - return resolvedUri.ToString(); - } - } +<%@ ServiceHost Language="C#" Debug="true" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" + Service="DataJS.Tests.ODataReadOracle" %> + +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, +// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +//uncomment this line to debug JSON serialization. +//#define DEBUG_SERIALIZATION + +namespace DataJS.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Runtime.Serialization; + using System.ServiceModel; + using System.ServiceModel.Activation; + using System.ServiceModel.Syndication; + using System.ServiceModel.Web; + using System.Xml; + using System.Xml.Linq; + using Microsoft.Spatial; + using Microsoft.OData.Core; + using System.Web.Script.Serialization; + + /// <summary> + /// Oracle for the OData.read library function + /// </summary> + [ServiceContract] + [ServiceBehavior(IncludeExceptionDetailInFaults = true)] + [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] + public class ODataReadOracle + { + const string jsonlightMediaType = "application/json"; + + /// <summary> + /// Reads a URI that will return an OData ATOM feed + /// </summary> + /// <param name="url">The URL to send the request to</param> + /// <param name="user">The username for basic authentication</param> + /// <param name="password">The password for basic authentication</param> + /// <returns>JSON object expected to be returned by OData.read (plus type metadata markers that will need to be removed)</returns> + [OperationContract] + [WebGet(ResponseFormat = WebMessageFormat.Json)] + public JsonObject ReadFeed(string url, string user, string password) + { + WebResponse response = ReaderUtils.CreateRequest(ResolveUri(url, UriKind.Absolute), user, password).GetResponse(); + return AtomReader.ReadFeed(new StreamReader(response.GetResponseStream())); + } + + /// <summary> + /// Reads a URI that will return an OData ATOM feed entry + /// </summary> + /// <param name="url">URL of the entry</param> + /// <param name="user">The username for basic authentication</param> + /// <param name="password">The password for basic authentication</param> + /// <returns>JSON object expected to be returned by OData.read</returns> + [OperationContract] + [WebGet(ResponseFormat = WebMessageFormat.Json)] + public JsonObject ReadEntry(string url, string user, string password) + { + WebResponse response = ReaderUtils.CreateRequest(ResolveUri(url, UriKind.Absolute), user, password).GetResponse(); + return AtomReader.ReadEntry(new StreamReader(response.GetResponseStream())); + } + + /// <summary> + /// Reads a URI that will return a metadata object + /// </summary> + /// <param name="url">The URL to send the request to</param> + /// <returns>Stream of metadata in json light format</returns> + [OperationContract] + [WebGet] + public Stream ReadMetadata(string url) + { + WebResponse response = WebRequest.Create(ResolveUri(url, UriKind.Absolute)).GetResponse(); + Dictionary<string, object> jsonObject = CsdlReader.ReadCsdl(new StreamReader(response.GetResponseStream())); + return ReaderUtils.ConvertDictionarytoJsonlightStream(jsonObject); + } + + /// <summary> + /// Reads a URI that will return a metadata object + /// </summary> + /// <param name="url">The URL to send the request to</param> + /// <param name="mimeType">Mime type being tested to determine base URI</param> + /// <returns>JSON object expected to be returned by OData.read (plus type metadata markers that will need to be removed)</returns> + [OperationContract] + [WebGet(ResponseFormat = WebMessageFormat.Json)] + public JsonObject ReadServiceDocument(string url, string mimeType) + { + WebResponse response = WebRequest.Create(ResolveUri(url, UriKind.Absolute)).GetResponse(); + string baseUri = string.Empty; + + // With JSON responses only relative path passed to the library is available + if (mimeType.Equals(jsonlightMediaType)) + { + baseUri = ResolveUri(url, UriKind.Relative).ToString(); + } + else + { + baseUri = response.ResponseUri.AbsoluteUri; + } + + return AtomReader.ReadServiceDocument(new StreamReader(response.GetResponseStream()), baseUri); + } + + /// <summary> + /// Reads a URI that will get the Json response and return the stream + /// </summary> + /// <param name="url">URL of the entry</param> + /// <param name="user">The username for basic authentication</param> + /// <param name="password">The password for basic authentication</param> + /// <returns>Stream of the Json response expected to be returned by OData.read</returns> + [OperationContract] + [WebGet(ResponseFormat = WebMessageFormat.Json)] + public Stream ReadJson(string url, string mimeType, string user, string password) + { + if (mimeType == null) + { + mimeType = jsonlightMediaType + ";odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8"; + } + + HttpWebRequest request = (HttpWebRequest)ReaderUtils.CreateRequest(ResolveUri(url, UriKind.Absolute), user, password); + request.Accept = mimeType; + WebResponse response = request.GetResponse(); + + return response.GetResponseStream(); + } + + + /// <summary> + /// Loops back an ATOM feed passed to the webservice in JSON format. + /// </summary> + /// <param name="content">The ATOM feed xml stream to loopback as JSON</param> + /// <returns>JSON object expected to be returned by OData.read (plus type metadata markers that will need to be removed)</returns> + [OperationContract] + [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] + public JsonObject ReadFeedLoopback(Stream content) + { + return AtomReader.ReadFeed(new StreamReader(content)); + } + + /// <summary> + /// Loops back an ATOM entry passed to the webservice in JSON format. + /// </summary> + /// <param name="content">The ATOM entry xml stream to loopback as JSON</param> + /// <returns>JSON object expected to be returned by OData.read (plus type metadata markers that will need to be removed)</returns> + [OperationContract] + [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] + public JsonObject ReadEntryLoopback(Stream content) + { + return AtomReader.ReadEntry(new StreamReader(content)); + } + + /// <summary> + /// Resolves the given url string to a URI + /// </summary> + /// <param name="url">The given URL string</param> + /// <param name="urlKind">URI kind to resolve to</param> + /// <returns>The resolved URI</returns> + private static string ResolveUri(string url, UriKind uriKind) + { + Uri resolvedUri = new Uri(url, UriKind.RelativeOrAbsolute); + if (!resolvedUri.IsAbsoluteUri) + { + // If the given URI is relative, then base it on the Referer URI + Uri baseUri = new Uri(WebOperationContext.Current.IncomingRequest.Headers["Referer"]); + resolvedUri = new Uri(baseUri, resolvedUri); + if (uriKind == UriKind.Relative) + { + resolvedUri = baseUri.MakeRelativeUri(resolvedUri); + } + } + + return resolvedUri.ToString(); + } + } } \ No newline at end of file
