You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@olingo.apache.org by ch...@apache.org on 2014/08/28 05:48:51 UTC
[44/51] [partial] rename folder /datajs into /odatajs. no file
modification.
http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/d5ec5557/datajs/src/lib/datajs/utils.js
----------------------------------------------------------------------
diff --git a/datajs/src/lib/datajs/utils.js b/datajs/src/lib/datajs/utils.js
deleted file mode 100644
index 27af705..0000000
--- a/datajs/src/lib/datajs/utils.js
+++ /dev/null
@@ -1,582 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-/** @module datajs/utils */
-
-
-function inBrowser() {
- return typeof window !== 'undefined';
-}
-
-/** Creates a new ActiveXObject from the given progId.
- * @param {String} progId - ProgId string of the desired ActiveXObject.
- * @returns {Object} The ActiveXObject instance. Null if ActiveX is not supported by the browser.
- * This function throws whatever exception might occur during the creation
- * of the ActiveXObject.
-*/
-var activeXObject = function (progId) {
-
- if (window.ActiveXObject) {
- return new window.ActiveXObject(progId);
- }
- return null;
-};
-
-/** Checks whether the specified value is different from null and undefined.
- * @param [value] Value to check ( may be null)
- * @returns {Boolean} true if the value is assigned; false otherwise.
-*/
-function assigned(value) {
- return value !== null && value !== undefined;
-}
-
-/** Checks whether the specified item is in the array.
- * @param {Array} [arr] Array to check in.
- * @param item - Item to look for.
- * @returns {Boolean} true if the item is contained, false otherwise.
-*/
-function contains(arr, item) {
- var i, len;
- for (i = 0, len = arr.length; i < len; i++) {
- if (arr[i] === item) {
- return true;
- }
- }
- return false;
-}
-
-/** Given two values, picks the first one that is not undefined.
- * @param a - First value.
- * @param b - Second value.
- * @returns a if it's a defined value; else b.</returns>
- */
-function defined(a, b) {
- return (a !== undefined) ? a : b;
-}
-
-/** Delays the invocation of the specified function until execution unwinds.
- * @param {Function} callback - Callback function.
- */
-function delay(callback) {
-
- if (arguments.length === 1) {
- window.setTimeout(callback, 0);
- return;
- }
-
- var args = Array.prototype.slice.call(arguments, 1);
- window.setTimeout(function () {
- callback.apply(this, args);
- }, 0);
-}
-
-/** Throws an exception in case that a condition evaluates to false.
- * @param {Boolean} condition - Condition to evaluate.
- * @param {String} message - Message explaining the assertion.
- * @param {Object} data - Additional data to be included in the exception.
- */
-// DATAJS INTERNAL START
-function djsassert(condition, message, data) {
-
-
- if (!condition) {
- throw { message: "Assert fired: " + message, data: data };
- }
-}
-// DATAJS INTERNAL END
-
-/** Extends the target with the specified values.
- * @param {Object} target - Object to add properties to.
- * @param {Object} values - Object with properties to add into target.
- * @returns {Object} The target object.
-*/
-function extend(target, values) {
- for (var name in values) {
- target[name] = values[name];
- }
-
- return target;
-}
-
-function find(arr, callback) {
- /** Returns the first item in the array that makes the callback function true.
- * @param {Array} [arr] Array to check in. ( may be null)
- * @param {Function} callback - Callback function to invoke once per item in the array.
- * @returns The first item that makes the callback return true; null otherwise or if the array is null.
- */
-
- if (arr) {
- var i, len;
- for (i = 0, len = arr.length; i < len; i++) {
- if (callback(arr[i])) {
- return arr[i];
- }
- }
- }
- return null;
-}
-
-function isArray(value) {
- /** Checks whether the specified value is an array object.
- * @param value - Value to check.
- * @returns {Boolean} true if the value is an array object; false otherwise.
- */
-
- return Object.prototype.toString.call(value) === "[object Array]";
-}
-
-/** Checks whether the specified value is a Date object.
- * @param value - Value to check.
- * @returns {Boolean} true if the value is a Date object; false otherwise.
- */
-function isDate(value) {
- return Object.prototype.toString.call(value) === "[object Date]";
-}
-
-/** Tests whether a value is an object.
- * @param value - Value to test.
- * @returns {Boolean} True is the value is an object; false otherwise.
- * Per javascript rules, null and array values are objects and will cause this function to return true.
- */
-function isObject(value) {
- return typeof value === "object";
-}
-
-/** Parses a value in base 10.
- * @param {String} value - String value to parse.
- * @returns {Number} The parsed value, NaN if not a valid value.
-*/
-function parseInt10(value) {
- return parseInt(value, 10);
-}
-
-/** Renames a property in an object.
- * @param {Object} obj - Object in which the property will be renamed.
- * @param {String} oldName - Name of the property that will be renamed.
- * @param {String} newName - New name of the property.
- * This function will not do anything if the object doesn't own a property with the specified old name.
- */
-function renameProperty(obj, oldName, newName) {
- if (obj.hasOwnProperty(oldName)) {
- obj[newName] = obj[oldName];
- delete obj[oldName];
- }
-}
-
-/** Default error handler.
- * @param {Object} error - Error to handle.
- */
-function throwErrorCallback(error) {
- throw error;
-}
-
-/** Removes leading and trailing whitespaces from a string.
- * @param {String str String to trim
- * @returns {String} The string with no leading or trailing whitespace.
- */
-function trimString(str) {
- if (str.trim) {
- return str.trim();
- }
-
- return str.replace(/^\s+|\s+$/g, '');
-}
-
-/** Returns a default value in place of undefined.
- * @param [value] Value to check (may be null)
- * @param defaultValue - Value to return if value is undefined.
- * @returns value if it's defined; defaultValue otherwise.
- * This should only be used for cases where falsy values are valid;
- * otherwise the pattern should be 'x = (value) ? value : defaultValue;'.
- */
-function undefinedDefault(value, defaultValue) {
- return (value !== undefined) ? value : defaultValue;
-}
-
-// Regular expression that splits a uri into its components:
-// 0 - is the matched string.
-// 1 - is the scheme.
-// 2 - is the authority.
-// 3 - is the path.
-// 4 - is the query.
-// 5 - is the fragment.
-var uriRegEx = /^([^:\/?#]+:)?(\/\/[^\/?#]*)?([^?#:]+)?(\?[^#]*)?(#.*)?/;
-var uriPartNames = ["scheme", "authority", "path", "query", "fragment"];
-
-/** Gets information about the components of the specified URI.
- * @param {String} uri - URI to get information from.
- * @return {Object} An object with an isAbsolute flag and part names (scheme, authority, etc.) if available.
- */
-function getURIInfo(uri) {
- var result = { isAbsolute: false };
-
- if (uri) {
- var matches = uriRegEx.exec(uri);
- if (matches) {
- var i, len;
- for (i = 0, len = uriPartNames.length; i < len; i++) {
- if (matches[i + 1]) {
- result[uriPartNames[i]] = matches[i + 1];
- }
- }
- }
- if (result.scheme) {
- result.isAbsolute = true;
- }
- }
-
- return result;
-}
-
-/** Builds a URI string from its components.
- * @param {Object} uriInfo - An object with uri parts (scheme, authority, etc.).
- * @returns {String} URI string.
- */
-function getURIFromInfo(uriInfo) {
- return "".concat(
- uriInfo.scheme || "",
- uriInfo.authority || "",
- uriInfo.path || "",
- uriInfo.query || "",
- uriInfo.fragment || "");
-}
-
-// Regular expression that splits a uri authority into its subcomponents:
-// 0 - is the matched string.
-// 1 - is the userinfo subcomponent.
-// 2 - is the host subcomponent.
-// 3 - is the port component.
-var uriAuthorityRegEx = /^\/{0,2}(?:([^@]*)@)?([^:]+)(?::{1}(\d+))?/;
-
-// Regular expression that matches percentage enconded octects (i.e %20 or %3A);
-var pctEncodingRegEx = /%[0-9A-F]{2}/ig;
-
-/** Normalizes the casing of a URI.
- * @param {String} uri - URI to normalize, absolute or relative.
- * @returns {String} The URI normalized to lower case.
-*/
-function normalizeURICase(uri) {
- var uriInfo = getURIInfo(uri);
- var scheme = uriInfo.scheme;
- var authority = uriInfo.authority;
-
- if (scheme) {
- uriInfo.scheme = scheme.toLowerCase();
- if (authority) {
- var matches = uriAuthorityRegEx.exec(authority);
- if (matches) {
- uriInfo.authority = "//" +
- (matches[1] ? matches[1] + "@" : "") +
- (matches[2].toLowerCase()) +
- (matches[3] ? ":" + matches[3] : "");
- }
- }
- }
-
- uri = getURIFromInfo(uriInfo);
-
- return uri.replace(pctEncodingRegEx, function (str) {
- return str.toLowerCase();
- });
-}
-
-/** Normalizes a possibly relative URI with a base URI.
- * @param {String} uri - URI to normalize, absolute or relative
- * @param {String} base - Base URI to compose with (may be null)
- * @returns {String} The composed URI if relative; the original one if absolute.
- */
-function normalizeURI(uri, base) {
- if (!base) {
- return uri;
- }
-
- var uriInfo = getURIInfo(uri);
- if (uriInfo.isAbsolute) {
- return uri;
- }
-
- var baseInfo = getURIInfo(base);
- var normInfo = {};
- var path;
-
- if (uriInfo.authority) {
- normInfo.authority = uriInfo.authority;
- path = uriInfo.path;
- normInfo.query = uriInfo.query;
- } else {
- if (!uriInfo.path) {
- path = baseInfo.path;
- normInfo.query = uriInfo.query || baseInfo.query;
- } else {
- if (uriInfo.path.charAt(0) === '/') {
- path = uriInfo.path;
- } else {
- path = mergeUriPathWithBase(uriInfo.path, baseInfo.path);
- }
- normInfo.query = uriInfo.query;
- }
- normInfo.authority = baseInfo.authority;
- }
-
- normInfo.path = removeDotsFromPath(path);
-
- normInfo.scheme = baseInfo.scheme;
- normInfo.fragment = uriInfo.fragment;
-
- return getURIFromInfo(normInfo);
-}
-
-/** Merges the path of a relative URI and a base URI.
- * @param {String} uriPath - Relative URI path.</param>
- * @param {String} basePath - Base URI path.
- * @returns {String} A string with the merged path.
- */
-function mergeUriPathWithBase(uriPath, basePath) {
- var path = "/";
- var end;
-
- if (basePath) {
- end = basePath.lastIndexOf("/");
- path = basePath.substring(0, end);
-
- if (path.charAt(path.length - 1) !== "/") {
- path = path + "/";
- }
- }
-
- return path + uriPath;
-}
-
-/** Removes the special folders . and .. from a URI's path.
- * @param {string} path - URI path component.
- * @returns {String} Path without any . and .. folders.
- */
-function removeDotsFromPath(path) {
- var result = "";
- var segment = "";
- var end;
-
- while (path) {
- if (path.indexOf("..") === 0 || path.indexOf(".") === 0) {
- path = path.replace(/^\.\.?\/?/g, "");
- } else if (path.indexOf("/..") === 0) {
- path = path.replace(/^\/\..\/?/g, "/");
- end = result.lastIndexOf("/");
- if (end === -1) {
- result = "";
- } else {
- result = result.substring(0, end);
- }
- } else if (path.indexOf("/.") === 0) {
- path = path.replace(/^\/\.\/?/g, "/");
- } else {
- segment = path;
- end = path.indexOf("/", 1);
- if (end !== -1) {
- segment = path.substring(0, end);
- }
- result = result + segment;
- path = path.replace(segment, "");
- }
- }
- return result;
-}
-
-function convertByteArrayToHexString(str) {
- var arr = [];
- if (window.atob === undefined) {
- arr = decodeBase64(str);
- } else {
- var binaryStr = window.atob(str);
- for (var i = 0; i < binaryStr.length; i++) {
- arr.push(binaryStr.charCodeAt(i));
- }
- }
- var hexValue = "";
- var hexValues = "0123456789ABCDEF";
- for (var j = 0; j < arr.length; j++) {
- var t = arr[j];
- hexValue += hexValues[t >> 4];
- hexValue += hexValues[t & 0x0F];
- }
- return hexValue;
-}
-
-function decodeBase64(str) {
- var binaryString = "";
- for (var i = 0; i < str.length; i++) {
- var base65IndexValue = getBase64IndexValue(str[i]);
- var binaryValue = "";
- if (base65IndexValue !== null) {
- binaryValue = base65IndexValue.toString(2);
- binaryString += addBase64Padding(binaryValue);
- }
- }
- var byteArray = [];
- var numberOfBytes = parseInt(binaryString.length / 8, 10);
- for (i = 0; i < numberOfBytes; i++) {
- var intValue = parseInt(binaryString.substring(i * 8, (i + 1) * 8), 2);
- byteArray.push(intValue);
- }
- return byteArray;
-}
-
-function getBase64IndexValue(character) {
- var asciiCode = character.charCodeAt(0);
- var asciiOfA = 65;
- var differenceBetweenZanda = 6;
- if (asciiCode >= 65 && asciiCode <= 90) { // between "A" and "Z" inclusive
- return asciiCode - asciiOfA;
- } else if (asciiCode >= 97 && asciiCode <= 122) { // between 'a' and 'z' inclusive
- return asciiCode - asciiOfA - differenceBetweenZanda;
- } else if (asciiCode >= 48 && asciiCode <= 57) { // between '0' and '9' inclusive
- return asciiCode + 4;
- } else if (character == "+") {
- return 62;
- } else if (character == "/") {
- return 63;
- } else {
- return null;
- }
-}
-
-function addBase64Padding(binaryString) {
- while (binaryString.length < 6) {
- binaryString = "0" + binaryString;
- }
- return binaryString;
-
-}
-
-function getJsonValueArraryLength(data) {
- if (data && data.value) {
- return data.value.length;
- }
-
- return 0;
-}
-
-function sliceJsonValueArray(data, start, end) {
- if (data === undefined || data.value === undefined) {
- return data;
- }
-
- if (start < 0) {
- start = 0;
- }
-
- var length = getJsonValueArraryLength(data);
- if (length < end) {
- end = length;
- }
-
- var newdata = {};
- for (var property in data) {
- if (property == "value") {
- newdata[property] = data[property].slice(start, end);
- } else {
- newdata[property] = data[property];
- }
- }
-
- return newdata;
-}
-
-function concatJsonValueArray(data, concatData) {
- if (concatData === undefined || concatData.value === undefined) {
- return data;
- }
-
- if (data === undefined || Object.keys(data).length === 0) {
- return concatData;
- }
-
- if (data.value === undefined) {
- data.value = concatData.value;
- return data;
- }
-
- data.value = data.value.concat(concatData.value);
-
- return data;
-}
-
-function endsWith(input, search) {
- return input.indexOf(search, input.length - search.length) !== -1;
-}
-
-function startsWith (input, search) {
- return input.indexOf(search) === 0;
-}
-
-function getFormatKind(format, defaultFormatKind) {
- var formatKind = defaultFormatKind;
- if (!assigned(format)) {
- return formatKind;
- }
-
- var normalizedFormat = format.toLowerCase();
- switch (normalizedFormat) {
- case "none":
- formatKind = 0;
- break;
- case "minimal":
- formatKind = 1;
- break;
- case "full":
- formatKind = 2;
- break;
- default:
- break;
- }
-
- return formatKind;
-}
-
-
-
-
-exports.inBrowser = inBrowser;
-exports.activeXObject = activeXObject;
-exports.assigned = assigned;
-exports.contains = contains;
-exports.defined = defined;
-exports.delay = delay;
-exports.djsassert = djsassert;
-exports.extend = extend;
-exports.find = find;
-exports.getURIInfo = getURIInfo;
-exports.isArray = isArray;
-exports.isDate = isDate;
-exports.isObject = isObject;
-exports.normalizeURI = normalizeURI;
-exports.normalizeURICase = normalizeURICase;
-exports.parseInt10 = parseInt10;
-exports.renameProperty = renameProperty;
-exports.throwErrorCallback = throwErrorCallback;
-exports.trimString = trimString;
-exports.undefinedDefault = undefinedDefault;
-exports.decodeBase64 = decodeBase64;
-exports.convertByteArrayToHexString = convertByteArrayToHexString;
-exports.getJsonValueArraryLength = getJsonValueArraryLength;
-exports.sliceJsonValueArray = sliceJsonValueArray;
-exports.concatJsonValueArray = concatJsonValueArray;
-exports.startsWith = startsWith;
-exports.endsWith = endsWith;
-exports.getFormatKind = getFormatKind;
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/d5ec5557/datajs/src/lib/datajs/xml.js
----------------------------------------------------------------------
diff --git a/datajs/src/lib/datajs/xml.js b/datajs/src/lib/datajs/xml.js
deleted file mode 100644
index b8af4fe..0000000
--- a/datajs/src/lib/datajs/xml.js
+++ /dev/null
@@ -1,816 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-/** @module datajs/xml */
-
-var utils = require('./utils.js');
-
-var activeXObject = utils.activeXObject;
-var djsassert = utils.djsassert;
-var extend = utils.extend;
-var isArray = utils.isArray;
-var normalizeURI = utils.normalizeURI;
-
-// URI prefixes to generate smaller code.
-var http = "http://";
-var w3org = http + "www.w3.org/"; // http://www.w3.org/
-
-var xhtmlNS = w3org + "1999/xhtml"; // http://www.w3.org/1999/xhtml
-var xmlnsNS = w3org + "2000/xmlns/"; // http://www.w3.org/2000/xmlns/
-var xmlNS = w3org + "XML/1998/namespace"; // http://www.w3.org/XML/1998/namespace
-
-var mozillaParserErroNS = http + "www.mozilla.org/newlayout/xml/parsererror.xml";
-
-/** Checks whether the specified string has leading or trailing spaces.
- * @param {String} text - String to check.
- * @returns {Boolean} true if text has any leading or trailing whitespace; false otherwise.
- */
-function hasLeadingOrTrailingWhitespace(text) {
- var re = /(^\s)|(\s$)/;
- return re.test(text);
-}
-
-/** Determines whether the specified text is empty or whitespace.
- * @param {String} text - Value to inspect.
- * @returns {Boolean} true if the text value is empty or all whitespace; false otherwise.
- */
-function isWhitespace(text) {
-
-
- var ws = /^\s*$/;
- return text === null || ws.test(text);
-}
-
-/** Determines whether the specified element has xml:space='preserve' applied.
- * @param domElement - Element to inspect.
- * @returns {Boolean} Whether xml:space='preserve' is in effect.
- */
-function isWhitespacePreserveContext(domElement) {
-
-
- while (domElement !== null && domElement.nodeType === 1) {
- var val = xmlAttributeValue(domElement, "space", xmlNS);
- if (val === "preserve") {
- return true;
- } else if (val === "default") {
- break;
- } else {
- domElement = domElement.parentNode;
- }
- }
-
- return false;
-}
-
-/** Determines whether the attribute is a XML namespace declaration.
- * @param domAttribute - Element to inspect.
- * @return {Boolean} True if the attribute is a namespace declaration (its name is 'xmlns' or starts with 'xmlns:'; false otherwise.
- */
-function isXmlNSDeclaration(domAttribute) {
- var nodeName = domAttribute.nodeName;
- return nodeName == "xmlns" || nodeName.indexOf("xmlns:") === 0;
-}
-
-/** Safely set as property in an object by invoking obj.setProperty.
- * @param obj - Object that exposes a setProperty method.
- * @param {String} name - Property name
- * @param value - Property value.
- */
-function safeSetProperty(obj, name, value) {
-
-
- try {
- obj.setProperty(name, value);
- } catch (_) { }
-}
-
-/** Creates an configures new MSXML 3.0 ActiveX object.
- * @returns {Object} New MSXML 3.0 ActiveX object.
- * This function throws any exception that occurs during the creation
- * of the MSXML 3.0 ActiveX object.
- */
-function msXmlDom3() {
- var msxml3 = activeXObject("Msxml2.DOMDocument.3.0");
- if (msxml3) {
- safeSetProperty(msxml3, "ProhibitDTD", true);
- safeSetProperty(msxml3, "MaxElementDepth", 256);
- safeSetProperty(msxml3, "AllowDocumentFunction", false);
- safeSetProperty(msxml3, "AllowXsltScript", false);
- }
- return msxml3;
-}
-
-/** Creates an configures new MSXML 6.0 or MSXML 3.0 ActiveX object.
- * @returns {Object} New MSXML 3.0 ActiveX object.
- * This function will try to create a new MSXML 6.0 ActiveX object. If it fails then
- * it will fallback to create a new MSXML 3.0 ActiveX object. Any exception that
- * happens during the creation of the MSXML 6.0 will be handled by the function while
- * the ones that happend during the creation of the MSXML 3.0 will be thrown.
- */
-function msXmlDom() {
- try {
- var msxml = activeXObject("Msxml2.DOMDocument.6.0");
- if (msxml) {
- msxml.async = true;
- }
- return msxml;
- } catch (_) {
- return msXmlDom3();
- }
-}
-
-/** Parses an XML string using the MSXML DOM.
- * @returns {Object} New MSXML DOMDocument node representing the parsed XML string.
- * This function throws any exception that occurs during the creation
- * of the MSXML ActiveX object. It also will throw an exception
- * in case of a parsing error.
- */
-function msXmlParse(text) {
- var dom = msXmlDom();
- if (!dom) {
- return null;
- }
-
- dom.loadXML(text);
- var parseError = dom.parseError;
- if (parseError.errorCode !== 0) {
- xmlThrowParserError(parseError.reason, parseError.srcText, text);
- }
- return dom;
-}
-
-/** Throws a new exception containing XML parsing error information.
- * @param exceptionOrReason - String indicating the reason of the parsing failure or Object detailing the parsing error.
- * @param {String} srcText - String indicating the part of the XML string that caused the parsing error.
- * @param {String} errorXmlText - XML string for wich the parsing failed.
- */
-function xmlThrowParserError(exceptionOrReason, srcText, errorXmlText) {
-
- if (typeof exceptionOrReason === "string") {
- exceptionOrReason = { message: exceptionOrReason };
- }
- throw extend(exceptionOrReason, { srcText: srcText || "", errorXmlText: errorXmlText || "" });
-}
-
-/** Returns an XML DOM document from the specified text.
- * @param {String} text - Document text.
- * @returns XML DOM document.
- * This function will throw an exception in case of a parse error
- */
-function xmlParse(text) {
- var domParser = window.DOMParser && new window.DOMParser();
- var dom;
-
- if (!domParser) {
- dom = msXmlParse(text);
- if (!dom) {
- xmlThrowParserError("XML DOM parser not supported");
- }
- return dom;
- }
-
- try {
- dom = domParser.parseFromString(text, "text/xml");
- } catch (e) {
- xmlThrowParserError(e, "", text);
- }
-
- var element = dom.documentElement;
- var nsURI = element.namespaceURI;
- var localName = xmlLocalName(element);
-
- // Firefox reports errors by returing the DOM for an xml document describing the problem.
- if (localName === "parsererror" && nsURI === mozillaParserErroNS) {
- var srcTextElement = xmlFirstChildElement(element, mozillaParserErroNS, "sourcetext");
- var srcText = srcTextElement ? xmlNodeValue(srcTextElement) : "";
- xmlThrowParserError(xmlInnerText(element) || "", srcText, text);
- }
-
- // Chrome (and maybe other webkit based browsers) report errors by injecting a header with an error message.
- // The error may be localized, so instead we simply check for a header as the
- // top element or descendant child of the document.
- if (localName === "h3" && nsURI === xhtmlNS || xmlFirstDescendantElement(element, xhtmlNS, "h3")) {
- var reason = "";
- var siblings = [];
- var cursor = element.firstChild;
- while (cursor) {
- if (cursor.nodeType === 1) {
- reason += xmlInnerText(cursor) || "";
- }
- siblings.push(cursor.nextSibling);
- cursor = cursor.firstChild || siblings.shift();
- }
- reason += xmlInnerText(element) || "";
- xmlThrowParserError(reason, "", text);
- }
-
- return dom;
-}
-
-/** Builds a XML qualified name string in the form of "prefix:name".
- * @param {String} prefix - Prefix string (may be null)
- * @param {String} name - Name string to qualify with the prefix.
- * @returns {String} Qualified name.
- */
-function xmlQualifiedName(prefix, name) {
- return prefix ? prefix + ":" + name : name;
-}
-
-/** Appends a text node into the specified DOM element node.
- * @param domNode - DOM node for the element.
- * @param {String} text - Text to append as a child of element.
-*/
-function xmlAppendText(domNode, textNode) {
- if (hasLeadingOrTrailingWhitespace(textNode.data)) {
- var attr = xmlAttributeNode(domNode, xmlNS, "space");
- if (!attr) {
- attr = xmlNewAttribute(domNode.ownerDocument, xmlNS, xmlQualifiedName("xml", "space"));
- xmlAppendChild(domNode, attr);
- }
- attr.value = "preserve";
- }
- domNode.appendChild(textNode);
- return domNode;
-}
-
-/** Iterates through the XML element's attributes and invokes the callback function for each one.
- * @param element - Wrapped element to iterate over.
- * @param {Function} onAttributeCallback - Callback function to invoke with wrapped attribute nodes.
-*/
-function xmlAttributes(element, onAttributeCallback) {
- var attributes = element.attributes;
- var i, len;
- for (i = 0, len = attributes.length; i < len; i++) {
- onAttributeCallback(attributes.item(i));
- }
-}
-
-/** Returns the value of a DOM element's attribute.
- * @param domNode - DOM node for the owning element.
- * @param {String} localName - Local name of the attribute.
- * @param {String} nsURI - Namespace URI of the attribute.
- * @returns {String} - The attribute value, null if not found (may be null)
- */
-function xmlAttributeValue(domNode, localName, nsURI) {
-
- var attribute = xmlAttributeNode(domNode, localName, nsURI);
- return attribute ? xmlNodeValue(attribute) : null;
-}
-
-/** Gets an attribute node from a DOM element.
- * @param domNode - DOM node for the owning element.
- * @param {String} localName - Local name of the attribute.
- * @param {String} nsURI - Namespace URI of the attribute.
- * @returns The attribute node, null if not found.
- */
-function xmlAttributeNode(domNode, localName, nsURI) {
-
- var attributes = domNode.attributes;
- if (attributes.getNamedItemNS) {
- return attributes.getNamedItemNS(nsURI || null, localName);
- }
-
- return attributes.getQualifiedItem(localName, nsURI) || null;
-}
-
-/** Gets the value of the xml:base attribute on the specified element.
- * @param domNode - Element to get xml:base attribute value from.
- * @param [baseURI] - Base URI used to normalize the value of the xml:base attribute ( may be null)
- * @returns {String} Value of the xml:base attribute if found; the baseURI or null otherwise.
- */
-function xmlBaseURI(domNode, baseURI) {
-
- var base = xmlAttributeNode(domNode, "base", xmlNS);
- return (base ? normalizeURI(base.value, baseURI) : baseURI) || null;
-}
-
-
-/** Iterates through the XML element's child DOM elements and invokes the callback function for each one.
- * @param element - DOM Node containing the DOM elements to iterate over.
- * @param {Function} onElementCallback - Callback function to invoke for each child DOM element.
-*/
-function xmlChildElements(domNode, onElementCallback) {
-
- xmlTraverse(domNode, /*recursive*/false, function (child) {
- if (child.nodeType === 1) {
- onElementCallback(child);
- }
- // continue traversing.
- return true;
- });
-}
-
-/** Gets the descendant element under root that corresponds to the specified path and namespace URI.
- * @param root - DOM element node from which to get the descendant element.
- * @param {String} namespaceURI - The namespace URI of the element to match.
- * @param {String} path - Path to the desired descendant element.
- * @return The element specified by path and namespace URI.
- * All the elements in the path are matched against namespaceURI.
- * The function will stop searching on the first element that doesn't match the namespace and the path.
- */
-function xmlFindElementByPath(root, namespaceURI, path) {
- var parts = path.split("/");
- var i, len;
- for (i = 0, len = parts.length; i < len; i++) {
- root = root && xmlFirstChildElement(root, namespaceURI, parts[i]);
- }
- return root || null;
-}
-
-/** Gets the DOM element or DOM attribute node under root that corresponds to the specified path and namespace URI.
- * @param root - DOM element node from which to get the descendant node.
- * @param {String} namespaceURI - The namespace URI of the node to match.
- * @param {String} path - Path to the desired descendant node.
- * @return The node specified by path and namespace URI.</returns>
-
-* This function will traverse the path and match each node associated to a path segement against the namespace URI.
-* The traversal stops when the whole path has been exahusted or a node that doesn't belogong the specified namespace is encountered.
-* The last segment of the path may be decorated with a starting @ character to indicate that the desired node is a DOM attribute.
-*/
-function xmlFindNodeByPath(root, namespaceURI, path) {
-
-
- var lastSegmentStart = path.lastIndexOf("/");
- var nodePath = path.substring(lastSegmentStart + 1);
- var parentPath = path.substring(0, lastSegmentStart);
-
- var node = parentPath ? xmlFindElementByPath(root, namespaceURI, parentPath) : root;
- if (node) {
- if (nodePath.charAt(0) === "@") {
- return xmlAttributeNode(node, nodePath.substring(1), namespaceURI);
- }
- return xmlFirstChildElement(node, namespaceURI, nodePath);
- }
- return null;
-}
-
-/** Returns the first child DOM element under the specified DOM node that matches the specified namespace URI and local name.
- * @param domNode - DOM node from which the child DOM element is going to be retrieved.
- * @param {String} [namespaceURI] -
- * @param {String} [localName] -
- * @return The node's first child DOM element that matches the specified namespace URI and local name; null otherwise.</returns>
- */
-function xmlFirstChildElement(domNode, namespaceURI, localName) {
-
- return xmlFirstElementMaybeRecursive(domNode, namespaceURI, localName, /*recursive*/false);
-}
-
-/** Returns the first descendant DOM element under the specified DOM node that matches the specified namespace URI and local name.
- * @param domNode - DOM node from which the descendant DOM element is going to be retrieved.
- * @param {String} [namespaceURI] -
- * @param {String} [localName] -
- * @return The node's first descendant DOM element that matches the specified namespace URI and local name; null otherwise.
-*/
-function xmlFirstDescendantElement(domNode, namespaceURI, localName) {
- if (domNode.getElementsByTagNameNS) {
- var result = domNode.getElementsByTagNameNS(namespaceURI, localName);
- return result.length > 0 ? result[0] : null;
- }
- return xmlFirstElementMaybeRecursive(domNode, namespaceURI, localName, /*recursive*/true);
-}
-
-/** Returns the first descendant DOM element under the specified DOM node that matches the specified namespace URI and local name.
- * @param domNode - DOM node from which the descendant DOM element is going to be retrieved.
- * @param {String} [namespaceURI] -
- * @param {String} [localName] -
- * @param {Boolean} recursive
- * - True if the search should include all the descendants of the DOM node.
- * - False if the search should be scoped only to the direct children of the DOM node.
- * @return The node's first descendant DOM element that matches the specified namespace URI and local name; null otherwise.
- */
-function xmlFirstElementMaybeRecursive(domNode, namespaceURI, localName, recursive) {
-
- var firstElement = null;
- xmlTraverse(domNode, recursive, function (child) {
- if (child.nodeType === 1) {
- var isExpectedNamespace = !namespaceURI || xmlNamespaceURI(child) === namespaceURI;
- var isExpectedNodeName = !localName || xmlLocalName(child) === localName;
-
- if (isExpectedNamespace && isExpectedNodeName) {
- firstElement = child;
- }
- }
- return firstElement === null;
- });
- return firstElement;
-}
-
-/** Gets the concatenated value of all immediate child text and CDATA nodes for the specified element.
- * @param domElement - Element to get values for.
- * @returns {String} Text for all direct children.
- */
-function xmlInnerText(xmlElement) {
-
- var result = null;
- var root = (xmlElement.nodeType === 9 && xmlElement.documentElement) ? xmlElement.documentElement : xmlElement;
- var whitespaceAlreadyRemoved = root.ownerDocument.preserveWhiteSpace === false;
- var whitespacePreserveContext;
-
- xmlTraverse(root, false, function (child) {
- if (child.nodeType === 3 || child.nodeType === 4) {
- // isElementContentWhitespace indicates that this is 'ignorable whitespace',
- // but it's not defined by all browsers, and does not honor xml:space='preserve'
- // in some implementations.
- //
- // If we can't tell either way, we walk up the tree to figure out whether
- // xml:space is set to preserve; otherwise we discard pure-whitespace.
- //
- // For example <a> <b>1</b></a>. The space between <a> and <b> is usually 'ignorable'.
- var text = xmlNodeValue(child);
- var shouldInclude = whitespaceAlreadyRemoved || !isWhitespace(text);
- if (!shouldInclude) {
- // Walk up the tree to figure out whether we are in xml:space='preserve' context
- // for the cursor (needs to happen only once).
- if (whitespacePreserveContext === undefined) {
- whitespacePreserveContext = isWhitespacePreserveContext(root);
- }
-
- shouldInclude = whitespacePreserveContext;
- }
-
- if (shouldInclude) {
- if (!result) {
- result = text;
- } else {
- result += text;
- }
- }
- }
- // Continue traversing?
- return true;
- });
- return result;
-}
-
-/** Returns the localName of a XML node.
- * @param domNode - DOM node to get the value from.
- * @returns {String} localName of domNode.
- */
-function xmlLocalName(domNode) {
-
- return domNode.localName || domNode.baseName;
-}
-
-/** Returns the namespace URI of a XML node.
- * @param node - DOM node to get the value from.
- * @returns {String} Namespace URI of domNode.
- */
-function xmlNamespaceURI(domNode) {
-
- return domNode.namespaceURI || null;
-}
-
-/** Returns the value or the inner text of a XML node.
- * @param node - DOM node to get the value from.
- * @return Value of the domNode or the inner text if domNode represents a DOM element node.
- */
-function xmlNodeValue(domNode) {
-
- if (domNode.nodeType === 1) {
- return xmlInnerText(domNode);
- }
- return domNode.nodeValue;
-}
-
-/** Walks through the descendants of the domNode and invokes a callback for each node.
- * @param domNode - DOM node whose descendants are going to be traversed.
- * @param {Boolean} recursive
- * - True if the traversal should include all the descenants of the DOM node.
- * - False if the traversal should be scoped only to the direct children of the DOM node.
- * @returns {String} Namespace URI of node.
- */
-function xmlTraverse(domNode, recursive, onChildCallback) {
-
- var subtrees = [];
- var child = domNode.firstChild;
- var proceed = true;
- while (child && proceed) {
- proceed = onChildCallback(child);
- if (proceed) {
- if (recursive && child.firstChild) {
- subtrees.push(child.firstChild);
- }
- child = child.nextSibling || subtrees.shift();
- }
- }
-}
-
-/** Returns the next sibling DOM element of the specified DOM node.
- * @param domNode - DOM node from which the next sibling is going to be retrieved.
- * @param {String} [namespaceURI] -
- * @param {String} [localName] -
- * @return The node's next sibling DOM element, null if there is none.</returns>
- */
-function xmlSiblingElement(domNode, namespaceURI, localName) {
-
- var sibling = domNode.nextSibling;
- while (sibling) {
- if (sibling.nodeType === 1) {
- var isExpectedNamespace = !namespaceURI || xmlNamespaceURI(sibling) === namespaceURI;
- var isExpectedNodeName = !localName || xmlLocalName(sibling) === localName;
-
- if (isExpectedNamespace && isExpectedNodeName) {
- return sibling;
- }
- }
- sibling = sibling.nextSibling;
- }
- return null;
-}
-
-/** Creates a new empty DOM document node.
- * @return New DOM document node.</returns>
- *
- * This function will first try to create a native DOM document using
- * the browsers createDocument function. If the browser doesn't
- * support this but supports ActiveXObject, then an attempt to create
- * an MSXML 6.0 DOM will be made. If this attempt fails too, then an attempt
- * for creating an MXSML 3.0 DOM will be made. If this last attemp fails or
- * the browser doesn't support ActiveXObject then an exception will be thrown.
- */
-function xmlDom() {
- var implementation = window.document.implementation;
- return (implementation && implementation.createDocument) ?
- implementation.createDocument(null, null, null) :
- msXmlDom();
-}
-
-/** Appends a collection of child nodes or string values to a parent DOM node.
- * @param parent - DOM node to which the children will be appended.
- * @param {Array} children - Array containing DOM nodes or string values that will be appended to the parent.
- * @return The parent with the appended children or string values.</returns>
- * 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 to the parent.
- */
-function xmlAppendChildren(parent, children) {
- if (!isArray(children)) {
- return xmlAppendChild(parent, children);
- }
-
- var i, len;
- for (i = 0, len = children.length; i < len; i++) {
- children[i] && xmlAppendChild(parent, children[i]);
- }
- return parent;
-}
-
-/** Appends a child node or a string value to a parent DOM node.
- * @param parent - DOM node to which the child will be appended.
- * @param child - Child DOM node or string value to append to the parent.
- * @return The parent with the appended child or string value.</returns>
- * If child is a string value, then a new DOM text node is going to be created
- * for it and then appended to the parent.
- */
-function xmlAppendChild(parent, child) {
-
- djsassert(parent !== child, "xmlAppendChild() - parent and child are one and the same!");
- if (child) {
- if (typeof child === "string") {
- return xmlAppendText(parent, xmlNewText(parent.ownerDocument, child));
- }
- if (child.nodeType === 2) {
- parent.setAttributeNodeNS ? parent.setAttributeNodeNS(child) : parent.setAttributeNode(child);
- } else {
- parent.appendChild(child);
- }
- }
- return parent;
-}
-
-/** Creates a new DOM attribute node.
- * @param dom - DOM document used to create the attribute.
- * @param {String} prefix - Namespace prefix.
- * @param {String} namespaceURI - Namespace URI.
- * @return DOM attribute node for the namespace declaration.
- */
-function xmlNewAttribute(dom, namespaceURI, qualifiedName, value) {
-
- var attribute =
- dom.createAttributeNS && dom.createAttributeNS(namespaceURI, qualifiedName) ||
- dom.createNode(2, qualifiedName, namespaceURI || undefined);
-
- attribute.value = value || "";
- return attribute;
-}
-
-/** Creates a new DOM element node.
- * @param dom - DOM document used to create the DOM element.
- * @param {String} namespaceURI - Namespace URI of the new DOM element.
- * @param {String} qualifiedName - Qualified name in the form of "prefix:name" of the new DOM element.
- * @param {Array} [children] Collection of child DOM nodes or string values that are going to be appended to the new DOM element.
- * @return New DOM element.</returns>
- * 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 to the new DOM element.
- */
-function xmlNewElement(dom, nampespaceURI, qualifiedName, children) {
- var element =
- dom.createElementNS && dom.createElementNS(nampespaceURI, qualifiedName) ||
- dom.createNode(1, qualifiedName, nampespaceURI || undefined);
-
- return xmlAppendChildren(element, children || []);
-}
-
-/** Creates a namespace declaration attribute.
- * @param dom - DOM document used to create the attribute.
- * @param {String} namespaceURI - Namespace URI.
- * @param {String} prefix - Namespace prefix.
- * @return DOM attribute node for the namespace declaration.</returns>
- */
-function xmlNewNSDeclaration(dom, namespaceURI, prefix) {
- return xmlNewAttribute(dom, xmlnsNS, xmlQualifiedName("xmlns", prefix), namespaceURI);
-}
-
-/** Creates a new DOM document fragment node for the specified xml text.
- * @param dom - DOM document from which the fragment node is going to be created.
- * @param {String} text XML text to be represented by the XmlFragment.
- * @return New DOM document fragment object.
- */
-function xmlNewFragment(dom, text) {
-
- var value = "<c>" + text + "</c>";
- var tempDom = xmlParse(value);
- var tempRoot = tempDom.documentElement;
- var imported = ("importNode" in dom) ? dom.importNode(tempRoot, true) : tempRoot;
- var fragment = dom.createDocumentFragment();
-
- var importedChild = imported.firstChild;
- while (importedChild) {
- fragment.appendChild(importedChild);
- importedChild = importedChild.nextSibling;
- }
- return fragment;
-}
-
-/** Creates new DOM text node.
- * @param dom - DOM document used to create the text node.
- * @param {String} text - Text value for the DOM text node.
- * @return DOM text node.</returns>
- */
-function xmlNewText(dom, text) {
- return dom.createTextNode(text);
-}
-
-/** Creates a new DOM element or DOM attribute node as specified by path and appends it to the DOM tree pointed by root.
- * @param dom - DOM document used to create the new node.
- * @param root - DOM element node used as root of the subtree on which the new nodes are going to be created.
- * @param {String} namespaceURI - Namespace URI of the new DOM element or attribute.
- * @param {String} namespacePrefix - Prefix used to qualify the name of the new DOM element or attribute.
- * @param {String} Path - Path string describing the location of the new DOM element or attribute from the root element.
- * @return DOM element or attribute node for the last segment of the path.</returns>
-
- * This function will traverse the path and will create a new DOM element with the specified namespace URI and prefix
- * for each segment that doesn't have a matching element under root.
- * The last segment of the path may be decorated with a starting @ character. In this case a new DOM attribute node
- * will be created.
- */
-function xmlNewNodeByPath(dom, root, namespaceURI, prefix, path) {
- var name = "";
- var parts = path.split("/");
- var xmlFindNode = xmlFirstChildElement;
- var xmlNewNode = xmlNewElement;
- var xmlNode = root;
-
- var i, len;
- for (i = 0, len = parts.length; i < len; i++) {
- name = parts[i];
- if (name.charAt(0) === "@") {
- name = name.substring(1);
- xmlFindNode = xmlAttributeNode;
- xmlNewNode = xmlNewAttribute;
- }
-
- var childNode = xmlFindNode(xmlNode, namespaceURI, name);
- if (!childNode) {
- childNode = xmlNewNode(dom, namespaceURI, xmlQualifiedName(prefix, name));
- xmlAppendChild(xmlNode, childNode);
- }
- xmlNode = childNode;
- }
- return xmlNode;
-}
-
-/** Returns the text representation of the document to which the specified node belongs.
- * @param root - Wrapped element in the document to serialize.
- * @returns {String} Serialized document.
-*/
-function xmlSerialize(domNode) {
- var xmlSerializer = window.XMLSerializer;
- if (xmlSerializer) {
- var serializer = new xmlSerializer();
- return serializer.serializeToString(domNode);
- }
-
- if (domNode.xml) {
- return domNode.xml;
- }
-
- throw { message: "XML serialization unsupported" };
-}
-
-/** Returns the XML representation of the all the descendants of the node.
- * @param domNode - Node to serialize.</param>
- * @returns {String} The XML representation of all the descendants of the node.
- */
-function xmlSerializeDescendants(domNode) {
- var children = domNode.childNodes;
- var i, len = children.length;
- if (len === 0) {
- return "";
- }
-
- // Some implementations of the XMLSerializer don't deal very well with fragments that
- // don't have a DOMElement as their first child. The work around is to wrap all the
- // nodes in a dummy root node named "c", serialize it and then just extract the text between
- // the <c> and the </c> substrings.
-
- var dom = domNode.ownerDocument;
- var fragment = dom.createDocumentFragment();
- var fragmentRoot = dom.createElement("c");
-
- fragment.appendChild(fragmentRoot);
- // Move the children to the fragment tree.
- for (i = 0; i < len; i++) {
- fragmentRoot.appendChild(children[i]);
- }
-
- var xml = xmlSerialize(fragment);
- xml = xml.substr(3, xml.length - 7);
-
- // Move the children back to the original dom tree.
- for (i = 0; i < len; i++) {
- domNode.appendChild(fragmentRoot.childNodes[i]);
- }
-
- return xml;
-}
-
-/** Returns the XML representation of the node and all its descendants.
- * @param domNode - Node to serialize
- * @returns {String} The XML representation of the node and all its descendants.
- */
-function xmlSerializeNode(domNode) {
-
- var xml = domNode.xml;
- if (xml !== undefined) {
- return xml;
- }
-
- if (window.XMLSerializer) {
- var serializer = new window.XMLSerializer();
- return serializer.serializeToString(domNode);
- }
-
- throw { message: "XML serialization unsupported" };
-}
-
-exports.http = http;
-exports.w3org = w3org;
-exports.xmlNS = xmlNS;
-exports.xmlnsNS = xmlnsNS;
-
-exports.hasLeadingOrTrailingWhitespace = hasLeadingOrTrailingWhitespace;
-exports.isXmlNSDeclaration = isXmlNSDeclaration;
-exports.xmlAppendChild = xmlAppendChild;
-exports.xmlAppendChildren = xmlAppendChildren;
-exports.xmlAttributeNode = xmlAttributeNode;
-exports.xmlAttributes = xmlAttributes;
-exports.xmlAttributeValue = xmlAttributeValue;
-exports.xmlBaseURI = xmlBaseURI;
-exports.xmlChildElements = xmlChildElements;
-exports.xmlFindElementByPath = xmlFindElementByPath;
-exports.xmlFindNodeByPath = xmlFindNodeByPath;
-exports.xmlFirstChildElement = xmlFirstChildElement;
-exports.xmlFirstDescendantElement = xmlFirstDescendantElement;
-exports.xmlInnerText = xmlInnerText;
-exports.xmlLocalName = xmlLocalName;
-exports.xmlNamespaceURI = xmlNamespaceURI;
-exports.xmlNodeValue = xmlNodeValue;
-exports.xmlDom = xmlDom;
-exports.xmlNewAttribute = xmlNewAttribute;
-exports.xmlNewElement = xmlNewElement;
-exports.xmlNewFragment = xmlNewFragment;
-exports.xmlNewNodeByPath = xmlNewNodeByPath;
-exports.xmlNewNSDeclaration = xmlNewNSDeclaration;
-exports.xmlNewText = xmlNewText;
-exports.xmlParse = xmlParse;
-exports.xmlQualifiedName = xmlQualifiedName;
-exports.xmlSerialize = xmlSerialize;
-exports.xmlSerializeDescendants = xmlSerializeDescendants;
-exports.xmlSiblingElement = xmlSiblingElement;
http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/d5ec5557/datajs/src/lib/odata.js
----------------------------------------------------------------------
diff --git a/datajs/src/lib/odata.js b/datajs/src/lib/odata.js
deleted file mode 100644
index 0249aa3..0000000
--- a/datajs/src/lib/odata.js
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
- /** @module odata */
-
-// Imports
-var odataUtils = exports.utils = require('./odata/utils.js');
-var odataHandler = exports.handler = require('./odata/handler.js');
-var odataMetadata = exports.metadata = require('./odata/metadata.js');
-var odataNet = exports.net = require('./odata/net.js');
-var odataJson = exports.json = require('./odata/json.js');
- exports.batch = require('./odata/batch.js');
-
-
-
-var utils = require('./datajs/utils.js');
-var assigned = utils.assigned;
-
-var defined = utils.defined;
-var throwErrorCallback = utils.throwErrorCallback;
-
-var invokeRequest = odataUtils.invokeRequest;
-var MAX_DATA_SERVICE_VERSION = odataHandler.MAX_DATA_SERVICE_VERSION;
-var prepareRequest = odataUtils.prepareRequest;
-var metadataParser = odataMetadata.metadataParser;
-
-// CONTENT START
-
-var handlers = [odataJson.jsonHandler, odataHandler.textHandler];
-
-/** Dispatches an operation to handlers.
- * @param {String} handlerMethod - Name of handler method to invoke.
- * @param {Object} requestOrResponse - request/response argument for delegated call.
- * @param {Object} context - context argument for delegated call.
- */
-function dispatchHandler(handlerMethod, requestOrResponse, context) {
-
- 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" };
- }
-}
-
-/** Default success handler for OData.
- * @param data - Data to process.
- */
-exports.defaultSuccess = function (data) {
-
- window.alert(window.JSON.stringify(data));
-};
-
-exports.defaultError = throwErrorCallback;
-
-exports.defaultHandler = {
-
- /** Reads the body of the specified response by delegating to JSON handlers.
- * @param response - Response object.
- * @param context - Operation context.
- */
- read: function (response, context) {
-
- if (response && assigned(response.body) && response.headers["Content-Type"]) {
- dispatchHandler("read", response, context);
- }
- },
-
- /** Write the body of the specified request by delegating to JSON handlers.
- * @param request - Reques tobject.
- * @param context - Operation context.
- */
- write: function (request, context) {
-
- dispatchHandler("write", request, context);
- },
-
- maxDataServiceVersion: MAX_DATA_SERVICE_VERSION,
- accept: "application/json;q=0.9, */*;q=0.1"
- };
-
-exports.defaultMetadata = []; //TODO check why is the defaultMetadata an Array? and not an Object.
-
-/** Reads data from the specified URL.
- * @param urlOrRequest - URL to read data from.
- * @param {Function} [success] -
- * @param {Function} [error] -
- * @param {Object} [handler] -
- * @param {Object} [httpClient] -
- * @param {Object} [metadata] -
- */
-exports.read = function (urlOrRequest, success, error, handler, httpClient, metadata) {
-
- var request;
- if (urlOrRequest instanceof String || typeof urlOrRequest === "string") {
- request = { requestUri: urlOrRequest };
- } else {
- request = urlOrRequest;
- }
-
- return exports.request(request, success, error, handler, httpClient, metadata);
-};
-
-/** Sends a request containing OData payload to a server.
- * @param {Object} request - Object that represents the request to be sent.
- * @param {Function} [success] -
- * @param {Function} [error] -
- * @param {Object} [handler] -
- * @param {Object} [httpClient] -
- * @param {Object} [metadata] -
- */
-exports.request = function (request, success, error, handler, httpClient, metadata) {
-
- success = success || exports.defaultSuccess;
- error = error || exports.defaultError;
- handler = handler || exports.defaultHandler;
- httpClient = httpClient || odataNet.defaultHttpClient;
- metadata = metadata || exports.defaultMetadata;
-
- // Augment the request with additional defaults.
- request.recognizeDates = utils.defined(request.recognizeDates, odataJson.jsonHandler.recognizeDates);
- request.callbackParameterName = utils.defined(request.callbackParameterName, odataNet.defaultHttpClient.callbackParameterName);
- request.formatQueryString = utils.defined(request.formatQueryString, odataNet.defaultHttpClient.formatQueryString);
- request.enableJsonpCallback = utils.defined(request.enableJsonpCallback, odataNet.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 {
- odataUtils.prepareRequest(request, handler, context);
- return odataUtils.invokeRequest(request, success, error, handler, httpClient, context);
- } catch (err) {
- // errors in success handler for sync requests are catched here and result in error handler calls.
- // So here we fix this and throw that error further.
- if (err.bIsSuccessHandlerError) {
- throw err;
- } else {
- error(err);
- }
- }
-
-};
-
-/** Parses the csdl metadata to DataJS metatdata format. This method can be used when the metadata is retrieved using something other than DataJS
- * @param {string} csdlMetadata - A string that represents the entire csdl metadata.
- * @returns {Object} An object that has the representation of the metadata in Datajs format.
- */
-exports.parseMetadata = function (csdlMetadataDocument) {
-
- return metadataParser(null, csdlMetadataDocument);
-};
-
-// Configure the batch handler to use the default handler for the batch parts.
-exports.batch.batchHandler.partHandler = exports.defaultHandler;
-exports.metadataHandler = odataMetadata.metadataHandler;
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/d5ec5557/datajs/src/lib/odata/batch.js
----------------------------------------------------------------------
diff --git a/datajs/src/lib/odata/batch.js b/datajs/src/lib/odata/batch.js
deleted file mode 100644
index 5b006ff..0000000
--- a/datajs/src/lib/odata/batch.js
+++ /dev/null
@@ -1,377 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-/** @module odata/batch */
-
-var utils = require('./../datajs.js').utils;
-var odataUtils = require('./utils.js');
-var odataHandler = require('./handler.js');
-
-var extend = utils.extend;
-var isArray = utils.isArray;
-var trimString = utils.trimString;
-
-var contentType = odataHandler.contentType;
-var handler = odataHandler.handler;
-var isBatch = odataUtils.isBatch;
-var MAX_DATA_SERVICE_VERSION = odataHandler.MAX_DATA_SERVICE_VERSION;
-var normalizeHeaders = odataUtils.normalizeHeaders;
-//TODO var payloadTypeOf = odata.payloadTypeOf;
-var prepareRequest = odataUtils.prepareRequest;
-
-
-
-
-
-// Imports
-
-
-
-// CONTENT START
-var batchMediaType = "multipart/mixed";
-var responseStatusRegex = /^HTTP\/1\.\d (\d{3}) (.*)$/i;
-var responseHeaderRegex = /^([^()<>@,;:\\"\/[\]?={} \t]+)\s?:\s?(.*)/;
-
-/* Calculates a random 16 bit number and returns it in hexadecimal format.
- * @returns {String} A 16-bit number in hex format.
- */
-function hex16() {
-
- return Math.floor((1 + Math.random()) * 0x10000).toString(16).substr(1);
-}
-
-/* Creates a string that can be used as a multipart request boundary.
- * @param {String} [prefix] -
- * @returns {String} Boundary string of the format: <prefix><hex16>-<hex16>-<hex16>
- */
-function createBoundary(prefix) {
-
- return prefix + hex16() + "-" + hex16() + "-" + hex16();
-}
-
-/* Gets the handler for data serialization of individual requests / responses in a batch.
- * @param context - Context used for data serialization.
- * @returns Handler object
- */
-function partHandler(context) {
-
- return context.handler.partHandler;
-}
-
-/* Gets the current boundary used for parsing the body of a multipart response.
- * @param context - Context used for parsing a multipart response.
- * @returns {String} Boundary string.
- */
-function currentBoundary(context) {
- var boundaries = context.boundaries;
- return boundaries[boundaries.length - 1];
-}
-
-/** Parses a batch response.
- * @param handler - This handler.
- * @param {String} text - Batch text.
- * @param {Object} context - Object with parsing context.
- * @return An object representation of the batch.
- */
-function batchParser(handler, text, context) {
-
- var boundary = context.contentType.properties["boundary"];
- return { __batchResponses: readBatch(text, { boundaries: [boundary], handlerContext: context }) };
-}
-
-/** Serializes a batch object representation into text.
- * @param handler - This handler.
- * @param {Object} data - Representation of a batch.
- * @param {Object} context - Object with parsing context.
- * @return An text representation of the batch object; undefined if not applicable.#
- */
-function batchSerializer(handler, data, context) {
-
- var cType = context.contentType = context.contentType || contentType(batchMediaType);
- if (cType.mediaType === batchMediaType) {
- return writeBatch(data, context);
- }
-}
-
-/* Parses a multipart/mixed response body from from the position defined by the context.
- * @param {String} text - Body of the multipart/mixed response.
- * @param context - Context used for parsing.
- * @return Array of objects representing the individual responses.
- */
-function readBatch(text, context) {
- var delimiter = "--" + currentBoundary(context);
-
- // Move beyond the delimiter and read the complete batch
- readTo(text, context, delimiter);
-
- // Ignore the incoming line
- readLine(text, context);
-
- // Read the batch parts
- var responses = [];
- var partEnd;
-
- while (partEnd !== "--" && context.position < text.length) {
- var partHeaders = readHeaders(text, context);
- var partContentType = contentType(partHeaders["Content-Type"]);
-
- var changeResponses;
- if (partContentType && partContentType.mediaType === batchMediaType) {
- context.boundaries.push(partContentType.properties.boundary);
- try {
- changeResponses = readBatch(text, context);
- } catch (e) {
- e.response = readResponse(text, context, delimiter);
- changeResponses = [e];
- }
- responses.push({ __changeResponses: changeResponses });
- context.boundaries.pop();
- readTo(text, context, "--" + currentBoundary(context));
- } else {
- if (!partContentType || partContentType.mediaType !== "application/http") {
- throw { message: "invalid MIME part type " };
- }
- // Skip empty line
- readLine(text, context);
- // Read the response
- var response = readResponse(text, context, delimiter);
- try {
- if (response.statusCode >= 200 && response.statusCode <= 299) {
- partHandler(context.handlerContext).read(response, context.handlerContext);
- } else {
- // Keep track of failed responses and continue processing the batch.
- response = { message: "HTTP request failed", response: response };
- }
- } catch (e) {
- response = e;
- }
-
- responses.push(response);
- }
-
- partEnd = text.substr(context.position, 2);
-
- // Ignore the incoming line.
- readLine(text, context);
- }
- return responses;
-}
-
-/* Parses the http headers in the text from the position defined by the context.
-* @param {String} text - Text containing an http response's headers</param>
-* @param context - Context used for parsing.
-* @returns Object containing the headers as key value pairs.
-* This function doesn't support split headers and it will stop reading when it hits two consecutive line breaks.
-*/
-function readHeaders(text, context) {
- var headers = {};
- var parts;
- var line;
- var pos;
-
- do {
- pos = context.position;
- line = readLine(text, context);
- parts = responseHeaderRegex.exec(line);
- if (parts !== null) {
- headers[parts[1]] = parts[2];
- } else {
- // Whatever was found is not a header, so reset the context position.
- context.position = pos;
- }
- } while (line && parts);
-
- normalizeHeaders(headers);
-
- return headers;
-}
-
-/* Parses an HTTP response.
- * @param {String} text -Text representing the http response.
- * @param context optional - Context used for parsing.
- * @param {String} delimiter -String used as delimiter of the multipart response parts.
- * @return Object representing the http response.
- */
-function readResponse(text, context, delimiter) {
- // Read the status line.
- var pos = context.position;
- var match = responseStatusRegex.exec(readLine(text, context));
-
- var statusCode;
- var statusText;
- var headers;
-
- if (match) {
- statusCode = match[1];
- statusText = match[2];
- headers = readHeaders(text, context);
- readLine(text, context);
- } else {
- context.position = pos;
- }
-
- return {
- statusCode: statusCode,
- statusText: statusText,
- headers: headers,
- body: readTo(text, context, "\r\n" + delimiter)
- };
-}
-
-/** Returns a substring from the position defined by the context up to the next line break (CRLF).
- * @param {String} text - Input string.
- * @param context - Context used for reading the input string.
- * @returns {String} Substring to the first ocurrence of a line break or null if none can be found.
- */
-function readLine(text, context) {
-
- return readTo(text, context, "\r\n");
-}
-
-/** Returns a substring from the position given by the context up to value defined by the str parameter and increments the position in the context.
- * @param {String} text - Input string.</param>
- * @param context - Context used for reading the input string.</param>
- * @param {String} [str] - Substring to read up to.
- * @returns {String} Substring to the first ocurrence of str or the end of the input string if str is not specified. Null if the marker is not found.
- */
-function readTo(text, context, str) {
- var start = context.position || 0;
- var end = text.length;
- if (str) {
- end = text.indexOf(str, start);
- if (end === -1) {
- return null;
- }
- context.position = end + str.length;
- } else {
- context.position = end;
- }
-
- return text.substring(start, end);
-}
-
-/** Serializes a batch request object to a string.
- * @param data - Batch request object in payload representation format
- * @param context - Context used for the serialization
- * @returns {String} String representing the batch request
- */
-function writeBatch(data, context) {
- if (!isBatch(data)) {
- throw { message: "Data is not a batch object." };
- }
-
- var batchBoundary = createBoundary("batch_");
- var batchParts = data.__batchRequests;
- var batch = "";
- var i, len;
- for (i = 0, len = batchParts.length; i < len; i++) {
- batch += writeBatchPartDelimiter(batchBoundary, false) +
- writeBatchPart(batchParts[i], context);
- }
- batch += writeBatchPartDelimiter(batchBoundary, true);
-
- // Register the boundary with the request content type.
- var contentTypeProperties = context.contentType.properties;
- contentTypeProperties.boundary = batchBoundary;
-
- return batch;
-}
-
-/** Creates the delimiter that indicates that start or end of an individual request.
- * @param {String} boundary Boundary string used to indicate the start of the request</param>
- * @param {Boolean} close - Flag indicating that a close delimiter string should be generated
- * @returns {String} Delimiter string
- */
-function writeBatchPartDelimiter(boundary, close) {
- var result = "\r\n--" + boundary;
- if (close) {
- result += "--";
- }
-
- return result + "\r\n";
-}
-
-/** Serializes a part of a batch request to a string. A part can be either a GET request or
- * a change set grouping several CUD (create, update, delete) requests.
- * @param part - Request or change set object in payload representation format</param>
- * @param context - Object containing context information used for the serialization</param>
- * @param {boolean} [nested] -
- * @returns {String} String representing the serialized part
- * A change set is an array of request objects and they cannot be nested inside other change sets.
- */
-function writeBatchPart(part, context, nested) {
-
-
- var changeSet = part.__changeRequests;
- var result;
- if (isArray(changeSet)) {
- if (nested) {
- throw { message: "Not Supported: change set nested in other change set" };
- }
-
- var changeSetBoundary = createBoundary("changeset_");
- result = "Content-Type: " + batchMediaType + "; boundary=" + changeSetBoundary + "\r\n";
- var i, len;
- for (i = 0, len = changeSet.length; i < len; i++) {
- result += writeBatchPartDelimiter(changeSetBoundary, false) +
- writeBatchPart(changeSet[i], context, true);
- }
-
- result += writeBatchPartDelimiter(changeSetBoundary, true);
- } else {
- result = "Content-Type: application/http\r\nContent-Transfer-Encoding: binary\r\n\r\n";
- var partContext = extend({}, context);
- partContext.handler = handler;
- partContext.request = part;
- partContext.contentType = null;
-
- prepareRequest(part, partHandler(context), partContext);
- result += writeRequest(part);
- }
-
- return result;
-}
-
-/* Serializes a request object to a string.
- * @param request - Request object to serialize</param>
- * @returns {String} String representing the serialized request
- */
-function writeRequest(request) {
- var result = (request.method ? request.method : "GET") + " " + request.requestUri + " HTTP/1.1\r\n";
- for (var name in request.headers) {
- if (request.headers[name]) {
- result = result + name + ": " + request.headers[name] + "\r\n";
- }
- }
-
- result += "\r\n";
-
- if (request.body) {
- result += request.body;
- }
-
- return result;
-}
-
-
-
-/** batchHandler (see {@link module:odata/batch~batchParser}) */
-exports.batchHandler = handler(batchParser, batchSerializer, batchMediaType, MAX_DATA_SERVICE_VERSION);
-exports.batchSerializer = batchSerializer;
-exports.writeRequest = writeRequest;
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/olingo-odata4-js/blob/d5ec5557/datajs/src/lib/odata/handler.js
----------------------------------------------------------------------
diff --git a/datajs/src/lib/odata/handler.js b/datajs/src/lib/odata/handler.js
deleted file mode 100644
index 3e85a1e..0000000
--- a/datajs/src/lib/odata/handler.js
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-/** @module odata/handler */
-
-
-var utils = require('./../datajs.js').utils;
-var oDataUtils = require('./utils.js');
-
-// Imports.
-var assigned = utils.assigned;
-var extend = utils.extend;
-var trimString = utils.trimString;
-var maxVersion = oDataUtils.maxVersion;
-var MAX_DATA_SERVICE_VERSION = "4.0";
-
-/** Parses a string into an object with media type and properties.
- * @param {String} str - String with media type to parse.
- * @return null if the string is empty; an object with 'mediaType' and a 'properties' dictionary otherwise.
- */
-function contentType(str) {
-
- if (!str) {
- return null;
- }
-
- var contentTypeParts = str.split(";");
- var properties = {};
-
- var i, len;
- for (i = 1, len = contentTypeParts.length; i < len; i++) {
- var contentTypeParams = contentTypeParts[i].split("=");
- properties[trimString(contentTypeParams[0])] = contentTypeParams[1];
- }
-
- return { mediaType: trimString(contentTypeParts[0]), properties: properties };
-}
-
-/** Serializes an object with media type and properties dictionary into a string.
- * @param contentType - Object with media type and properties dictionary to serialize.
- * @return String representation of the media type object; undefined if contentType is null or undefined.</returns>
- */
-function contentTypeToString(contentType) {
- if (!contentType) {
- return undefined;
- }
-
- var result = contentType.mediaType;
- var property;
- for (property in contentType.properties) {
- result += ";" + property + "=" + contentType.properties[property];
- }
- return result;
-}
-
-/** Creates an object that is going to be used as the context for the handler's parser and serializer.
- * @param contentType - Object with media type and properties dictionary.
- * @param {String} dataServiceVersion - String indicating the version of the protocol to use.
- * @param context - Operation context.
- * @param handler - Handler object that is processing a resquest or response.
- * @return Context object.</returns>
- */
-function createReadWriteContext(contentType, dataServiceVersion, context, handler) {
-
- var rwContext = {};
- extend(rwContext, context);
- extend(rwContext, {
- contentType: contentType,
- dataServiceVersion: dataServiceVersion,
- handler: handler
- });
-
- return rwContext;
-}
-
-/** Sets a request header's value. If the header has already a value other than undefined, null or empty string, then this method does nothing.
- * @param request - Request object on which the header will be set.
- * @param {String} name - Header name.
- * @param {String} value - Header value.
- */
-function fixRequestHeader(request, name, value) {
- if (!request) {
- return;
- }
-
- var headers = request.headers;
- if (!headers[name]) {
- headers[name] = value;
- }
-}
-
-/** Sets the DataServiceVersion header of the request if its value is not yet defined or of a lower version.
- * @param request - Request object on which the header will be set.
- * @param {String} version - Version value.
- * If the request has already a version value higher than the one supplied the this function does nothing.
- */
-function fixDataServiceVersionHeader(request, version) {
-
- if (request) {
- var headers = request.headers;
- var dsv = headers["OData-Version"];
- headers["OData-Version"] = dsv ? maxVersion(dsv, version) : version;
- }
-}
-
-/** Gets the value of a request or response header.
- * @param requestOrResponse - Object representing a request or a response.
- * @param {String} name - Name of the header to retrieve.
- * @returns {String} String value of the header; undefined if the header cannot be found.
- */
-function getRequestOrResponseHeader(requestOrResponse, name) {
-
- var headers = requestOrResponse.headers;
- return (headers && headers[name]) || undefined;
-}
-
-/** Gets the value of the Content-Type header from a request or response.
- * @param requestOrResponse - Object representing a request or a response.
- * @returns {Object} Object with 'mediaType' and a 'properties' dictionary; null in case that the header is not found or doesn't have a value.
- */
-function getContentType(requestOrResponse) {
-
- return contentType(getRequestOrResponseHeader(requestOrResponse, "Content-Type"));
-}
-
-var versionRE = /^\s?(\d+\.\d+);?.*$/;
-/** Gets the value of the DataServiceVersion header from a request or response.
- * @param requestOrResponse - Object representing a request or a response.
- * @returns {String} Data service version; undefined if the header cannot be found.
- */
-function getDataServiceVersion(requestOrResponse) {
-
- var value = getRequestOrResponseHeader(requestOrResponse, "OData-Version");
- if (value) {
- var matches = versionRE.exec(value);
- if (matches && matches.length) {
- return matches[1];
- }
- }
-
- // Fall through and return undefined.
-}
-
-/** Checks that a handler can process a particular mime type.
- * @param handler - Handler object that is processing a resquest or response.
- * @param cType - Object with 'mediaType' and a 'properties' dictionary.
- * @returns {Boolean} True if the handler can process the mime type; false otherwise.
- *
- * The following check isn't as strict because if cType.mediaType = application/; it will match an accept value of "application/xml";
- * however in practice we don't not expect to see such "suffixed" mimeTypes for the handlers.
- */
-function handlerAccepts(handler, cType) {
- return handler.accept.indexOf(cType.mediaType) >= 0;
-}
-
-/** Invokes the parser associated with a handler for reading the payload of a HTTP response.
- * @param handler - Handler object that is processing the response.
- * @param {Function} parseCallback - Parser function that will process the response payload.
- * @param response - HTTP response whose payload is going to be processed.
- * @param context - Object used as the context for processing the response.
- * @returns {Boolean} True if the handler processed the response payload and the response.data property was set; false otherwise.
- */
-function handlerRead(handler, parseCallback, response, context) {
-
- if (!response || !response.headers) {
- return false;
- }
-
- var cType = getContentType(response);
- var version = getDataServiceVersion(response) || "";
- var body = response.body;
-
- if (!assigned(body)) {
- return false;
- }
-
- if (handlerAccepts(handler, cType)) {
- var readContext = createReadWriteContext(cType, version, context, handler);
- readContext.response = response;
- response.data = parseCallback(handler, body, readContext);
- return response.data !== undefined;
- }
-
- return false;
-}
-
-/** Invokes the serializer associated with a handler for generating the payload of a HTTP request.
- * @param handler - Handler object that is processing the request.
- * @param {Function} serializeCallback - Serializer function that will generate the request payload.
- * @param response - HTTP request whose payload is going to be generated.
- * @param context - Object used as the context for serializing the request.
- * @returns {Boolean} True if the handler serialized the request payload and the request.body property was set; false otherwise.
- */
-function handlerWrite(handler, serializeCallback, request, context) {
- if (!request || !request.headers) {
- return false;
- }
-
- var cType = getContentType(request);
- var version = getDataServiceVersion(request);
-
- if (!cType || handlerAccepts(handler, cType)) {
- var writeContext = createReadWriteContext(cType, version, context, handler);
- writeContext.request = request;
-
- request.body = serializeCallback(handler, request.data, writeContext);
-
- if (request.body !== undefined) {
- fixDataServiceVersionHeader(request, writeContext.dataServiceVersion || "4.0");
-
- fixRequestHeader(request, "Content-Type", contentTypeToString(writeContext.contentType));
- fixRequestHeader(request, "OData-MaxVersion", handler.maxDataServiceVersion);
- return true;
- }
- }
-
- return false;
-}
-
-/** Creates a handler object for processing HTTP requests and responses.
- * @param {Function} parseCallback - Parser function that will process the response payload.
- * @param {Function} serializeCallback - Serializer function that will generate the request payload.
- * @param {String} accept - String containing a comma separated list of the mime types that this handler can work with.
- * @param {String} maxDataServiceVersion - String indicating the highest version of the protocol that this handler can work with.
- * @returns {Object} Handler object.
- */
-function handler(parseCallback, serializeCallback, accept, maxDataServiceVersion) {
-
- return {
- accept: accept,
- maxDataServiceVersion: maxDataServiceVersion,
-
- read: function (response, context) {
- return handlerRead(this, parseCallback, response, context);
- },
-
- write: function (request, context) {
- return handlerWrite(this, serializeCallback, request, context);
- }
- };
-}
-
-function textParse(handler, body /*, context */) {
- return body;
-}
-
-function textSerialize(handler, data /*, context */) {
- if (assigned(data)) {
- return data.toString();
- } else {
- return undefined;
- }
-}
-
-
-
-
-exports.textHandler = handler(textParse, textSerialize, "text/plain", MAX_DATA_SERVICE_VERSION);
-
-exports.contentType = contentType;
-exports.contentTypeToString = contentTypeToString;
-exports.handler = handler;
-exports.createReadWriteContext = createReadWriteContext;
-exports.fixRequestHeader = fixRequestHeader;
-exports.getRequestOrResponseHeader = getRequestOrResponseHeader;
-exports.getContentType = getContentType;
-exports.getDataServiceVersion = getDataServiceVersion;
-exports.MAX_DATA_SERVICE_VERSION = MAX_DATA_SERVICE_VERSION;
\ No newline at end of file