http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/4621d41c/JSLib/src/odata-xml.js ---------------------------------------------------------------------- diff --git a/JSLib/src/odata-xml.js b/JSLib/src/odata-xml.js deleted file mode 100644 index da050bd..0000000 --- a/JSLib/src/odata-xml.js +++ /dev/null @@ -1,837 +0,0 @@ -// 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. - -// odata-xml.js - -(function (window, undefined) { - - var datajs = window.odatajs || {}; - var odata = window.OData || {}; - - // Imports. - - var djsassert = odatajs.djsassert; - var http = odatajs.http; - var isArray = odatajs.isArray; - var isDate = odatajs.isDate; - var isObject = odatajs.isObject; - var normalizeURI = odatajs.normalizeURI; - var parseInt10 = odatajs.parseInt10; - var xmlAppendChild = odatajs.xmlAppendChild; - var xmlAppendChildren = odatajs.xmlAppendChildren; - var xmlAttributes = odatajs.xmlAttributes; - var xmlBaseURI = odatajs.xmlBaseURI; - var xmlChildElements = odatajs.xmlChildElements; - var xmlDom = odatajs.xmlDom; - var xmlFirstChildElement = odatajs.xmlFirstChildElement; - var xmlInnerText = odatajs.xmlInnerText; - var xmlLocalName = odatajs.xmlLocalName; - var xmlNamespaceURI = odatajs.xmlNamespaceURI; - var xmlNewAttribute = odatajs.xmlNewAttribute; - var xmlNewElement = odatajs.xmlNewElement; - var xmlNodeValue = odatajs.xmlNodeValue; - var xmlNS = odatajs.xmlNS; - var xmlnsNS = odatajs.xmlnsNS; - var xmlParse = odatajs.xmlParse; - var xmlQualifiedName = odatajs.xmlQualifiedName; - var xmlSerialize = odatajs.xmlSerialize; - var xmlSiblingElement = odatajs.xmlSiblingElement; - var w3org = odatajs.w3org; - - var dataItemTypeName = odata.dataItemTypeName; - var EDM_BINARY = odata.EDM_BINARY; - var EDM_BOOLEAN = odata.EDM_BOOLEAN; - var EDM_BYTE = odata.EDM_BYTE; - var EDM_DATETIME = odata.EDM_DATETIME; - var EDM_DATETIMEOFFSET = odata.EDM_DATETIMEOFFSET; - var EDM_DECIMAL = odata.EDM_DECIMAL; - var EDM_DOUBLE = odata.EDM_DOUBLE; - var EDM_GEOGRAPHY = odata.EDM_GEOGRAPHY; - var EDM_GEOGRAPHY_POINT = odata.EDM_GEOGRAPHY_POINT; - var EDM_GEOGRAPHY_LINESTRING = odata.EDM_GEOGRAPHY_LINESTRING; - var EDM_GEOGRAPHY_POLYGON = odata.EDM_GEOGRAPHY_POLYGON; - var EDM_GEOGRAPHY_COLLECTION = odata.EDM_GEOGRAPHY_COLLECTION; - var EDM_GEOGRAPHY_MULTIPOLYGON = odata.EDM_GEOGRAPHY_MULTIPOLYGON; - var EDM_GEOGRAPHY_MULTILINESTRING = odata.EDM_GEOGRAPHY_MULTILINESTRING; - var EDM_GEOGRAPHY_MULTIPOINT = odata.EDM_GEOGRAPHY_MULTIPOINT; - var EDM_GEOMETRY = odata.EDM_GEOMETRY; - var EDM_GEOMETRY_POINT = odata.EDM_GEOMETRY_POINT; - var EDM_GEOMETRY_LINESTRING = odata.EDM_GEOMETRY_LINESTRING; - var EDM_GEOMETRY_POLYGON = odata.EDM_GEOMETRY_POLYGON; - var EDM_GEOMETRY_COLLECTION = odata.EDM_GEOMETRY_COLLECTION; - var EDM_GEOMETRY_MULTIPOLYGON = odata.EDM_GEOMETRY_MULTIPOLYGON; - var EDM_GEOMETRY_MULTILINESTRING = odata.EDM_GEOMETRY_MULTILINESTRING; - var EDM_GEOMETRY_MULTIPOINT = odata.EDM_GEOMETRY_MULTIPOINT; - var EDM_GUID = odata.EDM_GUID; - var EDM_INT16 = odata.EDM_INT16; - var EDM_INT32 = odata.EDM_INT32; - var EDM_INT64 = odata.EDM_INT64; - var EDM_SBYTE = odata.EDM_SBYTE; - var EDM_SINGLE = odata.EDM_SINGLE; - var EDM_STRING = odata.EDM_STRING; - var EDM_TIME = odata.EDM_TIME; - var GEOJSON_POINT = odata.GEOJSON_POINT; - var GEOJSON_LINESTRING = odata.GEOJSON_LINESTRING; - var GEOJSON_POLYGON = odata.GEOJSON_POLYGON; - var GEOJSON_MULTIPOINT = odata.GEOJSON_MULTIPOINT; - var GEOJSON_MULTILINESTRING = odata.GEOJSON_MULTILINESTRING; - var GEOJSON_MULTIPOLYGON = odata.GEOJSON_MULTIPOLYGON; - var GEOJSON_GEOMETRYCOLLECTION = odata.GEOJSON_GEOMETRYCOLLECTION; - var formatDateTimeOffset = odata.formatDateTimeOffset; - var formatDuration = odata.formatDuration; - var getCollectionType = odata.getCollectionType; - var gmlNewODataSpatialValue = odata.gmlNewODataSpatialValue; - var gmlReadODataSpatialValue = odata.gmlReadODataSpatialValue; - var gmlXmlNs = odata.gmlXmlNs; - var handler = odata.handler; - var isCollection = odata.isCollection; - var isCollectionType = odata.isCollectionType; - var isDeferred = odata.isDeferred; - var isNamedStream = odata.isNamedStream; - var isGeographyEdmType = odata.isGeographyEdmType; - var isGeometryEdmType = odata.isGeometryEdmType; - var isPrimitive = odata.isPrimitive; - var isPrimitiveEdmType = odata.isPrimitiveEdmType; - var lookupComplexType = odata.lookupComplexType; - var lookupProperty = odata.lookupProperty; - var maxVersion = odata.maxVersion; - var navigationPropertyKind = odata.navigationPropertyKind; - var MAX_DATA_SERVICE_VERSION = odata.MAX_DATA_SERVICE_VERSION; - var parseBool = odata.parseBool; - var parseDateTime = odata.parseDateTime; - var parseDateTimeOffset = odata.parseDateTimeOffset; - var parseDuration = odata.parseDuration; - var parseTimezone = odata.parseTimezone; - - // CONTENT START - - var xmlMediaType = "application/xml"; - - var ado = http + "docs.oasis-open.org/odata/"; // http://docs.oasis-open.org/odata/ - var adoDs = ado + "ns"; // http://docs.oasis-open.org/odata/ns - - var edmxNs = adoDs + "/edmx"; // http://docs.oasis-open.org/odata/ns/edmx - var edmNs1 = adoDs + "/edm"; // http://docs.oasis-open.org/odata/ns/edm - - var odataXmlNs = adoDs; // http://docs.oasis-open.org/odata/ns - var odataMetaXmlNs = adoDs + "/metadata"; // http://docs.oasis-open.org/odata/ns/metadata - var odataRelatedPrefix = adoDs + "/related/"; // http://docs.oasis-open.org/odata/ns/related - var odataScheme = adoDs + "/scheme"; // http://docs.oasis-open.org/odata/ns/scheme - - var odataPrefix = "d"; - var odataMetaPrefix = "m"; - - var createAttributeExtension = function (domNode, useNamespaceURI) { - /// <summary>Creates an extension object for the specified attribute.</summary> - /// <param name="domNode">DOM node for the attribute.</param> - /// <param name="useNamespaceURI" type="Boolean">Flag indicating if the namespaceURI property should be added to the extension object instead of the namespace property.</param> - /// <remarks> - /// The useNamespaceURI flag is used to prevent a breaking change from older versions of datajs in which extension - /// objects created for Atom extension attributes have the namespaceURI property instead of the namespace one. - /// - /// This flag and the namespaceURI property should be deprecated in future major versions of the library. - /// </remarks> - /// <returns type="Object">The new extension object.</returns> - - djsassert(domNode.nodeType === 2, "createAttributeExtension - domNode is not an attribute node!!"); - var extension = { name: xmlLocalName(domNode), value: domNode.value }; - extension[useNamespaceURI ? "namespaceURI" : "namespace"] = xmlNamespaceURI(domNode); - - return extension; - }; - - var createElementExtension = function (domNode, useNamespaceURI) { - /// <summary>Creates an extension object for the specified element.</summary> - /// <param name="domNode">DOM node for the element.</param> - /// <param name="useNamespaceURI" type="Boolean">Flag indicating if the namespaceURI property should be added to the extension object instead of the namespace property.</param> - /// <remarks> - /// The useNamespaceURI flag is used to prevent a breaking change from older versions of datajs in which extension - /// objects created for Atom extension attributes have the namespaceURI property instead of the namespace one. - /// - /// This flag and the namespaceURI property should be deprecated in future major versions of the library. - /// </remarks> - /// <returns type="Object">The new extension object.</returns> - - djsassert(domNode.nodeType === 1, "createAttributeExtension - domNode is not an element node!!"); - - var attributeExtensions = []; - var childrenExtensions = []; - - var i, len; - var attributes = domNode.attributes; - for (i = 0, len = attributes.length; i < len; i++) { - var attr = attributes[i]; - if (xmlNamespaceURI(attr) !== xmlnsNS) { - attributeExtensions.push(createAttributeExtension(attr, useNamespaceURI)); - } - } - - var child = domNode.firstChild; - while (child != null) { - if (child.nodeType === 1) { - childrenExtensions.push(createElementExtension(child, useNamespaceURI)); - } - child = child.nextSibling; - } - - var extension = { - name: xmlLocalName(domNode), - value: xmlInnerText(domNode), - attributes: attributeExtensions, - children: childrenExtensions - }; - - extension[useNamespaceURI ? "namespaceURI" : "namespace"] = xmlNamespaceURI(domNode); - return extension; - }; - - var isCollectionItemElement = function (domElement) { - /// <summary>Checks whether the domElement is a collection item.</summary> - /// <param name="domElement">DOM element possibliy represnting a collection item.</param> - /// <returns type="Boolean">True if the domeElement belongs to the OData metadata namespace and its local name is "element"; false otherwise.</returns> - - return xmlNamespaceURI(domElement) === odataXmlNs && xmlLocalName(domElement) === "element"; - }; - - var makePropertyMetadata = function (type, extensions) { - /// <summary>Creates an object containing property metadata.</summary> - /// <param type="String" name="type">Property type name.</param> - /// <param type="Array" name="extensions">Array of attribute extension objects.</param> - /// <returns type="Object">Property metadata object cotaining type and extensions fields.</returns> - - return { type: type, extensions: extensions }; - }; - - var odataInferTypeFromPropertyXmlDom = function (domElement) { - /// <summary>Infers type of a property based on its xml DOM tree.</summary> - /// <param name="domElement">DOM element for the property.</param> - /// <returns type="String">Inferred type name; null if the type cannot be determined.</returns> - - if (xmlFirstChildElement(domElement, gmlXmlNs)) { - return EDM_GEOMETRY; - } - - var firstChild = xmlFirstChildElement(domElement, odataXmlNs); - if (!firstChild) { - return EDM_STRING; - } - - if (isCollectionItemElement(firstChild)) { - var sibling = xmlSiblingElement(firstChild, odataXmlNs); - if (sibling && isCollectionItemElement(sibling)) { - // More than one <element> tag have been found, it can be safely assumed that this is a collection property. - return "Collection()"; - } - } - - return null; - }; - - var xmlReadODataPropertyAttributes = function (domElement) { - /// <summary>Reads the attributes of a property DOM element in an OData XML document.</summary> - /// <param name="domElement">DOM element for the property.</param> - /// <returns type="Object">Object containing the property type, if it is null, and its attribute extensions.</returns> - - var type = null; - var isNull = false; - var extensions = []; - - xmlAttributes(domElement, function (attribute) { - var nsURI = xmlNamespaceURI(attribute); - var localName = xmlLocalName(attribute); - var value = xmlNodeValue(attribute); - - if (nsURI === odataMetaXmlNs) { - if (localName === "null") { - isNull = (value.toLowerCase() === "true"); - return; - } - - if (localName === "type") { - type = value; - return; - } - } - - if (nsURI !== xmlNS && nsURI !== xmlnsNS) { - extensions.push(createAttributeExtension(attribute, true)); - return; - } - }); - - return { type: (!type && isNull ? EDM_STRING : type), isNull: isNull, extensions: extensions }; - }; - - var xmlReadODataProperty = function (domElement) { - /// <summary>Reads a property DOM element in an OData XML document.</summary> - /// <param name="domElement">DOM element for the property.</param> - /// <returns type="Object">Object with name, value, and metadata for the property.</returns> - - if (xmlNamespaceURI(domElement) !== odataXmlNs) { - // domElement is not a proprety element because it is not in the odata xml namespace. - return null; - } - - var propertyName = xmlLocalName(domElement); - var propertyAttributes = xmlReadODataPropertyAttributes(domElement); - - var propertyIsNull = propertyAttributes.isNull; - var propertyType = propertyAttributes.type; - - var propertyMetadata = makePropertyMetadata(propertyType, propertyAttributes.extensions); - var propertyValue = propertyIsNull ? null : xmlReadODataPropertyValue(domElement, propertyType, propertyMetadata); - - return { name: propertyName, value: propertyValue, metadata: propertyMetadata }; - }; - - var xmlReadODataPropertyValue = function (domElement, propertyType, propertyMetadata) { - /// <summary>Reads the value of a property in an OData XML document.</summary> - /// <param name="domElement">DOM element for the property.</param> - /// <param name="propertyType" type="String">Property type name.</param> - /// <param name="propertyMetadata" type="Object">Object that will store metadata about the property.</param> - /// <returns>Property value.</returns> - - if (!propertyType) { - propertyType = odataInferTypeFromPropertyXmlDom(domElement); - propertyMetadata.type = propertyType; - } - - var isGeograhpyType = isGeographyEdmType(propertyType); - if (isGeograhpyType || isGeometryEdmType(propertyType)) { - return xmlReadODataSpatialPropertyValue(domElement, propertyType, isGeograhpyType); - } - - if (isPrimitiveEdmType(propertyType)) { - return xmlReadODataEdmPropertyValue(domElement, propertyType); - } - - if (isCollectionType(propertyType)) { - return xmlReadODataCollectionPropertyValue(domElement, propertyType, propertyMetadata); - } - - return xmlReadODataComplexPropertyValue(domElement, propertyType, propertyMetadata); - }; - - var xmlReadODataSpatialPropertyValue = function (domElement, propertyType, isGeography) { - /// <summary>Reads the value of an spatial property in an OData XML document.</summary> - /// <param name="property">DOM element for the spatial property.</param> - /// <param name="propertyType" type="String">Property type name.</param> - /// <param name="isGeography" type="Boolean" Optional="True">Flag indicating if the value uses a geographic reference system or not.<param> - /// <remarks> - /// When using a geographic reference system, the first component of all the coordinates in each <pos> element in the GML DOM tree is the Latitude and - /// will be deserialized as the second component of each <pos> element in the GML DOM tree. - /// </remarks> - /// <returns>Spatial property value in GeoJSON format.</returns> - - var gmlRoot = xmlFirstChildElement(domElement, gmlXmlNs); - djsassert(gmlRoot, "xmlReadODataSpatialPropertyValue - domElement doesn't have a child element that belongs to the gml namespace!!"); - - var value = gmlReadODataSpatialValue(gmlRoot, isGeography); - value.__metadata = { type: propertyType }; - return value; - }; - - var xmlReadODataEdmPropertyValue = function (domNode, propertyType) { - /// <summary>Reads the value of an EDM property in an OData XML document.</summary> - /// <param name="donNode">DOM node for the EDM property.</param> - /// <param name="propertyType" type="String">Property type name.</param> - /// <returns>EDM property value.</returns> - - var propertyValue = xmlNodeValue(domNode) || ""; - - switch (propertyType) { - case EDM_BOOLEAN: - return parseBool(propertyValue); - case EDM_BINARY: - case EDM_DECIMAL: - case EDM_GUID: - case EDM_INT64: - case EDM_STRING: - return propertyValue; - case EDM_BYTE: - case EDM_INT16: - case EDM_INT32: - case EDM_SBYTE: - return parseInt10(propertyValue); - case EDM_DOUBLE: - case EDM_SINGLE: - return parseFloat(propertyValue); - case EDM_TIME: - return parseDuration(propertyValue); - case EDM_DATETIME: - return parseDateTime(propertyValue); - case EDM_DATETIMEOFFSET: - return parseDateTimeOffset(propertyValue); - } - - return propertyValue; - }; - - var xmlReadODataComplexPropertyValue = function(domElement, propertyType, propertyMetadata) { - /// <summary>Reads the value of a complex type property in an OData XML document.</summary> - /// <param name="property">DOM element for the complex type property.</param> - /// <param name="propertyType" type="String">Property type name.</param> - /// <param name="propertyMetadata" type="Object">Object that will store metadata about the property.</param> - /// <returns type="Object">Complex type property value.</returns> - - var propertyValue = { __metadata: { type: propertyType } }; - xmlChildElements(domElement, function(child) { - var childProperty = xmlReadODataProperty(child); - var childPropertyName = childProperty.name; - - propertyMetadata.properties = propertyMetadata.properties || {}; - propertyMetadata.properties[childPropertyName] = childProperty.metadata; - propertyValue[childPropertyName] = childProperty.value; - }); - - return propertyValue; - }; - - var xmlReadODataCollectionPropertyValue = function (domElement, propertyType, propertyMetadata) { - /// <summary>Reads the value of a collection property in an OData XML document.</summary> - /// <param name="property">DOM element for the collection property.</param> - /// <param name="propertyType" type="String">Property type name.</param> - /// <param name="propertyMetadata" type="Object">Object that will store metadata about the property.</param> - /// <returns type="Object">Collection property value.</returns> - - var items = []; - var itemsMetadata = propertyMetadata.elements = []; - var collectionType = getCollectionType(propertyType); - - xmlChildElements(domElement, function (child) { - if (isCollectionItemElement(child)) { - var itemAttributes = xmlReadODataPropertyAttributes(child); - var itemExtensions = itemAttributes.extensions; - var itemType = itemAttributes.type || collectionType; - var itemMetadata = makePropertyMetadata(itemType, itemExtensions); - - var item = xmlReadODataPropertyValue(child, itemType, itemMetadata); - - items.push(item); - itemsMetadata.push(itemMetadata); - } - }); - - return { __metadata: { type: propertyType === "Collection()" ? null : propertyType }, results: items }; - }; - - var readODataXmlDocument = function (xmlRoot, baseURI) { - /// <summary>Reads an OData link(s) producing an object model in return.</summary> - /// <param name="xmlRoot">Top-level element to read.</param> - /// <param name="baseURI" type="String">Base URI for normalizing relative URIs found in the XML payload.</param> - /// <returns type="Object">The object model representing the specified element.</returns> - - if (xmlNamespaceURI(xmlRoot) === odataXmlNs) { - baseURI = xmlBaseURI(xmlRoot, baseURI); - var localName = xmlLocalName(xmlRoot); - - if (localName === "links") { - return readLinks(xmlRoot, baseURI); - } - if (localName === "uri") { - return readUri(xmlRoot, baseURI); - } - } - return undefined; - }; - - var readLinks = function (linksElement, baseURI) { - /// <summary>Deserializes an OData XML links element.</summary> - /// <param name="linksElement">XML links element.</param> - /// <param name="baseURI" type="String">Base URI for normalizing relative URIs found in the XML payload.</param> - /// <returns type="Object">A new object representing the links collection.</returns> - - var uris = []; - - xmlChildElements(linksElement, function (child) { - if (xmlLocalName(child) === "uri" && xmlNamespaceURI(child) === odataXmlNs) { - uris.push(readUri(child, baseURI)); - } - }); - - return { results: uris }; - }; - - var readUri = function (uriElement, baseURI) { - /// <summary>Deserializes an OData XML uri element.</summary> - /// <param name="uriElement">XML uri element.</param> - /// <param name="baseURI" type="String">Base URI for normalizing relative URIs found in the XML payload.</param> - /// <returns type="Object">A new object representing the uri.</returns> - - var uri = xmlInnerText(uriElement) || ""; - return { uri: normalizeURI(uri, baseURI) }; - }; - - var xmlODataInferSpatialValueGeoJsonType = function (value, edmType) { - /// <summary>Infers the GeoJSON type from the spatial property value and the edm type name.</summary> - /// <param name="value" type="Object">Spatial property value in GeoJSON format.</param> - /// <param name="edmType" type="String" mayBeNull="true" optional="true">Spatial property edm type.<param> - /// <remarks> - /// If the edmType parameter is null, undefined, "Edm.Geometry" or "Edm.Geography", then the function returns - /// the GeoJSON type indicated by the value's type property. - /// - /// If the edmType parameter is specified or is not one of the base spatial types, then it is used to - /// determine the GeoJSON type and the value's type property is ignored. - /// </remarks> - /// <returns>New DOM element in the GML namespace for the spatial value. </returns> - - if (edmType === EDM_GEOMETRY || edmType === EDM_GEOGRAPHY) { - return value && value.type; - } - - if (edmType === EDM_GEOMETRY_POINT || edmType === EDM_GEOGRAPHY_POINT) { - return GEOJSON_POINT; - } - - if (edmType === EDM_GEOMETRY_LINESTRING || edmType === EDM_GEOGRAPHY_LINESTRING) { - return GEOJSON_LINESTRING; - } - - if (edmType === EDM_GEOMETRY_POLYGON || edmType === EDM_GEOGRAPHY_POLYGON) { - return GEOJSON_POLYGON; - } - - if (edmType === EDM_GEOMETRY_COLLECTION || edmType === EDM_GEOGRAPHY_COLLECTION) { - return GEOJSON_GEOMETRYCOLLECTION; - } - - if (edmType === EDM_GEOMETRY_MULTIPOLYGON || edmType === EDM_GEOGRAPHY_MULTIPOLYGON) { - return GEOJSON_MULTIPOLYGON; - } - - if (edmType === EDM_GEOMETRY_MULTILINESTRING || edmType === EDM_GEOGRAPHY_MULTILINESTRING) { - return GEOJSON_MULTILINESTRING; - } - - if (edmType === EDM_GEOMETRY_MULTIPOINT || edmType === EDM_GEOGRAPHY_MULTIPOINT) { - return GEOJSON_MULTIPOINT; - } - - djsassert(false, "gmlInferGeoJsonType - edm type <" + edmType + "> was unexpected!!"); - return null; - }; - - var xmlNewODataMetaElement = function (dom, name, children) { - /// <summary>Creates a new DOM element in the OData metadata namespace.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Local name of the OData metadata element to create.</param> - /// <param name="children" type="Array">Array containing DOM nodes or string values that will be added as children of the new DOM element.</param> - /// <returns>New DOM element in the OData metadata namespace.</returns> - /// <remarks> - /// If a value in the children collection is a string, then a new DOM text node is going to be created - /// for it and then appended as a child of the new DOM Element. - /// </remarks> - - return xmlNewElement(dom, odataMetaXmlNs, xmlQualifiedName(odataMetaPrefix, name), children); - }; - - var xmlNewODataMetaAttribute = function (dom, name, value) { - /// <summary>Creates a new DOM attribute in the odata namespace.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Local name of the OData attribute to create.</param> - /// <param name="value">Attribute value.</param> - /// <returns>New DOM attribute in the odata namespace.</returns> - - return xmlNewAttribute(dom, odataMetaXmlNs, xmlQualifiedName(odataMetaPrefix, name), value); - }; - - var xmlNewODataElement = function (dom, name, children) { - /// <summary>Creates a new DOM element in the OData namespace.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Local name of the OData element to create.</param> - /// <param name="children" type="Array">Array containing DOM nodes or string values that will be added as children of the new DOM element.</param> - /// <returns>New DOM element in the OData namespace.</returns> - /// <remarks> - /// If a value in the children collection is a string, then a new DOM text node is going to be created - /// for it and then appended as a child of the new DOM Element. - /// </remarks> - - return xmlNewElement(dom, odataXmlNs, xmlQualifiedName(odataPrefix, name), children); - }; - - var xmlNewODataPrimitiveValue = function (value, typeName) { - /// <summary>Returns the string representation of primitive value for an OData XML document.</summary> - /// <param name="value">Primivite value to format.</param> - /// <param name="typeName" type="String" optional="true">Type name of the primitive value.</param> - /// <returns type="String">Formatted primitive value.</returns> - - if (typeName === EDM_DATETIME || typeName === EDM_DATETIMEOFFSET || isDate(value)) { - return formatDateTimeOffset(value); - } - if (typeName === EDM_TIME) { - return formatDuration(value); - } - return value.toString(); - }; - - var xmlNewODataElementInfo = function (domElement, dataServiceVersion) { - /// <summary>Creates an object that represents a new DOM element for an OData XML document and the data service version it requires.</summary> - /// <param name="domElement">New DOM element for an OData XML document.</param> - /// <param name="dataServiceVersion" type="String">Required data service version by the new DOM element.</param> - /// <returns type="Object">Object containing new DOM element and its required data service version.</returns> - - return { element: domElement, dsv: dataServiceVersion }; - }; - - var xmlNewODataProperty = function (dom, name, typeName, children) { - /// <summary>Creates a new DOM element for an entry property in an OData XML document.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Property name.</param> - /// <param name="typeName" type="String" optional="true">Property type name.</param> - /// <param name="children" type="Array">Array containing DOM nodes or string values that will be added as children of the new DOM element.</param> - /// <remarks> - /// If a value in the children collection is a string, then a new DOM text node is going to be created - /// for it and then appended as a child of the new DOM Element. - /// </remarks> - /// <returns>New DOM element in the OData namespace for the entry property.</returns> - - var typeAttribute = typeName ? xmlNewODataMetaAttribute(dom, "type", typeName) : null; - var property = xmlNewODataElement(dom, name, typeAttribute); - return xmlAppendChildren(property, children); - }; - - var xmlNewODataEdmProperty = function (dom, name, value, typeName) { - /// <summary>Creates a new DOM element for an EDM property in an OData XML document.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Property name.</param> - /// <param name="value">Property value.</param> - /// <param name="typeName" type="String" optional="true">Property type name.</param> - /// <returns type="Object"> - /// Object containing the new DOM element in the OData namespace for the EDM property and the - /// required data service version for this property. - /// </returns> - - var propertyValue = xmlNewODataPrimitiveValue(value, typeName); - var property = xmlNewODataProperty(dom, name, typeName, propertyValue); - return xmlNewODataElementInfo(property, /*dataServiceVersion*/"4.0"); - }; - - var xmlNewODataNullProperty = function (dom, name, typeName, model) { - /// <summary>Creates a new DOM element for a null property in an OData XML document.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Property name.</param> - /// <param name="typeName" type="String" optional="true">Property type name.</param> - /// <param name="model" type="Object" optional="true">Object describing an OData conceptual schema.</param> - /// <remarks> - /// If no typeName is specified, then it will be assumed that this is a primitive type property. - /// </remarks> - /// <returns type="Object"> - /// Object containing the new DOM element in the OData namespace for the null property and the - /// required data service version for this property. - /// </returns> - - var nullAttribute = xmlNewODataMetaAttribute(dom, "null", "true"); - var property = xmlNewODataProperty(dom, name, typeName, nullAttribute); - var dataServiceVersion = lookupComplexType(typeName, model) ? "2.0" : "1.0"; - - return xmlNewODataElementInfo(property, dataServiceVersion); - }; - - var xmlNewODataCollectionProperty = function (dom, name, value, typeName, collectionMetadata, collectionModel, model) { - /// <summary>Creates a new DOM element for a collection property in an OData XML document.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Property name.</param> - /// <param name="value">Property value either as an array or an object representing a collection in the library's internal representation.</param> - /// <param name="typeName" type="String" optional="true">Property type name.</param> - /// <param name="collectionMetadata" type="Object" optional="true">Object containing metadata about the collection property.</param> - /// <param name="collectionModel" type="Object" optional="true">Object describing the collection property in an OData conceptual schema.</param> - /// <param name="model" type="Object" optional="true">Object describing an OData conceptual schema.</param> - /// <returns type="Object"> - /// Object containing the new DOM element in the OData namespace for the collection property and the - /// required data service version for this property. - /// </returns> - - var itemTypeName = getCollectionType(typeName); - var items = isArray(value) ? value : value.results; - var itemMetadata = typeName ? { type: itemTypeName} : {}; - itemMetadata.properties = collectionMetadata.properties; - - var xmlProperty = xmlNewODataProperty(dom, name, itemTypeName ? typeName : null); - - var i, len; - for (i = 0, len = items.length; i < len; i++) { - var itemValue = items[i]; - var item = xmlNewODataDataElement(dom, "element", itemValue, itemMetadata, collectionModel, model); - - xmlAppendChild(xmlProperty, item.element); - } - return xmlNewODataElementInfo(xmlProperty, /*dataServiceVersion*/"4.0"); - }; - - var xmlNewODataComplexProperty = function (dom, name, value, typeName, propertyMetadata, propertyModel, model) { - /// <summary>Creates a new DOM element for a complex type property in an OData XML document.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Property name.</param> - /// <param name="value">Property value as an object in the library's internal representation.</param> - /// <param name="typeName" type="String" optional="true">Property type name.</param> - /// <param name="propertyMetadata" type="Object" optional="true">Object containing metadata about the complex type property.</param> - /// <param name="propertyModel" type="Object" optional="true">Object describing the complex type property in an OData conceptual schema.</param> - /// <param name="model" type="Object" optional="true">Object describing an OData conceptual schema.</param> - /// <returns type="Object"> - /// Object containing the new DOM element in the OData namespace for the complex type property and the - /// required data service version for this property. - /// </returns> - - var xmlProperty = xmlNewODataProperty(dom, name, typeName); - var complexTypePropertiesMetadata = propertyMetadata.properties || {}; - var complexTypeModel = lookupComplexType(typeName, model) || {}; - - var dataServiceVersion = "4.0"; - - for (var key in value) { - if (key !== "__metadata") { - var memberValue = value[key]; - var memberModel = lookupProperty(complexTypeModel.property, key); - var memberMetadata = complexTypePropertiesMetadata[key] || {}; - var member = xmlNewODataDataElement(dom, key, memberValue, memberMetadata, memberModel, model); - - dataServiceVersion = maxVersion(dataServiceVersion, member.dsv); - xmlAppendChild(xmlProperty, member.element); - } - } - return xmlNewODataElementInfo(xmlProperty, dataServiceVersion); - }; - - var xmlNewODataSpatialProperty = function (dom, name, value, typeName, isGeography) { - /// <summary>Creates a new DOM element for an EDM spatial property in an OData XML document.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Property name.</param> - /// <param name="value" type="Object">GeoJSON object containing the property value.</param> - /// <param name="typeName" type="String" optional="true">Property type name.</param> - /// <returns type="Object"> - /// Object containing the new DOM element in the OData namespace for the EDM property and the - /// required data service version for this property. - /// </returns> - - var geoJsonType = xmlODataInferSpatialValueGeoJsonType(value, typeName); - - var gmlRoot = gmlNewODataSpatialValue(dom, value, geoJsonType, isGeography); - var xmlProperty = xmlNewODataProperty(dom, name, typeName, gmlRoot); - - return xmlNewODataElementInfo(xmlProperty, "4.0"); - }; - - var xmlNewODataDataElement = function (dom, name, value, dataItemMetadata, dataItemModel, model) { - /// <summary>Creates a new DOM element for a data item in an entry, complex property, or collection property.</summary> - /// <param name="dom">DOM document used for creating the new DOM Element.</param> - /// <param name="name" type="String">Data item name.</param> - /// <param name="value" optional="true" mayBeNull="true">Value of the data item, if any.</param> - /// <param name="dataItemMetadata" type="Object" optional="true">Object containing metadata about the data item.</param> - /// <param name="dataItemModel" type="Object" optional="true">Object describing the data item in an OData conceptual schema.</param> - /// <param name="model" type="Object" optional="true">Object describing an OData conceptual schema.</param> - /// <returns type="Object"> - /// Object containing the new DOM element in the appropriate namespace for the data item and the - /// required data service version for it. - /// </returns> - - var typeName = dataItemTypeName(value, dataItemMetadata, dataItemModel); - if (isPrimitive(value)) { - return xmlNewODataEdmProperty(dom, name, value, typeName || EDM_STRING); - } - - var isGeography = isGeographyEdmType(typeName); - if (isGeography || isGeometryEdmType(typeName)) { - return xmlNewODataSpatialProperty(dom, name, value, typeName, isGeography); - } - - if (isCollection(value, typeName)) { - return xmlNewODataCollectionProperty(dom, name, value, typeName, dataItemMetadata, dataItemModel, model); - } - - if (isNamedStream(value)) { - return null; - } - - // This may be a navigation property. - var navPropKind = navigationPropertyKind(value, dataItemModel); - if (navPropKind !== null) { - return null; - } - - if (value === null) { - return xmlNewODataNullProperty(dom, name, typeName); - } - - djsassert(isObject(value), "xmlNewODataEntryProperty - property '" + name + "' is not an object"); - return xmlNewODataComplexProperty(dom, name, value, typeName, dataItemMetadata, dataItemModel, model); - }; - - var odataNewLinkDocument = function (data) { - /// <summary>Writes the specified data into an OData XML document.</summary> - /// <param name="data">Data to write.</param> - /// <returns>The root of the DOM tree built.</returns> - - if (data && isObject(data)) { - var dom = xmlDom(); - return xmlAppendChild(dom, xmlNewODataElement(dom, "uri", data.uri)); - } - // Allow for undefined to be returned. - }; - - var xmlParser = function (handler, text) { - /// <summary>Parses an OData XML document.</summary> - /// <param name="handler">This handler.</param> - /// <param name="text" type="String">Document text.</param> - /// <returns>An object representation of the document; undefined if not applicable.</returns> - - if (text) { - var doc = xmlParse(text); - var root = xmlFirstChildElement(doc); - if (root) { - return readODataXmlDocument(root); - } - } - - // Allow for undefined to be returned. - }; - - var xmlSerializer = function (handler, data, context) { - /// <summary>Serializes an OData XML object into a document.</summary> - /// <param name="handler">This handler.</param> - /// <param name="data" type="Object">Representation of feed or entry.</param> - /// <param name="context" type="Object">Object with parsing context.</param> - /// <returns>A text representation of the data object; undefined if not applicable.</returns> - - var cType = context.contentType = context.contentType || contentType(xmlMediaType); - if (cType && cType.mediaType === xmlMediaType) { - return xmlSerialize(odataNewLinkDocument(data)); - } - return undefined; - }; - - odata.xmlHandler = handler(xmlParser, xmlSerializer, xmlMediaType, MAX_DATA_SERVICE_VERSION); - - // DATAJS INTERNAL START - odata.adoDs = adoDs; - odata.createAttributeExtension = createAttributeExtension; - odata.createElementExtension = createElementExtension; - odata.edmxNs = edmxNs; - odata.edmNs1 = edmNs1; - odata.odataMetaXmlNs = odataMetaXmlNs; - odata.odataMetaPrefix = odataMetaPrefix; - odata.odataXmlNs = odataXmlNs; - odata.odataPrefix = odataPrefix; - odata.odataScheme = odataScheme; - odata.odataRelatedPrefix = odataRelatedPrefix; - odata.xmlNewODataElement = xmlNewODataElement; - odata.xmlNewODataElementInfo = xmlNewODataElementInfo; - odata.xmlNewODataMetaAttribute = xmlNewODataMetaAttribute; - odata.xmlNewODataMetaElement = xmlNewODataMetaElement; - odata.xmlNewODataDataElement = xmlNewODataDataElement; - odata.xmlReadODataEdmPropertyValue = xmlReadODataEdmPropertyValue; - odata.xmlReadODataProperty = xmlReadODataProperty; - - // DATAJS INTERNAL END - - // CONTENT END -})(this); \ No newline at end of file
http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/4621d41c/JSLib/src/odata.js ---------------------------------------------------------------------- diff --git a/JSLib/src/odata.js b/JSLib/src/odata.js deleted file mode 100644 index 10a6d2b..0000000 --- a/JSLib/src/odata.js +++ /dev/null @@ -1,155 +0,0 @@ -// 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. - -// odata.js - -(function (window, undefined) { - - var datajs = window.odatajs || {}; - var odata = window.OData || {}; - - // Imports - - var assigned = odatajs.assigned; - var defined = odatajs.defined; - var throwErrorCallback = odatajs.throwErrorCallback; - - var invokeRequest = odata.invokeRequest; - var MAX_DATA_SERVICE_VERSION = odata.MAX_DATA_SERVICE_VERSION; - var prepareRequest = odata.prepareRequest; - var metadataParser = odata.metadataParser; - - // CONTENT START - - // to do: disable atom scenario - var handlers = [odata.jsonHandler/*, odata.atomHandler*/, odata.xmlHandler, odata.textHandler]; - - var dispatchHandler = function (handlerMethod, requestOrResponse, context) { - /// <summary>Dispatches an operation to handlers.</summary> - /// <param name="handlerMethod" type="String">Name of handler method to invoke.</param> - /// <param name="requestOrResponse" type="Object">request/response argument for delegated call.</param> - /// <param name="context" type="Object">context argument for delegated call.</param> - - var i, len; - for (i = 0, len = handlers.length; i < len && !handlers[i][handlerMethod](requestOrResponse, context); i++) { - } - - if (i === len) { - throw { message: "no handler for data" }; - } - }; - - odata.defaultSuccess = function (data) { - /// <summary>Default success handler for OData.</summary> - /// <param name="data">Data to process.</param> - - window.alert(window.JSON.stringify(data)); - }; - - odata.defaultError = throwErrorCallback; - - odata.defaultHandler = { - read: function (response, context) { - /// <summary>Reads the body of the specified response by delegating to JSON and ATOM handlers.</summary> - /// <param name="response">Response object.</param> - /// <param name="context">Operation context.</param> - - if (response && assigned(response.body) && response.headers["Content-Type"]) { - dispatchHandler("read", response, context); - } - }, - - write: function (request, context) { - /// <summary>Write the body of the specified request by delegating to JSON and ATOM handlers.</summary> - /// <param name="request">Reques tobject.</param> - /// <param name="context">Operation context.</param> - - dispatchHandler("write", request, context); - }, - - maxDataServiceVersion: MAX_DATA_SERVICE_VERSION, - accept: "application/json;q=0.9, application/atomsvc+xml;q=0.8, */*;q=0.1" - }; - - odata.defaultMetadata = []; - - odata.read = function (urlOrRequest, success, error, handler, httpClient, metadata) { - /// <summary>Reads data from the specified URL.</summary> - /// <param name="urlOrRequest">URL to read data from.</param> - /// <param name="success" type="Function" optional="true">Callback for a successful read operation.</param> - /// <param name="error" type="Function" optional="true">Callback for handling errors.</param> - /// <param name="handler" type="Object" optional="true">Handler for data serialization.</param> - /// <param name="httpClient" type="Object" optional="true">HTTP client layer.</param> - /// <param name="metadata" type="Object" optional="true">Conceptual metadata for this request.</param> - - var request; - if (urlOrRequest instanceof String || typeof urlOrRequest === "string") { - request = { requestUri: urlOrRequest }; - } else { - request = urlOrRequest; - } - - return odata.request(request, success, error, handler, httpClient, metadata); - }; - - odata.request = function (request, success, error, handler, httpClient, metadata) { - /// <summary>Sends a request containing OData payload to a server.</summary> - /// <param name="request" type="Object">Object that represents the request to be sent.</param> - /// <param name="success" type="Function" optional="true">Callback for a successful read operation.</param> - /// <param name="error" type="Function" optional="true">Callback for handling errors.</param> - /// <param name="handler" type="Object" optional="true">Handler for data serialization.</param> - /// <param name="httpClient" type="Object" optional="true">HTTP client layer.</param> - /// <param name="metadata" type="Object" optional="true">Conceptual metadata for this request.</param> - - success = success || odata.defaultSuccess; - error = error || odata.defaultError; - handler = handler || odata.defaultHandler; - httpClient = httpClient || odata.defaultHttpClient; - metadata = metadata || odata.defaultMetadata; - - // Augment the request with additional defaults. - request.recognizeDates = defined(request.recognizeDates, odata.jsonHandler.recognizeDates); - request.callbackParameterName = defined(request.callbackParameterName, odata.defaultHttpClient.callbackParameterName); - request.formatQueryString = defined(request.formatQueryString, odata.defaultHttpClient.formatQueryString); - request.enableJsonpCallback = defined(request.enableJsonpCallback, odata.defaultHttpClient.enableJsonpCallback); - - // Create the base context for read/write operations, also specifying complete settings. - var context = { - metadata: metadata, - recognizeDates: request.recognizeDates, - callbackParameterName: request.callbackParameterName, - formatQueryString: request.formatQueryString, - enableJsonpCallback: request.enableJsonpCallback - }; - - try { - prepareRequest(request, handler, context); - return invokeRequest(request, success, error, handler, httpClient, context); - } catch (err) { - error(err); - } - }; - - odata.parseMetadata = function (csdlMetadataDocument) { - /// <summary>Parses the csdl metadata to DataJS metatdata format. This method can be used when the metadata is retrieved using something other than DataJS</summary> - /// <param name="atomMetadata" type="string">A string that represents the entire csdl metadata.</param> - /// <returns type="Object">An object that has the representation of the metadata in Datajs format.</returns> - - return metadataParser(null, csdlMetadataDocument); - }; - - // Configure the batch handler to use the default handler for the batch parts. - odata.batchHandler.partHandler = odata.defaultHandler; - - // CONTENT END -})(this); \ No newline at end of file http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/4621d41c/JSLib/src/store-dom.js ---------------------------------------------------------------------- diff --git a/JSLib/src/store-dom.js b/JSLib/src/store-dom.js deleted file mode 100644 index d3aafa0..0000000 --- a/JSLib/src/store-dom.js +++ /dev/null @@ -1,320 +0,0 @@ -// 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. - -// store-dom.js - -(function (window, undefined) { - - var datajs = window.odatajs || {}; - - // Imports. - var throwErrorCallback = odatajs.throwErrorCallback; - var delay = odatajs.delay; - - // CONTENT START - - var localStorage = null; - - var domStoreDateToJSON = function () { - /// <summary>Converts a Date object into an object representation friendly to JSON serialization.</summary> - /// <returns type="Object">Object that represents the Date.</returns> - /// <remarks> - /// This method is used to override the Date.toJSON method and is called only by - /// JSON.stringify. It should never be called directly. - /// </remarks> - - var newValue = { v: this.valueOf(), t: "[object Date]" }; - // Date objects might have extra properties on them so we save them. - for (var name in this) { - newValue[name] = this[name]; - } - return newValue; - }; - - var domStoreJSONToDate = function (_, value) { - /// <summary>JSON reviver function for converting an object representing a Date in a JSON stream to a Date object</summary> - /// <param value="Object">Object to convert.</param> - /// <returns type="Date">Date object.</returns> - /// <remarks> - /// This method is used during JSON parsing and invoked only by the reviver function. - /// It should never be called directly. - /// </remarks> - - if (value && value.t === "[object Date]") { - var newValue = new Date(value.v); - for (var name in value) { - if (name !== "t" && name !== "v") { - newValue[name] = value[name]; - } - } - value = newValue; - } - return value; - }; - - var qualifyDomStoreKey = function (store, key) { - /// <summary>Qualifies the key with the name of the store.</summary> - /// <param name="store" type="Object">Store object whose name will be used for qualifying the key.</param> - /// <param name="key" type="String">Key string.</param> - /// <returns type="String">Fully qualified key string.</returns> - - return store.name + "#!#" + key; - }; - - var unqualifyDomStoreKey = function (store, key) { - /// <summary>Gets the key part of a fully qualified key string.</summary> - /// <param name="store" type="Object">Store object whose name will be used for qualifying the key.</param> - /// <param name="key" type="String">Fully qualified key string.</param> - /// <returns type="String">Key part string</returns> - - return key.replace(store.name + "#!#", ""); - }; - - var DomStore = function (name) { - /// <summary>Constructor for store objects that use DOM storage as the underlying mechanism.</summary> - /// <param name="name" type="String">Store name.</param> - this.name = name; - }; - - DomStore.create = function (name) { - /// <summary>Creates a store object that uses DOM Storage as its underlying mechanism.</summary> - /// <param name="name" type="String">Store name.</param> - /// <returns type="Object">Store object.</returns> - - if (DomStore.isSupported()) { - localStorage = localStorage || window.localStorage; - return new DomStore(name); - } - - throw { message: "Web Storage not supported by the browser" }; - }; - - DomStore.isSupported = function () { - /// <summary>Checks whether the underlying mechanism for this kind of store objects is supported by the browser.</summary> - /// <returns type="Boolean">True if the mechanism is supported by the browser; otherwise false.</summary> - return !!window.localStorage; - }; - - DomStore.prototype.add = function (key, value, success, error) { - /// <summary>Adds a new value identified by a key to the store.</summary> - /// <param name="key" type="String">Key string.</param> - /// <param name="value">Value that is going to be added to the store.</param> - /// <param name="success" type="Function" optional="no">Callback for a successful add operation.</param> - /// <param name="error" type="Function" optional="yes">Callback for handling errors. If not specified then store.defaultError is invoked.</param> - /// <remarks> - /// This method errors out if the store already contains the specified key. - /// </remarks> - - error = error || this.defaultError; - var store = this; - this.contains(key, function (contained) { - if (!contained) { - store.addOrUpdate(key, value, success, error); - } else { - delay(error, { message: "key already exists", key: key }); - } - }, error); - }; - - DomStore.prototype.addOrUpdate = function (key, value, success, error) { - /// <summary>Adds or updates a value identified by a key to the store.</summary> - /// <param name="key" type="String">Key string.</param> - /// <param name="value">Value that is going to be added or updated to the store.</param> - /// <param name="success" type="Function" optional="no">Callback for a successful add or update operation.</param> - /// <param name="error" type="Function" optional="yes">Callback for handling errors. If not specified then store.defaultError is invoked.</param> - /// <remarks> - /// This method will overwrite the key's current value if it already exists in the store; otherwise it simply adds the new key and value. - /// </remarks> - - error = error || this.defaultError; - - if (key instanceof Array) { - error({ message: "Array of keys not supported" }); - } else { - var fullKey = qualifyDomStoreKey(this, key); - var oldDateToJSON = Date.prototype.toJSON; - try { - var storedValue = value; - if (storedValue !== undefined) { - // Dehydrate using json - Date.prototype.toJSON = domStoreDateToJSON; - storedValue = window.JSON.stringify(value); - } - // Save the json string. - localStorage.setItem(fullKey, storedValue); - delay(success, key, value); - } - catch (e) { - if (e.code === 22 || e.number === 0x8007000E) { - delay(error, { name: "QUOTA_EXCEEDED_ERR", error: e }); - } else { - delay(error, e); - } - } - finally { - Date.prototype.toJSON = oldDateToJSON; - } - } - }; - - DomStore.prototype.clear = function (success, error) { - /// <summary>Removes all the data associated with this store object.</summary> - /// <param name="success" type="Function" optional="no">Callback for a successful clear operation.</param> - /// <param name="error" type="Function" optional="yes">Callback for handling errors. If not specified then store.defaultError is invoked.</param> - /// <remarks> - /// In case of an error, this method will not restore any keys that might have been deleted at that point. - /// </remarks> - - error = error || this.defaultError; - try { - var i = 0, len = localStorage.length; - while (len > 0 && i < len) { - var fullKey = localStorage.key(i); - var key = unqualifyDomStoreKey(this, fullKey); - if (fullKey !== key) { - localStorage.removeItem(fullKey); - len = localStorage.length; - } else { - i++; - } - } - delay(success); - } - catch (e) { - delay(error, e); - } - }; - - DomStore.prototype.close = function () { - /// <summary>This function does nothing in DomStore as it does not have a connection model</summary> - }; - - DomStore.prototype.contains = function (key, success, error) { - /// <summary>Checks whether a key exists in the store.</summary> - /// <param name="key" type="String">Key string.</param> - /// <param name="success" type="Function" optional="no">Callback indicating whether the store contains the key or not.</param> - /// <param name="error" type="Function" optional="yes">Callback for handling errors. If not specified then store.defaultError is invoked.</param> - error = error || this.defaultError; - try { - var fullKey = qualifyDomStoreKey(this, key); - var value = localStorage.getItem(fullKey); - delay(success, value !== null); - } catch (e) { - delay(error, e); - } - }; - - DomStore.prototype.defaultError = throwErrorCallback; - - DomStore.prototype.getAllKeys = function (success, error) { - /// <summary>Gets all the keys that exist in the store.</summary> - /// <param name="success" type="Function" optional="no">Callback for a successful get operation.</param> - /// <param name="error" type="Function" optional="yes">Callback for handling errors. If not specified then store.defaultError is invoked.</param> - - error = error || this.defaultError; - - var results = []; - var i, len; - - try { - for (i = 0, len = localStorage.length; i < len; i++) { - var fullKey = localStorage.key(i); - var key = unqualifyDomStoreKey(this, fullKey); - if (fullKey !== key) { - results.push(key); - } - } - delay(success, results); - } - catch (e) { - delay(error, e); - } - }; - - /// <summary>Identifies the underlying mechanism used by the store.</summary> - DomStore.prototype.mechanism = "dom"; - - DomStore.prototype.read = function (key, success, error) { - /// <summary>Reads the value associated to a key in the store.</summary> - /// <param name="key" type="String">Key string.</param> - /// <param name="success" type="Function" optional="no">Callback for a successful reads operation.</param> - /// <param name="error" type="Function" optional="yes">Callback for handling errors. If not specified then store.defaultError is invoked.</param> - error = error || this.defaultError; - - if (key instanceof Array) { - error({ message: "Array of keys not supported" }); - } else { - try { - var fullKey = qualifyDomStoreKey(this, key); - var value = localStorage.getItem(fullKey); - if (value !== null && value !== "undefined") { - // Hydrate using json - value = window.JSON.parse(value, domStoreJSONToDate); - } - else { - value = undefined; - } - delay(success, key, value); - } catch (e) { - delay(error, e); - } - } - }; - - DomStore.prototype.remove = function (key, success, error) { - /// <summary>Removes a key and its value from the store.</summary> - /// <param name="key" type="String">Key string.</param> - /// <param name="success" type="Function" optional="no">Callback for a successful remove operation.</param> - /// <param name="error" type="Function" optional="yes">Callback for handling errors. If not specified then store.defaultError is invoked.</param> - error = error || this.defaultError; - - if (key instanceof Array) { - error({ message: "Batches not supported" }); - } else { - try { - var fullKey = qualifyDomStoreKey(this, key); - localStorage.removeItem(fullKey); - delay(success); - } catch (e) { - delay(error, e); - } - } - }; - - DomStore.prototype.update = function (key, value, success, error) { - /// <summary>Updates the value associated to a key in the store.</summary> - /// <param name="key" type="String">Key string.</param> - /// <param name="value">New value.</param> - /// <param name="success" type="Function" optional="no">Callback for a successful update operation.</param> - /// <param name="error" type="Function" optional="yes">Callback for handling errors. If not specified then store.defaultError is invoked.</param> - /// <remarks> - /// This method errors out if the specified key is not found in the store. - /// </remarks> - - error = error || this.defaultError; - var store = this; - this.contains(key, function (contained) { - if (contained) { - store.addOrUpdate(key, value, success, error); - } else { - delay(error, { message: "key not found", key: key }); - } - }, error); - }; - - // DATAJS INTERNAL START - odatajs.DomStore = DomStore; - // DATAJS INTERNAL END - - // CONTENT END -})(this); \ No newline at end of file http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/4621d41c/JSLib/src/store-indexeddb.js ---------------------------------------------------------------------- diff --git a/JSLib/src/store-indexeddb.js b/JSLib/src/store-indexeddb.js deleted file mode 100644 index 1a0483c..0000000 --- a/JSLib/src/store-indexeddb.js +++ /dev/null @@ -1,417 +0,0 @@ -// 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. - -// store-indexeddb.js - -(function (window, undefined) { - - var datajs = window.odatajs || {}; - - // Imports. - var throwErrorCallback = odatajs.throwErrorCallback; - var delay = odatajs.delay; - - // CONTENT START - - var indexedDB = window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.indexedDB; - var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange; - var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || {}; - - var IDBT_READ_ONLY = IDBTransaction.READ_ONLY || "readonly"; - var IDBT_READ_WRITE = IDBTransaction.READ_WRITE || "readwrite"; - - var getError = function (error, defaultError) { - /// <summary>Returns either a specific error handler or the default error handler</summary> - /// <param name="error" type="Function">The specific error handler</param> - /// <param name="defaultError" type="Function">The default error handler</param> - /// <returns type="Function">The error callback</returns> - - return function (e) { - var errorFunc = error || defaultError; - if (!errorFunc) { - return; - } - - // Old api quota exceeded error support. - if (Object.prototype.toString.call(e) === "[object IDBDatabaseException]") { - if (e.code === 11 /* IndexedDb disk quota exceeded */) { - errorFunc({ name: "QuotaExceededError", error: e }); - return; - } - errorFunc(e); - return; - } - - var errName; - try { - var errObj = e.target.error || e; - errName = errObj.name; - } catch (ex) { - errName = (e.type === "blocked") ? "IndexedDBBlocked" : "UnknownError"; - } - errorFunc({ name: errName, error: e }); - }; - }; - - var openStoreDb = function (store, success, error) { - /// <summary>Opens the store object's indexed db database.</summary> - /// <param name="store" type="IndexedDBStore">The store object</param> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - - var storeName = store.name; - var dbName = "_datajs_" + storeName; - - var request = indexedDB.open(dbName); - request.onblocked = error; - request.onerror = error; - - request.onupgradeneeded = function () { - var db = request.result; - if (!db.objectStoreNames.contains(storeName)) { - db.createObjectStore(storeName); - } - }; - - request.onsuccess = function (event) { - var db = request.result; - if (!db.objectStoreNames.contains(storeName)) { - // Should we use the old style api to define the database schema? - if ("setVersion" in db) { - var versionRequest = db.setVersion("1.0"); - versionRequest.onsuccess = function () { - var transaction = versionRequest.transaction; - transaction.oncomplete = function () { - success(db); - }; - db.createObjectStore(storeName, null, false); - }; - versionRequest.onerror = error; - versionRequest.onblocked = error; - return; - } - - // The database doesn't have the expected store. - // Fabricate an error object for the event for the schema mismatch - // and error out. - event.target.error = { name: "DBSchemaMismatch" }; - error(event); - return; - } - - db.onversionchange = function(event) { - event.target.close(); - }; - success(db); - }; - }; - - var openTransaction = function (store, mode, success, error) { - /// <summary>Opens a new transaction to the store</summary> - /// <param name="store" type="IndexedDBStore">The store object</param> - /// <param name="mode" type="Short">The read/write mode of the transaction (constants from IDBTransaction)</param> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - - var storeName = store.name; - var storeDb = store.db; - var errorCallback = getError(error, store.defaultError); - - if (storeDb) { - success(storeDb.transaction(storeName, mode)); - return; - } - - openStoreDb(store, function (db) { - store.db = db; - success(db.transaction(storeName, mode)); - }, errorCallback); - }; - - var IndexedDBStore = function (name) { - /// <summary>Creates a new IndexedDBStore.</summary> - /// <param name="name" type="String">The name of the store.</param> - /// <returns type="Object">The new IndexedDBStore.</returns> - this.name = name; - }; - - IndexedDBStore.create = function (name) { - /// <summary>Creates a new IndexedDBStore.</summary> - /// <param name="name" type="String">The name of the store.</param> - /// <returns type="Object">The new IndexedDBStore.</returns> - if (IndexedDBStore.isSupported()) { - return new IndexedDBStore(name); - } - - throw { message: "IndexedDB is not supported on this browser" }; - }; - - IndexedDBStore.isSupported = function () { - /// <summary>Returns whether IndexedDB is supported.</summary> - /// <returns type="Boolean">True if IndexedDB is supported, false otherwise.</returns> - return !!indexedDB; - }; - - IndexedDBStore.prototype.add = function (key, value, success, error) { - /// <summary>Adds a key/value pair to the store</summary> - /// <param name="key" type="String">The key</param> - /// <param name="value" type="Object">The value</param> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - var name = this.name; - var defaultError = this.defaultError; - var keys = []; - var values = []; - - if (key instanceof Array) { - keys = key; - values = value; - } else { - keys = [key]; - values = [value]; - } - - openTransaction(this, IDBT_READ_WRITE, function (transaction) { - transaction.onabort = getError(error, defaultError, key, "add"); - transaction.oncomplete = function () { - if (key instanceof Array) { - success(keys, values); - } else { - success(key, value); - } - }; - - for (var i = 0; i < keys.length && i < values.length; i++) { - transaction.objectStore(name).add({ v: values[i] }, keys[i]); - } - }, error); - }; - - IndexedDBStore.prototype.addOrUpdate = function (key, value, success, error) { - /// <summary>Adds or updates a key/value pair in the store</summary> - /// <param name="key" type="String">The key</param> - /// <param name="value" type="Object">The value</param> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - var name = this.name; - var defaultError = this.defaultError; - var keys = []; - var values = []; - - if (key instanceof Array) { - keys = key; - values = value; - } else { - keys = [key]; - values = [value]; - } - - openTransaction(this, IDBT_READ_WRITE, function (transaction) { - transaction.onabort = getError(error, defaultError); - transaction.oncomplete = function () { - if (key instanceof Array) { - success(keys, values); - } else { - success(key, value); - } - }; - - for (var i = 0; i < keys.length && i < values.length; i++) { - var record = { v: values[i] }; - transaction.objectStore(name).put(record, keys[i]); - } - }, error); - }; - - IndexedDBStore.prototype.clear = function (success, error) { - /// <summary>Clears the store</summary> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - var name = this.name; - var defaultError = this.defaultError; - openTransaction(this, IDBT_READ_WRITE, function (transaction) { - transaction.onerror = getError(error, defaultError); - transaction.oncomplete = function () { - success(); - }; - - transaction.objectStore(name).clear(); - }, error); - }; - - IndexedDBStore.prototype.close = function () { - /// <summary>Closes the connection to the database</summary> - if (this.db) { - this.db.close(); - this.db = null; - } - }; - - IndexedDBStore.prototype.contains = function (key, success, error) { - /// <summary>Returns whether the store contains a key</summary> - /// <param name="key" type="String">The key</param> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - var name = this.name; - var defaultError = this.defaultError; - openTransaction(this, IDBT_READ_ONLY, function (transaction) { - var objectStore = transaction.objectStore(name); - var request = objectStore["get"](key); - - transaction.oncomplete = function () { - success(!!request.result); - }; - transaction.onerror = getError(error, defaultError); - }, error); - }; - - IndexedDBStore.prototype.defaultError = throwErrorCallback; - - IndexedDBStore.prototype.getAllKeys = function (success, error) { - /// <summary>Gets all the keys from the store</summary> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - var name = this.name; - var defaultError = this.defaultError; - openTransaction(this, IDBT_READ_WRITE, function (transaction) { - var results = []; - - transaction.oncomplete = function () { - success(results); - }; - - var request = transaction.objectStore(name).openCursor(); - - request.onerror = getError(error, defaultError); - request.onsuccess = function (event) { - var cursor = event.target.result; - if (cursor) { - results.push(cursor.key); - // Some tools have issues because continue is a javascript reserved word. - cursor["continue"].call(cursor); - } - }; - }, error); - }; - - /// <summary>Identifies the underlying mechanism used by the store.</summary> - IndexedDBStore.prototype.mechanism = "indexeddb"; - - IndexedDBStore.prototype.read = function (key, success, error) { - /// <summary>Reads the value for the specified key</summary> - /// <param name="key" type="String">The key</param> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - /// <remarks>If the key does not exist, the success handler will be called with value = undefined</remarks> - var name = this.name; - var defaultError = this.defaultError; - var keys = (key instanceof Array) ? key : [key]; - - openTransaction(this, IDBT_READ_ONLY, function (transaction) { - var values = []; - - transaction.onerror = getError(error, defaultError, key, "read"); - transaction.oncomplete = function () { - if (key instanceof Array) { - success(keys, values); - } else { - success(keys[0], values[0]); - } - }; - - for (var i = 0; i < keys.length; i++) { - // Some tools have issues because get is a javascript reserved word. - var objectStore = transaction.objectStore(name); - var request = objectStore["get"].call(objectStore, keys[i]); - request.onsuccess = function (event) { - var record = event.target.result; - values.push(record ? record.v : undefined); - }; - } - }, error); - }; - - IndexedDBStore.prototype.remove = function (key, success, error) { - /// <summary>Removes the specified key from the store</summary> - /// <param name="key" type="String">The key</param> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - var name = this.name; - var defaultError = this.defaultError; - var keys = (key instanceof Array) ? key : [key]; - - openTransaction(this, IDBT_READ_WRITE, function (transaction) { - transaction.onerror = getError(error, defaultError); - transaction.oncomplete = function () { - success(); - }; - - for (var i = 0; i < keys.length; i++) { - // Some tools have issues because continue is a javascript reserved word. - var objectStore = transaction.objectStore(name); - objectStore["delete"].call(objectStore, keys[i]); - } - }, error); - }; - - IndexedDBStore.prototype.update = function (key, value, success, error) { - /// <summary>Updates a key/value pair in the store</summary> - /// <param name="key" type="String">The key</param> - /// <param name="value" type="Object">The value</param> - /// <param name="success" type="Function">The success callback</param> - /// <param name="error" type="Function">The error callback</param> - var name = this.name; - var defaultError = this.defaultError; - var keys = []; - var values = []; - - if (key instanceof Array) { - keys = key; - values = value; - } else { - keys = [key]; - values = [value]; - } - - openTransaction(this, IDBT_READ_WRITE, function (transaction) { - transaction.onabort = getError(error, defaultError); - transaction.oncomplete = function () { - if (key instanceof Array) { - success(keys, values); - } else { - success(key, value); - } - }; - - for (var i = 0; i < keys.length && i < values.length; i++) { - var request = transaction.objectStore(name).openCursor(IDBKeyRange.only(keys[i])); - var record = { v: values[i] }; - request.pair = { key: keys[i], value: record }; - request.onsuccess = function (event) { - var cursor = event.target.result; - if (cursor) { - cursor.update(event.target.pair.value); - } else { - transaction.abort(); - } - }; - } - }, error); - }; - - // DATAJS INTERNAL START - odatajs.IndexedDBStore = IndexedDBStore; - // DATAJS INTERNAL END - - // CONTENT END -})(this); \ No newline at end of file
