/**
*
* Copyright (C) 2021 Akorbi Digital RMP
*
* This file is part of RunMyProcess SDK-JS.
*
* RunMyProcess SDK-JS is free software: you can redistribute it and/or modify
* it under the terms of 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.
*/
/**
Resource success callback
@callback Resource~onSuccess
@param {object} [rData] - the raw sata of the request
*/
/**
Resource failure callback
@callback Resource~onFailure
@param {object} response - an object with the standard browser's error properties
*/
/**
Generic class that is inherited in other classes to load, save and manage data.
@constructor
@property {String} url - The url used for requests and posts
@property {object} object - Holds the information as is returned by the server
@property {String} id - The id asociated with the an instance of Resource
@property {String} xml - A string representation of the xml to be posted to the server
@property {Array} categories - an array representing the category tag of a returned request
@property {Array} entries - an array representing the entries tag of a returned request
@property {Array} links - an array representing the links tag of a returned request
@property {String} rights - the rights asociated with an instance of resource
@property {String} selfUrl - The url asociated with an instance of Resource
@property {String} contentType - the expected return content of a request ("json" or "xml")
@property {String} pagination - a string that holds the pagination structure to me added to the
url
@property {Boolean} hasNext - boolean
@property {Boolean} hasPrevious - a string that holds the pagination structure to me added to the
@property {Array} filters - a list of filters
@property {Array} defaultFilters - a list of filters that are set as default
@property {String} version - the version for server resources
@property {Array} orderBy - a list of orderBy objects FE: [{orderBy:orderBy1,order:order1},{orderBy:orderBy2,order:order2}]
@property {String} mode - The request mode
@property {Array} parameters - additional parameters that may be added to the request
*/
function Resource(){
this.url;
this.object = {};
this.id;
this.xml;
this.categories = [];
this.entries = [];
this.links = [];
this.rights;
this.selfUrl;
this.contentType;
this.pagination = {};
this.hasNext = false;
this.hasPrevious = false;
this.filters = [];
this.defaultFilters = [];
this.version;
this.orderBy=[];
this.mode;
this.parameters = [];
};
/**
Loads Resource data for a given url
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
@param {String} options.url - url for loading
*/
Resource.prototype.urlLoader = function (options){
var father = this;
father.loadPreset = function () {
father.generateUrl = function () {
return father.selfUrl;
};
};
try{
father.selfUrl=options.url;
father.load(options);
}catch(e){
options.eObject=e;
father.errorManager(options);
}
};
/**
Gets json values without a standard xml Resource structure
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.ajaxLoad = function (options) {
try{
var father = this;
father.loadPreset();
var urlBase = options.baseUrl || RMPApplication.getBaseUrl();
var url = urlBase + father.generateUrl() + father.getUrlAggregates();
$.ajax({
url: url,
dataType: "json",
setRequestHeader: {Accept: 'application/json',
P_SDK_Version: context.version},
success: function(rdata){
options.onSuccess(rdata);
},
error: function(e){
if (!options.onFailure) {
var eOptions = {};
eOptions.object=e;
father.errorManager(eOptions);
} else {
options.onFailure(e);
};
}
}).done(function() {
});
}catch (e) {
options.eObject=e;
father.errorManager(options);
};
};
/**
Loads a resource without setting any variables
values
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.straightLoad = function (options) {
father = this;
try {
father.loadPreset();
if(!jQuery.isEmptyObject(options.pagination))father.pagination = options.pagination;
if(options.filters)father.filters = options.filters;
var loadOptions = {};
loadOptions.onSuccess = function (rObject) {
father.object = rObject;
options.onSuccess(rObject);
};
loadOptions.onFailure = function(e){
options.eObject=e;
father.errorManager(options);
};
loadOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
loadOptions.headers = options.headers;
father.dataLoad(loadOptions);
}catch (e) {
options.eObject=e;
father.errorManager(options);
};
};
/**
Loads a resource setting JSON variables from v2
values
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.JSONLoad = function (options) {
father = this;
try {
father.loadPreset();
var loadOptions = {};
loadOptions.onSuccess = function (rObject) {
for (var key in rObject) {
if (rObject.hasOwnProperty(key)) {
father[key] = rObject[key];
}
}
options.onSuccess(rObject);
};
loadOptions.onFailure = function(e){
options.eObject=e;
father.errorManager(options);
};
loadOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
loadOptions.headers = options.headers;
father.dataLoad(loadOptions);
}catch (e) {
options.eObject=e;
father.errorManager(options);
};
};
/**
Requests json values with the standard xml Resource structure and sets the generic variable
values
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
@param {Object} [options.pagination] -an Object with pagination variables (nb and first)
@example Load Resource
var r = new Resource();
r.load({
onSuccess:function(){
alert("Resource loaded!");
}
});
*/
Resource.prototype.load = function (options) {
var father = this;
father.pagination = {};//remove current pagination
father.filters = [];//remove current filters
father.orderBy = [];//remove current orderBy
father.mode = '';
father.parameters = [];
try {
if(options.removeDefaultFilters) father.defaultFilters = [];
father.loadPreset();
if(!jQuery.isEmptyObject(options.pagination))father.pagination = options.pagination;
if(options.mode)father.mode = options.mode;
if(options.parameters)father.parameters = options.parameters;
if(options.filters)father.filters = options.filters;
if(options.orderBy)father.orderBy = options.orderBy;
var loadOptions = {};
loadOptions.onSuccess = function (rObject) {
father.object = rObject;
father.id = rObject.id;
father.entries = father.getArray(rObject, "entry");
father.categories = father.getArray(rObject, "category");
father.links = father.getArray(rObject, "link");
if (father.linkSearch('next', father.links))father.hasNext=true;
else father.hasNext=false;
if (father.linkSearch('previous', father.links)) father.hasPrevious=true;
else father.hasPrevious=false;
father.selfUrl = father.reconstructUrl(father.linkSearch('self', father.links));
//father.pagination = {};//remove current pagination
father.filters = [];//remove current filters because it comes in the url as default
father.rights = father.object.rights;
father.loadSet(rObject);
options.onSuccess();
};
loadOptions.cachedCallback = options.cachedCallback;
loadOptions.onFailure = function(e){
options.eObject=e;
father.errorManager(options);
};
loadOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
loadOptions.headers = options.headers;
father.dataLoad(loadOptions);
}catch (e) {
options.eObject=e;
father.errorManager(options);
};
};
/**
Gets json values with the standard xml Resource prom the next page in pagination
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.loadNext = function (options) {
var father = this;
father.pagination = {};//remove current pagination
father.filters = [];//remove current filters
father.orderBy = [];//remove current orderBy
father.mode = '';
father.parameters = [];
if(options.filters)father.filters = options.filters;
father.loadPreset = function () {
father.generateUrl = function () {
return father.selfUrl;
};
};
father.selfUrl = father.reconstructUrl(father.linkSearch('next', father.links))||father.selfUrl;
var opt = {};
if(!jQuery.isEmptyObject(father.pagination))opt.pagination = father.pagination;//add current loaded pagination
if(father.filters)opt.filters = father.filters;//add current filters
if(father.orderBy)opt.orderBy = father.orderBy;//add current loaded orderby
if(options.mode)father.mode = options.mode;
if(options.parameters)father.parameters = options.parameters;//add current loaded pagination
opt.removeDefaultFilters = options.removeDefaultFilters;
opt.onSuccess = function() {
options.onSuccess();
};
opt.onFailure = function (e) {
options.eObject=e;
father.errorManager(options);
};
opt.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
father.load(opt);
};
/**
Gets json values with the standard xml Resource prom the previous page in pagination
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.loadPrevious = function (options) {
var father = this;
father.pagination = {};//remove current pagination
father.filters = [];//remove current filters
father.orderBy = [];//remove current orderBy
father.mode = '';
father.parameters = [];
if(options.filters)father.filters = options.filters;
father.loadPreset = function () {
father.generateUrl = function () {
return father.selfUrl;
};
};
father.selfUrl = father.reconstructUrl(father.linkSearch('previous', father.links))||father.selfUrl;
var opt = {};
if(!jQuery.isEmptyObject(father.pagination))opt.pagination = father.pagination;//add current loaded pagination
if(father.filters)opt.filters = father.filters;//add current filters
if(father.orderBy)opt.orderBy = father.orderBy;//add current loaded orderby
if(options.mode)father.mode = options.mode;
if(father.parameters)father.parameters = options.parameters;
opt.removeDefaultFilters = options.removeDefaultFilters;
opt.onSuccess = function(){
options.onSuccess();
};
opt.onFailure = function (e) {
options.eObject=e;
father.errorManager(options);
};
opt.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
father.load(opt);
};
/**
If not overritten, it calls the resourceSave function to save/post data
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.save = function (options) {
this.resourceSave(options);
};
/**
Save/Posts data loaded in the xml variable of the Resource constructor without loading any data to the resource
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.noLoadSave = function (options) {
try {
var father=this;
father.savePreset();
var v_contentType = father.contentType|| 'xml';
var pOptions = {};
pOptions.onSuccess = function (rObject) {
father.selfUrl = rObject;
father.saveSet(options);
};
pOptions.onFailure = function (e) {
options.eObject=e;
father.errorManager(options);
};
pOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
pOptions.xml = father.xml;
pOptions.method = 'POST';
if (v_contentType === 'json'){
father.jsonDataPost(pOptions);
}else{
pOptions.accept = 'text/xml'
father.dataPost(pOptions);
}
}catch (e) {
options.eObject=e;
father.errorManager(options);
};
};
/**
Save/Posts data loaded in the xml variable of the Resource constructor
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.resourceSave = function (options) {
var father = this;
try {
father.savePreset();
var v_contentType = father.contentType|| 'xml';
var pOptions = {};
pOptions.onSuccess = function (rObject) {
if (rObject.feed){
options.onSuccess(rObject.feed);
}else if (rObject){
options.onSuccess(rObject);
}else{
options.onSuccess();
}
};
pOptions.onFailure = function (e) {
options.eObject=e;
father.errorManager(options);
};
pOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
pOptions.xml = father.xml;
pOptions.accept = options.accept;
pOptions.method = 'POST';
if(options.mode)pOptions.mode=options.mode;
if (v_contentType === 'json'){
father.jsonDataPost(pOptions);
}else{
father.dataPost(pOptions);
}
}catch (e) {
options.eObject=e;
father.errorManager(options);
};
};
/**
Calls the resourceUpdate function to post data with predefined set of values
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.update = function (options) {
this.resourceUpdate(options);
};
/**
Calls post funtions to update an existing registry data loaded in the xml variable
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.resourceUpdate = function (options) {
var father = this;
try {
father.updatePreset();
var v_contentType = father.contentType || 'xml';
var pOptions = {};
pOptions.onSuccess = function(rObject){
options.onSuccess(rObject);
};
pOptions.onFailure = function (e) {
options.eObject=e;
father.errorManager(options);
};
pOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
pOptions.xml = father.xml;
pOptions.method = 'PUT';
if (v_contentType === 'json'){
father.jsonDataPost(pOptions);
}else{
father.dataPost(pOptions);
}
}catch (e) {
options.eObject=e;
father.errorManager(options);
};
};
/**
Calls post funtions to soft delete an existing registry
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.remove = function (options) {
try {
var father = this;
father.deletePreset();
var pOptions = {};
pOptions.onSuccess = function(rObject){
options.onSuccess(rObject);
};
pOptions.onFailure = function (e) {
options.eObject=e;
father.errorManager(options);
};
pOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
pOptions.xml = father.xml;
pOptions.method = 'DELETE';
if(options.mode)pOptions.mode=options.mode;
father.dataPost(pOptions);
}catch (e) {
options.eObject=e;
father.errorManager(options);
};
};
/**Override functions*/
/**
Runs after sucessful Post
@method
@param {Object} dataObject - success callback function
*/
Resource.prototype.loadSet = function (dataObject) {
};
/**
Runs after Post request to create a registry
@method
*/
Resource.prototype.saveSet = function (options) {
};
/**
Runs before Get request
@method
*/
Resource.prototype.loadPreset = function () {
};
/**
Runs before Post request to create a registry
@method
*/
Resource.prototype.savePreset = function () {
};
/**
Runs before Delete request
@method
*/
Resource.prototype.deletePreset = function () {
};
/**
Runs before Post request to update a registry
@method
*/
Resource.prototype.updatePreset = function () {
};
/**
Runs to generate a Post xml for saving or updating a registry
@method
@returns {String} xml - string to be posted
*/
Resource.prototype.generate_xml = function () {
return undefined;
};
/**
Runs to retrieve the url before a request
@method
@returns {String} url - for request
*/
Resource.prototype.generateUrl = function () {
return this.selfUrl;
};
/**Support functions*/
/**
Generates the filter string to be posted to the server
@method
*/
Resource.prototype.generateFilterStr= function (){
var father = this;
var filterStr='';
var operatorStr='';
var valueStr='';
for(var i=0;i<father.filters.length;i++){
if (filterStr==''){//if its the first filter
filterStr=encodeURIComponent(father.filters[i].filter);
operatorStr=encodeURIComponent(father.filters[i].operator);
valueStr=encodeURIComponent(father.filters[i].value);
}else{
filterStr=filterStr+'+'+encodeURIComponent(father.filters[i].filter);
operatorStr=operatorStr+'+'+encodeURIComponent(father.filters[i].operator);
valueStr=valueStr+'+'+encodeURIComponent(father.filters[i].value);
};
};
for(var i=0;i<father.defaultFilters.length;i++){
if (filterStr==''){//if its the first filter
filterStr=encodeURIComponent(father.defaultFilters[i].filter);
operatorStr=encodeURIComponent(father.defaultFilters[i].operator);
valueStr=encodeURIComponent(father.defaultFilters[i].value);
}else{
filterStr=filterStr+'+'+encodeURIComponent(father.defaultFilters[i].filter);
operatorStr=operatorStr+'+'+encodeURIComponent(father.defaultFilters[i].operator);
valueStr=valueStr+'+'+encodeURIComponent(father.defaultFilters[i].value);
};
};
if (filterStr=='') return '';
return 'filter='+filterStr+'&operator='+operatorStr+'&value='+valueStr;
};
/**
Generates the pagination string for the request Url
@method
*/
Resource.prototype.generatePaginationStr = function () {
var father = this;
if (jQuery.isEmptyObject(father.pagination)) return '';
return 'nb='+father.pagination.nb+'&first='+father.pagination.first||'0';
};
/**
Generates the orderBy string for the request Url
@method
*/
Resource.prototype.generateOrderByStr = function () {
var father = this;
var orderByStr='';
var orderStr='';
for(var i=0;i<father.orderBy.length;i++){
if (orderByStr==''){//if its the first orderBy
orderByStr=encodeURIComponent(father.orderBy[i].orderBy);
orderStr=encodeURIComponent(father.orderBy[i].order);
}else{
orderByStr=orderByStr+'+'+encodeURIComponent(father.orderBy[i].orderBy);
orderStr=orderStr+'+'+encodeURIComponent(father.orderBy[i].order);
};
};
if (orderByStr=='') return '';
return 'orderby='+orderByStr+'&order='+orderStr;
};
/**
Generates the Mode string for the request Url
@method
*/
Resource.prototype.generateModeStr = function () {
var father = this;
if (!father.mode) return '';
return 'P_mode='+father.mode;
};
/**
Generates the parameters string for the request Url
@method
*/
Resource.prototype.generateParametersStr = function () {
var father = this;
if (!father.parameters) return '';
var str = '';
for(var i=0;i<father.parameters.length;i++){
if(str!='')str=str+'&';
str = str+father.parameters[i];
}
return str;
};
/**
adds a filter to the stack
@method
@param {object} options - an object with the following parameters
@param {String} options.filter - the name of the filter to be used
@param {String} options.operator - the filter's operator
@param {String} options.value - the value of the filter
*/
Resource.prototype.addFilter = function (options){
this.filters.push(options);
};
/**
Finds and removes a filter from the stack
@method
@param {String} key - the filter to be removed
*/
Resource.prototype.removeFilter = function (key){
for (var i = 0; i<this.filters.length; i++) {
if (this.filters[i].filter===key){
this.filters.splice(i,1);
}
}
};
/**
Clears the filter array
@method
*/
Resource.prototype.clearFilters = function (){
this.filters = [];
};
/**
returns an array from a object list
@method
@param {Object} my_father - object where the list is located
@param {String} my_son - searched list
@returns {Array} Array of registries
*/
Resource.prototype.getArray = function (my_father, my_son) {
var my_array = [];
if (typeof (my_father) === "object") {
if (my_father[my_son] !== undefined) {
if (my_father[my_son].length !== undefined) {
var my_array = my_father[my_son];
} else {
var my_array = [my_father[my_son]];
}
}
}
return my_array;
};
/**
returns an array of all "link" object list found in an array
@method
@param {Array} entries - Array containing all entries
@returns {Array} Array of links
*/
Resource.prototype.entryLinks = function (entries) {
var lnks = [];
for (var i = 0; i < entries.length; i++) {
var entry_lnks=this.getArray(entries[i], 'link');
for (var j = 0; j < entry_lnks.length; j++) {
if (entry_lnks[j]==undefined){
lnks.push(entry_lnks);
}else{
lnks.push(entry_lnks[j]);
}
}
}
return lnks;
};
/**
returns an array of all "link" object list found in an array
@method
@param {Array} lArray - array of Values
@returns {Array} flattened array
*/
Resource.prototype.flatPoolTree = function (lArray){
var I = [];//data
I=lArray;
var F = [];//output
while (I.length!==0){
var Rlength=I.length;
for (var i = 0; i < Rlength; i++) {
if(I[i]!==undefined){
if(I[i].parent===undefined){
var obj = {};
obj=I[i];
obj.parent=undefined;
obj.children=[];
F.push(obj);
I.splice(i,1);
i=i-1;
};
};
}; //End generating first level
var Ilength=I.length;
for (var i = 0; i < F.length; i++) {
var P = {};
for (var j = 0; j < Ilength; j++){
if(I[j].parent.href!==undefined){
if(F[i].selfUrl===I[j].parent.href){
F[i].children.push(I[j]);
var obj = {};
obj=I[j];
obj.parent=F[i];
obj.children=[];
F.push(obj);
I.splice(j,1);
j=j-1;
};
};
};
}; //End generating List
}
return F;
};
/**
returns the object containing the term searched
@DEPRECATED
@method
@param {String} needle - The searched term
@param {Array} haystack - The values to be searched
@returns {Object} Object found
@deprecated since version 1.6
*/
Resource.prototype.termSearch = function (needle, haystack) {
if (haystack.length === undefined){
if (haystack.term === needle)return haystack;
} else{
for (var i = 0; i < haystack.length; i++) {
if (haystack[i].term === needle) {
return haystack[i];
}
}
}
return undefined;
};
/**
returns the object containing the term searched
@method
@param {String} needle - The searched term
@param {Array} haystack - The values to be searched
@returns {Object} Object found
*/
Resource.findTerm = function (needle, haystack) {
if (haystack.length === undefined){
if (haystack.term === needle)return haystack;
} else{
for (var i = 0; i < haystack.length; i++) {
if (haystack[i].term === needle) {
return haystack[i];
}
}
}
return undefined;
};
/**
returns the object containing the title searched
@method
@param {String} needle - The searched title
@param {Array} haystack - The values to be searched
@returns {Object} Object found
*/
Resource.prototype.titleSearch = function (needle, haystack) {
if (haystack.length === undefined){
if (haystack.title === needle)return haystack;
} else{
for (var i = 0; i < haystack.length; i++) {
if (haystack[i].title === needle) {
return haystack[i];
}
}
}
return undefined;
};
/**
returns the object containing the id searched
@method
@param {String} needle - The searched term
@param {Array} haystack - The values to be searched
@returns {Object} Object found
*/
Resource.prototype.idSearch = function (needle, haystack) {
for (var i = 0; i < haystack.length; i++) {
if (haystack[i].id === needle) {
return haystack[i];
}
}
return undefined;
};
/**
returns the object containing the link searched
@deprecated
@method
@param {String} needle - The searched term
@param {Array} haystack - The values to be searched
@returns {String} string representation of the link url
*/
Resource.prototype.linkSearch = function (needle, haystack) {
var father = this;
if (haystack.length === undefined){
if(haystack.rel===needle){
return haystack.href;
}
}else{
for (var i = 0; i < haystack.length; i++) {
if (haystack[i].rel === needle) {
return haystack[i].href;
}
}
}
return undefined;
};
/**
returns the object containing the link searched
@method
@param {String} needle - The searched term
@param {Array} haystack - The values to be searched
@returns {String} string representation of the link url
*/
Resource.findLink = function (needle, haystack) {
if (haystack.length === undefined){
if(haystack.rel===needle){
return haystack.href;
}
}else{
for (var i = 0; i < haystack.length; i++) {
if (haystack[i].rel === needle) {
return haystack[i].href;
}
}
}
return undefined;
};
/**
returns the object containing the link searched with url reconstruction
@method
@param {String} needle - The searched term
@param {Array} haystack - The values to be searched
@returns {String} string representation of the link url
*/
Resource.prototype.reconstructedLinkSearch = function (needle, haystack) {
return this.reconstructUrl(this.linkSearch(needle, haystack));
};
/**
returns the object containing the term searched
@deprecated
@method
@param {String} needle - The searched term
@param {Array} haystack - The values to be searched
@returns {Object} Object found
*/
Resource.prototype.linkObjectSearch = function (needle, haystack) {
if (haystack.length === undefined){
if(haystack.rel===needle){
return haystack;
}
}else{
for (var i = 0; i < haystack.length; i++) {
if (haystack[i].rel === needle) {
return haystack[i];
}
}
}
return undefined;
};
/**
returns the object containing the term searched
@method
@param {String} needle - The searched term
@param {Array} haystack - The values to be searched
@returns {Object} Object found
*/
Resource.findLinkObject = function (needle, haystack) {
if (haystack.length === undefined){
if(haystack.rel===needle){
return haystack;
}
}else{
for (var i = 0; i < haystack.length; i++) {
if (haystack[i].rel === needle) {
return haystack[i];
}
}
}
return undefined;
};
/**
DEPRECATED returns the base 64 decoded string
@deprecated since version 1.5
@method
@param {String} s - The base 64 string
@returns {String} Decoded string
*/
Resource.prototype.decode_base64 = function(s) {
var e={},i,k,v=[],r='',w=String.fromCharCode;
var n=[[65,91],[97,123],[48,58],[43,44],[47,48]];
for(z in n){for(i=n[z][0];i<n[z][1];i++){v.push(w(i));}}
for(i=0;i<64;i++){e[v[i]]=i;}
for(i=0;i<s.length;i+=72){
var b=0,c,x,l=0,o=s.substring(i,i+72);
for(x=0;x<o.length;x++){
c=e[o.charAt(x)];b=(b<<6)+c;l+=6;
while(l>=8){r+=w((b>>>(l-=8))%256);}
}
}
return r;
};
/**
DEPRECATED returns the base 64 encoded string
@deprecated since version 1.5
@method
@param {String} input - The string to encode.
@returns {String} encoded string
*/
Resource.prototype.encode_base64 = function (input) {
if (!input) return input;//return null if null
var output = "";
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
}
return output;
}
/**
returns the base 64 decoded string
@method
@param {String} s - The base 64 string
@returns {String} Decoded string
*/
Resource.decodeBase64 = function(s) {
var aMyUTF8Output = Resource.base64DecToArr(s);
return Resource.UTF8ArrToStr(aMyUTF8Output);
};
/**
returns the base 64 encoded string
@method
@param {String} input - The string to encode.
@returns {String} encoded string
*/
Resource.encodeBase64 = function (input) {
if (!input) return input;//return null if null
var aMyUTF8Input = Resource.strToUTF8Arr(input);
var sMyBase64 = Resource.base64EncArr(aMyUTF8Input);
return sMyBase64;
}
/*\
|*| http://creativecommons.org/publicdomain/zero/1.0/
|*| Base64 / binary data / UTF-8 strings utilities
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
|*|
\*/
/* Array of bytes to base64 string decoding */
Resource.b64ToUint6 = function(nChr) {
return nChr > 64 && nChr < 91 ?
nChr - 65
: nChr > 96 && nChr < 123 ?
nChr - 71
: nChr > 47 && nChr < 58 ?
nChr + 4
: nChr === 43 ?
62
: nChr === 47 ?
63
:
0;
}
Resource.base64DecToArr = function(sBase64, nBlocksSize) {
var
sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);
for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
nMod4 = nInIdx & 3;
nUint24 |= Resource.b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
}
nUint24 = 0;
}
}
return taBytes;
}
/* Base64 string to array encoding */
Resource.uint6ToB64 = function(nUint6) {
return nUint6 < 26 ?
nUint6 + 65
: nUint6 < 52 ?
nUint6 + 71
: nUint6 < 62 ?
nUint6 - 4
: nUint6 === 62 ?
43
: nUint6 === 63 ?
47
:
65;
}
Resource.base64EncArr = function(aBytes) {
var nMod3 = 2, sB64Enc = "";
for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
nMod3 = nIdx % 3;
if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
if (nMod3 === 2 || aBytes.length - nIdx === 1) {
sB64Enc += String.fromCharCode(Resource.uint6ToB64(nUint24 >>> 18 & 63), Resource.uint6ToB64(nUint24 >>> 12 & 63), Resource.uint6ToB64(nUint24 >>> 6 & 63), Resource.uint6ToB64(nUint24 & 63));
nUint24 = 0;
}
}
return sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '==');
}
/* UTF-8 array to DOMString and vice versa */
Resource.UTF8ArrToStr = function(aBytes) {
var sView = "";
for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {
nPart = aBytes[nIdx];
sView += String.fromCharCode(
nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */
/* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */
(nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
: nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */
(nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
: nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */
(nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
: nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */
(nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
: nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */
(nPart - 192 << 6) + aBytes[++nIdx] - 128
: /* nPart < 127 ? */ /* one byte */
nPart
);
}
return sView;
}
Resource.strToUTF8Arr = function(sDOMStr) {
var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0;
/* mapping... */
for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) {
nChr = sDOMStr.charCodeAt(nMapIdx);
nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6;
}
aBytes = new Uint8Array(nArrLen);
/* transcription... */
for (var nIdx = 0, nChrIdx = 0; nIdx < nArrLen; nChrIdx++) {
nChr = sDOMStr.charCodeAt(nChrIdx);
if (nChr < 128) {
/* one byte */
aBytes[nIdx++] = nChr;
} else if (nChr < 0x800) {
/* two bytes */
aBytes[nIdx++] = 192 + (nChr >>> 6);
aBytes[nIdx++] = 128 + (nChr & 63);
} else if (nChr < 0x10000) {
/* three bytes */
aBytes[nIdx++] = 224 + (nChr >>> 12);
aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
aBytes[nIdx++] = 128 + (nChr & 63);
} else if (nChr < 0x200000) {
/* four bytes */
aBytes[nIdx++] = 240 + (nChr >>> 18);
aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
aBytes[nIdx++] = 128 + (nChr & 63);
} else if (nChr < 0x4000000) {
/* five bytes */
aBytes[nIdx++] = 248 + (nChr >>> 24);
aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
aBytes[nIdx++] = 128 + (nChr & 63);
} else /* if (nChr <= 0x7fffffff) */ {
/* six bytes */
aBytes[nIdx++] = 252 + (nChr >>> 30);
aBytes[nIdx++] = 128 + (nChr >>> 24 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
aBytes[nIdx++] = 128 + (nChr & 63);
}
}
return aBytes;
}
/**
removes the u0000 escape notation from string
@method
@param {String} input - The string to clean.
@returns {String} clean string
*/
Resource.prototype.removeUnicodeEscNotation = function (input) {
return input.replace(/[\n\r\u0000\\]/g, '')
}
/**
removes the u0000 escape notation from string
@method
@param {String} input - The string to clean.
@returns {String} clean string
*/
Resource.removeEscNotation = function (input) {
return input.replace(/[\n\r\u0000\\]/g, '')
}
/**
Sorts array and removes duplicated values
@method
@param {Array} arr - The unsorted array
@returns {Array} Sorted array with no duplicate values
*/
Resource.prototype.sort_unique = function(arr) {
arr = arr.sort();
var ret = [arr[0]];
for (var i = 1; i < arr.length; i++) {
if (arr[i-1] !== arr[i]) {
ret.push(arr[i]);
}
}
return ret;
};
/**
Correctly transforms a string to an xml document
@method
@param {String} text - The xml string to transform
@returns {XMLDOM} a xml document
*/
Resource.prototype.stringtoXML = function (text){
if (window.ActiveXObject){
var doc=new ActiveXObject('Microsoft.XMLDOM');
doc.async='false';
doc.loadXML(text);
} else {
var parser=new DOMParser();
var doc=parser.parseFromString(text,'text/xml');
}
return doc;
};
/**
encode to HTML string for special characters
@method
@param {String} text - The html string to transform
@returns {String} the transformed html
*/
Resource.prototype.encodeHTML = function (text) {
if(!text)return text;
return text.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
/**
Transforms an xml string to a JSON object
@method
@param {String} xml - The xml string to transform
@returns {Object} JSON object
*/
Resource.prototype.xmlToJson = function(xml) {
// Create the return object
var obj = {};
var father=this;
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj[attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = father.xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(father.xmlToJson(item));
}
}
}
return obj;
};
/**
Pads to 0 the int values
@method
@param {Number} n - the number to pad
@returns {Number} the padded number
*/
Resource.prototype.padzero = function(n) {
return n < 10 ? '0' + n : n;
};
/**
returns an iso string from a date object
@method
@param {date} d - The date to transform
@returns {String} iso string
*/
Resource.prototype.toISOString = function (d) {
return d.getUTCFullYear() + '-' + this.padzero(d.getUTCMonth() + 1) + '-'
+ this.padzero(d.getUTCDate()) + 'T' + this.padzero(d.getUTCHours()) + ':'
+ this.padzero(d.getUTCMinutes()) + ':' + this.padzero(d.getUTCSeconds()) + '+'
+'0000';
//+ this.pad2zeros(d.getUTCMilliseconds()) + '';
};
/**
Manages errors and failures during the run process.
@method
@param {object} options - options to be used during the call<br/>
@param {Object} options.eObject - error object
@param {String} [options.message] - error message
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
*/
Resource.prototype.errorManager = function(options) {
if (!options.onFailure) {
alert(JSON.stringify(options.eObject));
} else {
options.onFailure(options.eObject);
};
};
/**
Generates a URL without pagination or filters and generates Resource Filters and Pagination
@method
@param {String} url - the url to reconstruct
*/
Resource.prototype.reconstructUrl = function(url) {
var father = this;
if(!url) return '';
var urlSplt=url.split("?");
var cleanUrl = urlSplt[0];
if(urlSplt[1]){//get all filters and paginations
var parts = urlSplt[1].split("&");
var filtersToAdd=[];
var operatorsToAdd=[];
var valuesToAdd=[];
var orderbyToAdd=[];
var orderToAdd=[];
var modeToAdd;
for (var i = 0; i < parts.length; ++i) {
var operators = parts[i].split("=");
switch (operators[0]) {
case 'nb':
if (!father.pagination.nb)father.pagination.nb=operators[1];
parts.splice(i,1);
i--;
break;
case 'first':
if (!father.pagination.first)father.pagination.first=operators[1];
parts.splice(i,1);
i--;
break;
case 'orderby':
orderbyToAdd = operators[1].split("+") || new Array(operators[1]);
parts.splice(i,1);
i--;
break;
case 'order':
orderToAdd = operators[1].split("+")|| new Array(operators[1]);
parts.splice(i,1);
i--;
break;
case 'filter':
filtersToAdd = operators[1].split("+")|| new Array(operators[1]);
parts.splice(i,1);
i--;
break;
case 'operator':
operatorsToAdd = operators[1].split("+") || new Array(operators[1]);
parts.splice(i,1);
i--;
break;
case 'value':
valuesToAdd = operators[1].split("+") || new Array(operators[1]);
parts.splice(i,1);
i--;
break;
case 'P_MODE':
modeToAdd = operators[1];
parts.splice(i,1);
i--;
break;
}
}
father.defaultFilters=[];
for (var i = 0; i < filtersToAdd.length; ++i) {
father.defaultFilters.push({
"filter":filtersToAdd[i],
"operator":operatorsToAdd[i],
"value":valuesToAdd[i]
});
}
for (var i = 0; i < orderbyToAdd.length; ++i) {
father.orderBy.push({
"orderBy":orderbyToAdd[i],
"order":orderToAdd[i]
});
}
father.mode = modeToAdd;
//Add remaining elements to parameters
for (var i = 0; i < parts.length; ++i) {
//var operators = parts[i].split("=");
father.parameters.push(parts[i]);//[operators[0]] = operators[1];
parts.splice(i,1);
}
if(parts.length)cleanUrl=cleanUrl+"?"+parts.join("&");//if anything is left add it to the URL
}
return cleanUrl;
};
/**
Runs to retrieve the url filters and pagination
@method
@returns {String} string to agregate to url
*/
Resource.prototype.getUrlAggregates = function () {
father = this;
if(father.filters.length || !jQuery.isEmptyObject(father.pagination) || father.orderBy.length || father.mode || father.parameters.length){
var pref = '?';
if(father.generateUrl().indexOf('?')!==-1) pref = '&';//check if there is an aggregate in the url
var filterStr=father.generateFilterStr();
var separator = '';
if (filterStr)separator='&';
var paginationStr =separator+father.generatePaginationStr();
separator = '';
if (filterStr||paginationStr)separator='&';
var orderByStr =separator+father.generateOrderByStr();
separator = '';
if (filterStr||paginationStr||orderByStr)separator='&';
var modeStr = separator+father.generateModeStr();
if (filterStr||paginationStr||orderByStr||modeStr)separator='&';
var parametersStr = separator+father.generateParametersStr();
return pref+filterStr+paginationStr+orderByStr+modeStr+parametersStr;
}else return '';
};
/**
Remove date decimals
@method
@returns {String} string date without decimals
*/
Resource.removeDecimalsFromDateString = function (dateStr) {
var pos = dateStr.indexOf("+");
if (pos!=-1){
return dateStr.substring(0,pos)+"Z";
}
return dateStr;
}
/**Data access functions*/
/**
Requests json values with the standard xml Resource structure. Will run context.init() if the
context is not loaded
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.dataLoad = function (options) {
var father = this;
// Bug.-undefined load_status workaround must be fixed to accept context reloads
// a switch must be created in the initial load function so the load fuction
// waits until the load has compleated to reload
if (context.load_status === undefined && context.customer_id !== undefined) {
context.load_status = 'C';
} //END Bug workarround
var url = options.baseUrl || RMPApplication.getBaseUrl();
var dOptions = options;
switch (context.load_status) {
case 'NL':
//LOAD CONTEXT;
var initOptions = {};
initOptions.OnSuccess = function (rdata) {
var lUrl = father.generateUrl();
var urlAggregates = father.getUrlAggregates();
/*if (lUrl.substring(lUrl.length -1)=='/'&& urlAggregates){
lUrl = lUrl.substring(0, lUrl.length -1);
}*/
url = url + lUrl + urlAggregates;
dOptions.url=url;
father.dataLoader(dOptions);
};
initOptions.onFailure = function(e){
options.eObject=e;
father.errorManager(options);
};
initOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
context.init(initOptions);
break;
case 'C':
//USE CONTEXT;
var lUrl = father.generateUrl();
var urlAggregates = father.getUrlAggregates();
/*if (lUrl.substring(lUrl.length -1)=='/'&& urlAggregates){
lUrl = lUrl.substring(0, lUrl.length -1);
}*/
url = url + lUrl + urlAggregates;
dOptions.url=url;
father.dataLoader(dOptions);
break;
case 'L':
//check context every 50ms
function contextChecker(){
if (context.load_status=='C'){
var lUrl = father.generateUrl();
var urlAggregates = father.getUrlAggregates();
/*if (lUrl.substring(lUrl.length -1)=='/'&& urlAggregates ){
lUrl = lUrl.substring(0, lUrl.length -1);
}*/
url = url + lUrl + urlAggregates;
dOptions.url=url;
father.dataLoader(dOptions);
}else{
setTimeout(contextChecker, 50);//wait 50 milliseconds then recheck
}
}
contextChecker();
break;
}
};
/**
Places Ajax request to the server with the defined url
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.dataLoader = function (options) {
try{
var father = this;
/*$.ajax({
url: options.url,
dataType: "json",
type:"GET",
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
xhrObj.setRequestHeader("RMPData-Version", this.version);
},
accepts:"application/json",
success: function(rdata){
var ret = rdata.feed||rdata;
options.onSuccess(ret);
},
error: function(e){
options.eObject=e;
father.errorManager(options);
}
});*/
$.ajax({
url: options.url,
dataType: "json",
setRequestHeader: {Accept: 'application/json',
P_SDK_Version: context.version},
success: function(rdata){
var ret = rdata.feed||rdata;
options.onSuccess(ret);
},
error: function(e){
if (!options.onFailure) {
father.errorManager({"eOptions":e});
} else {
options.onFailure(e);
};
}
}).done(function() {
});
}catch (e) {
options.eObject=e;
this.errorManager(options);
};
};
/**
@DEPRECATED
Places Ajax request to the server with the defined url with Offline capabilities
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {Resource~cachedCallback} [options.cachedCallback] - a callback function that returns the cached data
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
*/
Resource.prototype.dataLoaderOffline = function (options) {
try{
var father = this;
var ajaxSetup = {
headers : {
"RMPData-Version":father.version
}
};
if (options.ajaxSetup)ajaxSetup = options.ajaxSetup;
$.ajaxSetup(ajaxSetup);
$.retrieveJSON(options.url, function(rdata, status) {
var ret = rdata.feed||rdata;
if( status === "cached" ) {
if(options.cachedCallback) options.cachedCallback(ret);
}
if( status === "success" ) {
options.onSuccess(ret);
}
}).done(function(){
//Add some finally functionality
}).error(function(e){
options.eObject=e;
father.errorManager(options);
});
}catch (e) {
options.eObject=e;
this.errorManager(options);
};
};
/**
Places Ajax request to the server as Put, Delete or Post
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
@param {String} options.method - method of request (PUT, DELETE or POST)
@param {String} options.xml - xml string to be posted to the server
*/
Resource.prototype.dataPost = function (options) {
// Bug.-undefined load_status workaround must be fixed to accept context reloads
// a switch must be created in the initial load function so the load fuction
// waits until the load has compleated to reload
if (context.load_status === undefined && context.customer_id !== undefined) {
context.load_status = 'C';
} //END Bug workarround
var postUrl = options.baseUrl || RMPApplication.getBaseUrl();
var v_contentType = this.contentType || 'xml';
var post_method='';
var father = this;
var prefix='?';
switch(options.method){
case "PUT":
post_method=prefix+'method=PUT';
break;
case "DELETE":
post_method=prefix+'method=DELETE';
break;
}
var v_mode ='';
if(options.mode) {
if (post_method)prefix='&'
v_mode = prefix+'mode='+options.mode;
}
/*if (options.method=='PUT'){
post_method='?method=PUT';
}
if (options.method=='DELETE'){
post_method='?method=DELETE';
}*/
var accept = options.accept||'application/json';
switch (context.load_status) {
case 'NL':
//LOAD CONTEXT;
var initOptions = {};
initOptions.OnSuccess = function (rdata) {
postUrl = postUrl + father.generateUrl()+post_method+v_mode;
jQuery.ajax({
beforeSend: function (xhr){
xhr.setRequestHeader("Accept",accept);
},
type: "POST",
url:postUrl,
data:options.xml,
contentType:"application/xml",
success:function (rxml) {
options.onSuccess(rxml);
},
error:function (e) {
options.eObject=e;
father.errorManager(options);
}
});
};
initOptions.onFailure = function(e){
options.eObject=e;
father.errorManager(options);
};
initOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
context.init(initOptions);
break;
case 'C':
//USE CONTEXT;
postUrl = postUrl + father.generateUrl()+post_method+v_mode;
jQuery.ajax({
beforeSend: function (xhr){
xhr.setRequestHeader("Accept",accept);
},
type: "POST",
url:postUrl,
data:options.xml,
contentType:"application/xml",
success:function (rxml) {
options.onSuccess(rxml);
},
error:function (e) {
options.eObject=e;
father.errorManager(options);
}
});
break;
case 'L':
//check context every 50ms
function contextChecker(){
if (context.load_status=='C'){
postUrl = postUrl + father.generateUrl() + post_method+v_mode;
jQuery.ajax({
beforeSend: function (xhr){
xhr.setRequestHeader("Accept",accept);
},
type: "POST",
url:postUrl,
data:options.xml,
contentType:"application/xml",
success:function (rxml) {
options.onSuccess(rxml);
},
error:function (e) {
options.eObject=e;
father.errorManager(options);
}
});
}else{
setTimeout(contextChecker, 50);//wait 50 millisecnds then recheck
}
};
contextChecker();
break;
}
};
/**
Places Ajax request to the server as Put, Delete or Post for JSON objects
@method
@param {object} options - options to be used during the call<br/>
@param {Resource~onSuccess} options.onSuccess - a callback function called in case of a success
@param {Resource~onFailure} [options.onFailure] - a callback function called in case of a failure
@param {String} [options.baseUrl] - base URL. If not set the current base URL will be used
@param {String} options.method - method of request (PUT, DELETE or POST)
@param {String} options.xml - xml string to be posted to the server
*/
Resource.prototype.jsonDataPost = function (options) {
// Bug.-undefined load_status workaround must be fixed to accept context reloads
// a switch must be created in the initial load function so the load fuction
// waits until the load has compleated to reload
if (context.load_status === undefined && context.customer_id !== undefined) {
context.load_status = 'C';
} //END Bug workarround
var postUrl = options.baseUrl || RMPApplication.getBaseUrl();
var v_contentType = this.contentType || 'xml';
var post_method='';
var father = this;
if (options.method=='PUT'){
post_method='?method=PUT';
}
if (options.method=='DELETE'){
post_method='?method=DELETE';
}
var xmlstr=father.xml;//send xml to a variable to post
switch (context.load_status) {
case 'NL':
//LOAD CONTEXT;
var initOptions = {};
initOptions.OnSuccess = function (rdata) {
postUrl = postUrl + father.generateUrl()+post_method;
jQuery.ajax({
type: "POST",
url:postUrl,
data:xmlstr,
contentType:"application/json",
accepts:"application/json",
success:function (rxml) {
options.onSuccess(rxml);
},
error:function (e) {
options.eObject=e;
father.errorManager(options);
}
});
};
initOptions.onFailure = function(e){
options.eObject=e;
father.errorManager(options);
};
initOptions.baseUrl = options.baseUrl || RMPApplication.getBaseUrl();
context.init(initOptions);
break;
case 'C':
//USE CONTEXT;
postUrl = postUrl + father.generateUrl()+post_method;
jQuery.ajax({
type: "POST",
url:postUrl,
data:xmlstr,
contentType:"application/json",
accepts:"application/json",
success:function (rxml) {
options.onSuccess(rxml);
},
error:function (e) {
options.eObject=e;
father.errorManager(options);
}
});
break;
case 'L':
//check context every 50ms
function contextChecker(){
if (context.load_status=='C'){
postUrl = postUrl + father.generateUrl()+post_method;
jQuery.ajax({
type: "POST",
url:postUrl,
data:xmlstr,
contentType:"application/json",
accepts:"application/json",
success:function (rxml) {
options.onSuccess(rxml);
},
error:function (e) {
options.eObject=e;
father.errorManager(options);
}
});
}else{
setTimeout(contextChecker, 50);//wait 50 milliseconds then recheck
}
};
contextChecker();
break;
}
};