code stringlengths 2 1.05M |
|---|
'use strict';
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports.create = (event, context, callback) => {
const timestamp = new Date().getTime();
const data = JSON.parse(event.body);
if (typeof data.name !== 'string' || typeof data.id !== 'number') {
console.error('Validation Failed');
callback(new Error('Could not create survey'));
return;
}
const params = {
TableName: process.env.SURVEYS_TABLE,
ConditionExpression: 'attribute_not_exists(surveyId)',
Item: {
surveyId: data.id,
name : data.name,
createdAt: timestamp,
updatedAt: timestamp,
}
};
dynamoDb.put(params, (error, result) => {
if (error) {
console.error(error);
callback(new Error('Could not create survey'));
return;
}
const response = {
statusCode: 200,
body: JSON.stringify(params.Item),
};
callback(null, response);
});
};
|
import React from 'react';
class LandingPacts extends React.Component {
render() {
return (
<div className="landing-pacts">
<div className="container">
{this.renderPacts()}
</div>
</div>
);
}
renderPacts() {
return this.props.pageData.get('pacts').map((pact, i) => {
let items = pact.get('items').map((item, j) => {
return (
<div className="pact-item" key={j}>
{item.get('name')}
</div>
);
});
return (
<div className="pact-section" key={i}>
<div className="section-header">{pact.get('title')}</div>
{items}
</div>
);
});
}
}
export default LandingPacts;
|
'use strict';
var Response = require('./Response'),
Strings = require('./Strings'),
logger = require('./logger'),
middleware = {
authorization: require('./middleware/authorization'),
apiKey: require('./middleware/apiKey'),
initialize: require('./middleware/initialize')
},
_ = require('lodash');
var app = {};
Response.prototype.app = app;
module.exports = _.extend(app, {
middleware : middleware,
Response : Response,
Strings : Strings
});
app.debug = false;
app.useLogger = function(implementation){
logger.init(implementation);
};
app.logger = logger.init();
|
search_result['3483']=["topic_0000000000000853_props--.html","JobVacancyDetailVm Properties",""]; |
module.exports = (function () {
var Connection = function (leftObject, connector, rightObject) {
this.leftObject = leftObject;
this.connector = connector;
this.pNamespace = null;
this.rightObject = rightObject;
}
Connection.prototype.setNamespace = function (namespace) {
this.pNamespace = namespace;
}
Connection.prototype.getConnector = function () {
return this.connector;
}
Connection.prototype.getNamespace = function () {
return this.pNamespace;
}
return Connection;
})()
|
<script type="text/javascript">
//mostra e esconde os ícones de criar tarefa, editar e remover missao
$(document).ready(function(){
$("#nomeMissao").mouseout(function(){
$("divIconesMissao").hide();
});
$("#nomeMissao").mouseover(function(){
$("divIconesMissao").show();
});
});
</script>
<!--script que executa o drag and drop-->
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
<script>
$('#myModal').on('shown.bs.modal', function() {
$('#myInput').focus();
});
</script>
<script>
$('#myModalFase').on('shown.bs.modal', function() {
$('#myInput').focus();
});
</script>
SELECT p.nome,u1.username,u2.username,u3.username,u4.username FROM time as t
INNER JOIN projetos as p
on t.id_projeto = p.id_projeto
INNER JOIN users as u1
on u1.id_usuario = t.integranteUm
INNER JOIN users as u2
on u2.id_usuario = t.integranteDois
INNER JOIN users as u3
on u3.id_usuario = t.integranteTres
INNER JOIN users as u4
on u4.id_usuario = t.integranteQuatro
SELECT p.nome FROM projeto as p
INNER JOIN time as t
ON p.id_projeto = t.id_projeto
AND (t.integranteUm = p.id_criador
OR t.integranteDois =p.id_criador
OR t.integranteTres = p.id_criador
OR t.integranteQuatro = p.id_criador )
AND t.id_criador != p.id_criador
WHERE p.id_criador = 4;
SELECT p.nome FROM projetos as p
INNER JOIN time as t
ON p.id_projeto = t.id_projeto
ON t.id_criador != p.id_criador
AND (t.integranteUm = p.id_criador
OR t.integranteDois =p.id_criador
OR t.integranteTres = p.id_criador
OR t.integranteQuatro = p.id_criador )
WHERE t.id_criador = '2';
SELECT p.nome, p.id_projeto FROM projetos as p
INNER JOIN time as ta
ON p.id_projeto = ta.id_projeto
INNER JOIN time as t
ON t.id_criador != p.id_criador
AND (t.integranteUm = t.id_criador
OR t.integranteDois =t.id_criador
OR t.integranteTres =t.id_criador
OR t.integranteQuatro = t.id_criador )
WHERE p.id_criador = '2';
SELECT p.nome, p.id_projeto FROM projetos as p
INNER JOIN time as t
ON p.id_projeto = t.id_projeto
WHERE t.id_criador != 2
AND (t.integranteUm = t.id_criador
OR t.integranteDois = t.id_criador
OR t.integranteTres = t.id_criador
OR t.integranteQuatro = t.id_criador );
SELECT p.nome, p.id_projeto FROM projetos as p
INNER JOIN time as ta
ON p.id_projeto = ta.id_projeto
INNER JOIN time as t
ON t.id_criador != p.id_criador
WHERE t.id_criador = 4
AND (t.integranteUm = t.id_criador
OR t.integranteDois = t.id_criador
OR t.integranteTres = t.id_criador
OR t.integranteQuatro = t.id_criador );
SELECT p.nome, t.id_projeto FROM projetos as p
INNER JOIN time as t
ON p.id_projeto = t.id_projeto
WHERE t.id_criador != '4'
AND (t.integranteUm = t.id_criador
OR t.integranteDois = t.id_criador
OR t.integranteTres = t.id_criador
OR t.integranteQuatro = t.id_criador ); |
'use strict';
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function noop() {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
String.prototype.formatArray = function(a){
return this.replace(/\{(\d+)\}/g, function(r,e){return a[e];});
};
String.prototype.render = function(obj){
return this.replace(/\{(\w+)\}/g, function(r,e){return obj[e];});
};
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
//jQuery extensions
(function ($) {
$.fn.validEmail = function() {
return /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( $(this).val());
};
$.extend($.expr[':'], {
// http://jqueryvalidation.org/blank-selector/
blank: function( a ) { return !$.trim('' + $(a).val()); },
// http://jqueryvalidation.org/filled-selector/
filled: function( a ) { return !!$.trim('' + $(a).val()); },
// http://jqueryvalidation.org/unchecked-selector/
unchecked: function( a ) { return !$(a).prop('checked'); }
});
/*$.expr[':'].Contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});*/
}(jQuery)); |
module.exports = {
entry: "./app.js",
output: {
path: __dirname + "/dist",
filename: "app.js"
},
module: {
loaders: [
{
test: /\.js.*$/,
exclude: /(node_modules)/,
loader: 'babel?presets[]=es2015'
}
]
},
resolve: {
alias: {
vex: 'vex-js'
}
}
};
|
/*!
* froala_editor v3.2.0 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2020 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* Serbian (Latin)
*/
FE.LANGUAGE['sr'] = {
translation: {
// Place holder
'Type something': "Ukucajte ne\u0161tp",
// Basic formatting
'Bold': 'Podebljan',
'Italic': "Isko\u0161en",
'Underline': "Podvu\u010Deno",
'Strikethrough': 'Precrtan',
// Main buttons
'Insert': 'Umetanje',
'Delete': "Izbri\u0161i",
'Cancel': 'Otkazivanje',
'OK': 'Ok',
'Back': 'Nazad',
'Remove': 'Uklonite',
'More': "Vi\u0161e",
'Update': "A\u017Euriranje",
'Style': 'Stil',
// Font
'Font Family': 'Odaberi font',
'Font Size': "Veli\u010Dina fontova",
// Colors
'Colors': 'Boje',
'Background': 'Pozadina',
'Text': 'Tekst',
'HEX Color': 'HEX boje',
// Paragraphs
'Paragraph Format': 'Format pasusa',
'Normal': 'Normalno',
'Code': "\u0160ifra",
'Heading 1': 'Naslov 1',
'Heading 2': 'Naslov 2',
'Heading 3': 'Naslov 3',
'Heading 4': 'Naslov 4',
// Style
'Paragraph Style': 'Stil pasusa',
'Inline Style': 'Umetnutih stilova',
// Alignment
'Align': 'Poravnavanje',
'Align Left': 'Poravnaj levo',
'Align Center': 'Poravnaj u centru',
'Align Right': 'Poravnaj desno',
'Align Justify': 'Obostrano poravnavanje',
'None': 'Niko nije',
// Lists
'Ordered List': "Ure\u0111enih lista",
'Unordered List': "Neure\u0111enu lista",
// Indent
'Decrease Indent': "Smanjivanje uvla\u010Denja",
'Increase Indent': "Pove\u0107avanje uvla\u010Denja",
// Links
'Insert Link': 'Umetni vezu',
'Open in new tab': 'Otvori na novoj kartici',
'Open Link': 'Otvori vezu',
'Edit Link': "Ure\u0111ivanje veze",
'Unlink': 'Ukloni vezu',
'Choose Link': 'Odaberite vezu',
// Images
'Insert Image': 'Umetanje slike',
'Upload Image': 'Otpremanje slika',
'By URL': 'Po URL adresi',
'Browse': "Potra\u017Ei",
'Drop image': 'Baci sliku',
'or click': 'ili kliknite na dugme',
'Manage Images': 'Upravljanje slike',
'Loading': "U\u010Ditavanje",
'Deleting': 'Brisanje',
'Tags': 'Oznake',
'Are you sure? Image will be deleted.': "Jesi siguran? Slika \u0107e biti izbrisana.",
'Replace': 'Zameni',
'Uploading': 'Otpremanje',
'Loading image': "U\u010Ditavanje slika",
'Display': 'Prikaz',
'Inline': 'Pri upisivanju',
'Break Text': 'Prelom teksta',
'Alternative Text': 'Alternativni tekst',
'Change Size': "Promena veli\u010Dine",
'Width': "\u0160irina",
'Height': 'Visina',
'Something went wrong. Please try again.': "Ne\u0161to krenulo naopako. Poku\u0161ajte ponovo.",
'Image Caption': 'Slika natpisa',
'Advanced Edit': 'Napredno uređivanje',
// Video
'Insert Video': 'Umetanje video',
'Embedded Code': "Ugra\u0111eni k\xF4d",
'Paste in a video URL': 'Lepljenje u video URL',
'Drop video': 'Baci snimak',
'Your browser does not support HTML5 video.': 'Vaš pregledač ne podržava HTML5 video.',
'Upload Video': 'Otpremanje video',
// Tables
'Insert Table': 'Umetni tabelu',
'Table Header': 'Zaglavlje tabele',
'Remove Table': 'Uklanjanje tabele',
'Table Style': 'Stil tabele',
'Horizontal Align': 'Horizontalno poravnavanje',
'Row': 'Red',
'Insert row above': 'Umetni red iznad',
'Insert row below': 'Umetni red ispod',
'Delete row': "Izbri\u0161i red",
'Column': 'Kolone',
'Insert column before': 'Umetnite kolonu pre',
'Insert column after': 'Umetnite kolonu nakon',
'Delete column': "Izbri\u0161i kolone",
'Cell': 'Mobilni',
'Merge cells': "Objedinjavanje \u0107elija",
'Horizontal split': 'Horizontalna split',
'Vertical split': 'Vertikalno razdelite',
'Cell Background': 'Mobilni pozadina',
'Vertical Align': 'Vertikalno poravnavanje',
'Top': 'Top',
'Middle': 'Srednji',
'Bottom': 'Dno',
'Align Top': 'Poravnaj gore',
'Align Middle': 'Poravnaj po sredini',
'Align Bottom': 'Poravnaj dole',
'Cell Style': 'Mobilni stil',
// Files
'Upload File': 'Otpremanje datoteke',
'Drop file': 'Baci datoteku',
// Emoticons
'Emoticons': 'Emotikona',
'Grinning face': 'Nasmejanoj lice',
'Grinning face with smiling eyes': "Nasmejanoj lice sa osmehom o\u010Di",
'Face with tears of joy': "Suo\u010Davaju sa suzama radosnicama",
'Smiling face with open mouth': 'Nasmejano lice sa otvorenim ustima',
'Smiling face with open mouth and smiling eyes': "Lica sa otvorenim ustima i nasmejani o\u010Di",
'Smiling face with open mouth and cold sweat': 'Nasmejano lice sa otvorenih usta i hladan znoj',
'Smiling face with open mouth and tightly-closed eyes': "Nasmejano lice otvorenih usta i \u010Dvrsto zatvorenih o\u010Diju",
'Smiling face with halo': 'Nasmejano lice sa oreolom',
'Smiling face with horns': 'Nasmejano lice sa rogovima',
'Winking face': 'Namigivanje lice',
'Smiling face with smiling eyes': "Lica sa osmehom o\u010Di",
'Face savoring delicious food': "Lice u\u045Bivaju\u0436i u ukusnu hranu",
'Relieved face': 'Laknulo lice',
'Smiling face with heart-shaped eyes': "Nasmejano lice sa o\u010Dima u obliku srca",
'Smiling face with sunglasses': "Nasmejano lice sa nao\u010Dare",
'Smirking face': "Rugaju\u0436i lice",
'Neutral face': 'Neutralno lice',
'Expressionless face': 'Bez izraza lica.',
'Unamused face': 'Nije zapaljen lice',
'Face with cold sweat': "Suo\u010Davaju sa hladnim znojem",
'Pensive face': 'Nevesela lica',
'Confused face': 'Zbunjeno lice',
'Confounded face': 'Dosadnih lice',
'Kissing face': 'Ljubim lice',
'Face throwing a kiss': 'Lice baca poljubac',
'Kissing face with smiling eyes': "Ljubi lice sa osmehom o\u010Di",
'Kissing face with closed eyes': "Ljubi lice sa zatvorenim o\u010Dima",
'Face with stuck out tongue': 'Lice sa zaglavio jezik',
'Face with stuck out tongue and winking eye': 'Lice sa zaglavljen jezik i namigivanje',
'Face with stuck out tongue and tightly-closed eyes': "Lice sa zaglavljen jezik i cvrsto zatvorene o\u010Di",
'Disappointed face': "Razo\u010Darani lice",
'Worried face': 'Zabrinuto lice',
'Angry face': 'Ljut lice',
'Pouting face': 'Zlovoljan lice',
'Crying face': 'Plakanje lice',
'Persevering face': 'Istrajnog lice',
'Face with look of triumph': "Suo\u010Davaju sa izgledom trijumfa",
'Disappointed but relieved face': "Razo\u010Daran ali laknulo lice",
'Frowning face with open mouth': 'Namršten lice sa otvorenim ustima',
'Anguished face': 'Enih lica',
'Fearful face': 'Strahu lice',
'Weary face': 'Umorna lica',
'Sleepy face': 'Spava mi se lice',
'Tired face': 'Umorna lica',
'Grimacing face': 'Klupi lice',
'Loudly crying face': 'Glasno plakanje lice',
'Face with open mouth': "Suo\u010Davaju sa otvorenim ustima",
'Hushed face': 'Tihim lice',
'Face with open mouth and cold sweat': "Suo\u010Davaju sa otvorenih usta i hladan znoj",
'Face screaming in fear': 'Lice vrisak u strahu',
'Astonished face': 'Zadivljeni lice',
'Flushed face': 'Uplakanu lice',
'Sleeping face': 'Pospanog lica',
'Dizzy face': 'Lice mi se vrti',
'Face without mouth': 'Lice bez jezika',
'Face with medical mask': "Suo\u010Davaju sa medicinskim masku",
// Line breaker
'Break': 'Prelom',
// Math
'Subscript': 'Indeksni tekst',
'Superscript': 'Eksponentni tekst',
// Full screen
'Fullscreen': 'Puni ekran',
// Horizontal line
'Insert Horizontal Line': 'Umetni horizontalnu liniju',
// Clear formatting
'Clear Formatting': 'Brisanje oblikovanja',
// Save
'Save': "\u0441\u0430\u0447\u0443\u0432\u0430\u0442\u0438",
// Undo, redo
'Undo': 'Opozovi radnju',
'Redo': 'Ponavljanje',
// Select all
'Select All': 'Izaberi sve',
// Code view
'Code View': 'Prikaz koda',
// Quote
'Quote': 'Ponude',
'Increase': "Pove\u0107anje",
'Decrease': 'Smanjivanje',
// Quick Insert
'Quick Insert': 'Brzo umetanje',
// Spcial Characters
'Special Characters': 'Specijalni znakovi',
'Latin': 'Latino',
'Greek': 'Grk',
'Cyrillic': 'Ćirilica',
'Punctuation': 'Interpunkcije',
'Currency': 'Valuta',
'Arrows': 'Strelice',
'Math': 'Matematika',
'Misc': 'Misc',
// Print.
'Print': 'Odštampaj',
// Spell Checker.
'Spell Checker': 'Kontrolor pravopisa',
// Help
'Help': 'Pomoć',
'Shortcuts': 'Prečice',
'Inline Editor': 'Pri upisivanju Editor',
'Show the editor': 'Prikaži urednik',
'Common actions': 'Zajedničke akcije',
'Copy': 'Kopija',
'Cut': 'Rez',
'Paste': 'Nalepi',
'Basic Formatting': 'Osnovno oblikovanje',
'Increase quote level': 'Povećati ponudu za nivo',
'Decrease quote level': 'Smanjenje ponude nivo',
'Image / Video': 'Slika / Video',
'Resize larger': 'Veće veličine',
'Resize smaller': 'Promena veličine manji',
'Table': 'Sto',
'Select table cell': 'Select ćelije',
'Extend selection one cell': 'Proširite selekciju jednu ćeliju',
'Extend selection one row': 'Proširite selekciju jedan red',
'Navigation': 'Navigacija',
'Focus popup / toolbar': 'Fokus Iskačući meni / traka sa alatkama',
'Return focus to previous position': 'Vratiti fokus na prethodnu poziciju',
// Embed.ly
'Embed URL': 'Ugradite URL',
'Paste in a URL to embed': 'Nalepite URL adresu da biste ugradili',
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'Nalepljeni sadržaj dolazi iz Microsoft Word dokument. Da li želite zadržati u formatu ili počistiti?',
'Keep': 'Nastavi',
'Clean': 'Oиisti',
'Word Paste Detected': 'Word Nalepi otkriven',
// Character Counter
'Characters': 'Цхарацтерс',
// More Buttons
'More Text': 'море Тект',
'More Paragraph': 'Више Параграф',
'More Rich': 'Више Богат',
'More Misc': 'Више Мисц'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=sr.js.map
|
(function () {
'use strict';
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
/** @license MIT License (c) copyright 2010-2016 original author or authors */
// a with x appended
function append(x, a) {
var l = a.length;
var b = new Array(l + 1);
for (var i = 0; i < l; ++i) {
b[i] = a[i];
}
b[l] = x;
return b;
} // drop :: Int -> [a] -> [a]
// transform each element with f
function map(f, a) {
var l = a.length;
var b = new Array(l);
for (var i = 0; i < l; ++i) {
b[i] = f(a[i]);
}
return b;
} // reduce :: (a -> b -> a) -> a -> [b] -> a
// accumulate via left-fold
function reduce(f, z, a) {
var r = z;
for (var i = 0, l = a.length; i < l; ++i) {
r = f(r, a[i], i);
}
return r;
} // replace :: a -> Int -> [a]
// remove element at index
function remove(i, a) {
// eslint-disable-line complexity
if (i < 0) {
throw new TypeError('i must be >= 0');
}
var l = a.length;
if (l === 0 || i >= l) {
// exit early if index beyond end of array
return a;
}
if (l === 1) {
// exit early if index in bounds and length === 1
return [];
}
return unsafeRemove(i, a, l - 1);
} // unsafeRemove :: Int -> [a] -> Int -> [a]
// Internal helper to remove element at index
function unsafeRemove(i, a, l) {
var b = new Array(l);
var j = void 0;
for (j = 0; j < i; ++j) {
b[j] = a[j];
}
for (j = i; j < l; ++j) {
b[j] = a[j + 1];
}
return b;
} // removeAll :: (a -> boolean) -> [a] -> [a]
// remove all elements matching a predicate
function removeAll(f, a) {
var l = a.length;
var b = new Array(l);
var j = 0;
for (var x, i = 0; i < l; ++i) {
x = a[i];
if (!f(x)) {
b[j] = x;
++j;
}
}
b.length = j;
return b;
} // findIndex :: a -> [a] -> Int
// find index of x in a, from the left
function findIndex(x, a) {
for (var i = 0, l = a.length; i < l; ++i) {
if (x === a[i]) {
return i;
}
}
return -1;
} // isArrayLike :: * -> boolean
var compose = function compose(f, g) {
return function (x) {
return f(g(x));
};
}; // apply :: (a -> b) -> a -> b
function curry2(f) {
function curried(a, b) {
switch (arguments.length) {
case 0:
return curried;
case 1:
return function (b) {
return f(a, b);
};
default:
return f(a, b);
}
}
return curried;
} // curry3 :: ((a, b, c) -> d) -> (a -> b -> c -> d)
function curry3(f) {
function curried(a, b, c) {
// eslint-disable-line complexity
switch (arguments.length) {
case 0:
return curried;
case 1:
return curry2(function (b, c) {
return f(a, b, c);
});
case 2:
return function (c) {
return f(a, b, c);
};
default:
return f(a, b, c);
}
}
return curried;
} // curry4 :: ((a, b, c, d) -> e) -> (a -> b -> c -> d -> e)
var classCallCheck = function classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var ScheduledTask =
/*#__PURE__*/
function () {
function ScheduledTask(time, localOffset, period, task, scheduler) {
classCallCheck(this, ScheduledTask);
this.time = time;
this.localOffset = localOffset;
this.period = period;
this.task = task;
this.scheduler = scheduler;
this.active = true;
}
ScheduledTask.prototype.run = function run() {
return this.task.run(this.time - this.localOffset);
};
ScheduledTask.prototype.error = function error(e) {
return this.task.error(this.time - this.localOffset, e);
};
ScheduledTask.prototype.dispose = function dispose() {
this.scheduler.cancel(this);
return this.task.dispose();
};
return ScheduledTask;
}();
var RelativeScheduler =
/*#__PURE__*/
function () {
function RelativeScheduler(origin, scheduler) {
classCallCheck(this, RelativeScheduler);
this.origin = origin;
this.scheduler = scheduler;
}
RelativeScheduler.prototype.currentTime = function currentTime() {
return this.scheduler.currentTime() - this.origin;
};
RelativeScheduler.prototype.scheduleTask = function scheduleTask(localOffset, delay, period, task) {
return this.scheduler.scheduleTask(localOffset + this.origin, delay, period, task);
};
RelativeScheduler.prototype.relative = function relative(origin) {
return new RelativeScheduler(origin + this.origin, this.scheduler);
};
RelativeScheduler.prototype.cancel = function cancel(task) {
return this.scheduler.cancel(task);
};
RelativeScheduler.prototype.cancelAll = function cancelAll(f) {
return this.scheduler.cancelAll(f);
};
return RelativeScheduler;
}();
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var defer = function defer(task) {
return Promise.resolve(task).then(runTask);
};
function runTask(task) {
try {
return task.run();
} catch (e) {
return task.error(e);
}
}
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var Scheduler =
/*#__PURE__*/
function () {
function Scheduler(timer, timeline) {
var _this = this;
classCallCheck(this, Scheduler);
this.timer = timer;
this.timeline = timeline;
this._timer = null;
this._nextArrival = Infinity;
this._runReadyTasksBound = function () {
return _this._runReadyTasks(_this.currentTime());
};
}
Scheduler.prototype.currentTime = function currentTime() {
return this.timer.now();
};
Scheduler.prototype.scheduleTask = function scheduleTask(localOffset, delay, period, task) {
var time = this.currentTime() + Math.max(0, delay);
var st = new ScheduledTask(time, localOffset, period, task, this);
this.timeline.add(st);
this._scheduleNextRun();
return st;
};
Scheduler.prototype.relative = function relative(offset) {
return new RelativeScheduler(offset, this);
};
Scheduler.prototype.cancel = function cancel(task) {
task.active = false;
if (this.timeline.remove(task)) {
this._reschedule();
}
};
Scheduler.prototype.cancelAll = function cancelAll(f) {
this.timeline.removeAll(f);
this._reschedule();
};
Scheduler.prototype._reschedule = function _reschedule() {
if (this.timeline.isEmpty()) {
this._unschedule();
} else {
this._scheduleNextRun(this.currentTime());
}
};
Scheduler.prototype._unschedule = function _unschedule() {
this.timer.clearTimer(this._timer);
this._timer = null;
};
Scheduler.prototype._scheduleNextRun = function _scheduleNextRun() {
// eslint-disable-line complexity
if (this.timeline.isEmpty()) {
return;
}
var nextArrival = this.timeline.nextArrival();
if (this._timer === null) {
this._scheduleNextArrival(nextArrival);
} else if (nextArrival < this._nextArrival) {
this._unschedule();
this._scheduleNextArrival(nextArrival);
}
};
Scheduler.prototype._scheduleNextArrival = function _scheduleNextArrival(nextArrival) {
this._nextArrival = nextArrival;
var delay = Math.max(0, nextArrival - this.currentTime());
this._timer = this.timer.setTimer(this._runReadyTasksBound, delay);
};
Scheduler.prototype._runReadyTasks = function _runReadyTasks() {
this._timer = null;
this.timeline.runTasks(this.currentTime(), runTask);
this._scheduleNextRun();
};
return Scheduler;
}();
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var Timeline =
/*#__PURE__*/
function () {
function Timeline() {
classCallCheck(this, Timeline);
this.tasks = [];
}
Timeline.prototype.nextArrival = function nextArrival() {
return this.isEmpty() ? Infinity : this.tasks[0].time;
};
Timeline.prototype.isEmpty = function isEmpty() {
return this.tasks.length === 0;
};
Timeline.prototype.add = function add(st) {
insertByTime(st, this.tasks);
};
Timeline.prototype.remove = function remove$$1(st) {
var i = binarySearch(getTime(st), this.tasks);
if (i >= 0 && i < this.tasks.length) {
var at = findIndex(st, this.tasks[i].events);
if (at >= 0) {
this.tasks[i].events.splice(at, 1);
return true;
}
}
return false;
};
Timeline.prototype.removeAll = function removeAll$$1(f) {
for (var i = 0; i < this.tasks.length; ++i) {
removeAllFrom(f, this.tasks[i]);
}
};
Timeline.prototype.runTasks = function runTasks(t, runTask) {
var tasks = this.tasks;
var l = tasks.length;
var i = 0;
while (i < l && tasks[i].time <= t) {
++i;
}
this.tasks = tasks.slice(i); // Run all ready tasks
for (var j = 0; j < i; ++j) {
this.tasks = runReadyTasks(runTask, tasks[j].events, this.tasks);
}
};
return Timeline;
}();
function runReadyTasks(runTask, events, tasks) {
// eslint-disable-line complexity
for (var i = 0; i < events.length; ++i) {
var task = events[i];
if (task.active) {
runTask(task); // Reschedule periodic repeating tasks
// Check active again, since a task may have canceled itself
if (task.period >= 0 && task.active) {
task.time = task.time + task.period;
insertByTime(task, tasks);
}
}
}
return tasks;
}
function insertByTime(task, timeslots) {
var l = timeslots.length;
var time = getTime(task);
if (l === 0) {
timeslots.push(newTimeslot(time, [task]));
return;
}
var i = binarySearch(time, timeslots);
if (i >= l) {
timeslots.push(newTimeslot(time, [task]));
} else {
insertAtTimeslot(task, timeslots, time, i);
}
}
function insertAtTimeslot(task, timeslots, time, i) {
var timeslot = timeslots[i];
if (time === timeslot.time) {
addEvent(task, timeslot.events, time);
} else {
timeslots.splice(i, 0, newTimeslot(time, [task]));
}
}
function addEvent(task, events) {
if (events.length === 0 || task.time >= events[events.length - 1].time) {
events.push(task);
} else {
spliceEvent(task, events);
}
}
function spliceEvent(task, events) {
for (var j = 0; j < events.length; j++) {
if (task.time < events[j].time) {
events.splice(j, 0, task);
break;
}
}
}
function getTime(scheduledTask) {
return Math.floor(scheduledTask.time);
}
function removeAllFrom(f, timeslot) {
timeslot.events = removeAll(f, timeslot.events);
}
function binarySearch(t, sortedArray) {
// eslint-disable-line complexity
var lo = 0;
var hi = sortedArray.length;
var mid = void 0,
y = void 0;
while (lo < hi) {
mid = Math.floor((lo + hi) / 2);
y = sortedArray[mid];
if (t === y.time) {
return mid;
} else if (t < y.time) {
hi = mid;
} else {
lo = mid + 1;
}
}
return hi;
}
var newTimeslot = function newTimeslot(t, events) {
return {
time: t,
events: events
};
};
/** @license MIT License (c) copyright 2010-2017 original author or authors */
/* global setTimeout, clearTimeout */
var ClockTimer =
/*#__PURE__*/
function () {
function ClockTimer(clock) {
classCallCheck(this, ClockTimer);
this._clock = clock;
}
ClockTimer.prototype.now = function now() {
return this._clock.now();
};
ClockTimer.prototype.setTimer = function setTimer(f, dt) {
return dt <= 0 ? runAsap(f) : setTimeout(f, dt);
};
ClockTimer.prototype.clearTimer = function clearTimer(t) {
return t instanceof Asap ? t.cancel() : clearTimeout(t);
};
return ClockTimer;
}();
var Asap =
/*#__PURE__*/
function () {
function Asap(f) {
classCallCheck(this, Asap);
this.f = f;
this.active = true;
}
Asap.prototype.run = function run() {
return this.active && this.f();
};
Asap.prototype.error = function error(e) {
throw e;
};
Asap.prototype.cancel = function cancel() {
this.active = false;
};
return Asap;
}();
function runAsap(f) {
var task = new Asap(f);
defer(task);
return task;
}
/** @license MIT License (c) copyright 2010-2017 original author or authors */
/* global performance, process */
var RelativeClock =
/*#__PURE__*/
function () {
function RelativeClock(clock, origin) {
classCallCheck(this, RelativeClock);
this.origin = origin;
this.clock = clock;
}
RelativeClock.prototype.now = function now() {
return this.clock.now() - this.origin;
};
return RelativeClock;
}();
var HRTimeClock =
/*#__PURE__*/
function () {
function HRTimeClock(hrtime, origin) {
classCallCheck(this, HRTimeClock);
this.origin = origin;
this.hrtime = hrtime;
}
HRTimeClock.prototype.now = function now() {
var hrt = this.hrtime(this.origin);
return (hrt[0] * 1e9 + hrt[1]) / 1e6;
};
return HRTimeClock;
}();
var clockRelativeTo = function clockRelativeTo(clock) {
return new RelativeClock(clock, clock.now());
};
var newPerformanceClock = function newPerformanceClock() {
return clockRelativeTo(performance);
};
var newDateClock = function newDateClock() {
return clockRelativeTo(Date);
};
var newHRTimeClock = function newHRTimeClock() {
return new HRTimeClock(process.hrtime, process.hrtime());
};
var newPlatformClock = function newPlatformClock() {
if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
return newPerformanceClock();
} else if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
return newHRTimeClock();
}
return newDateClock();
}; // Read the current time from the provided Scheduler
var currentTime = function currentTime(scheduler) {
return scheduler.currentTime();
}; // Schedule a task to run as soon as possible, but
// not in the current call stack
var asap =
/*#__PURE__*/
curry2(function (task, scheduler) {
return scheduler.scheduleTask(0, 0, -1, task);
}); // Schedule a task to run after a millisecond delay
var delay =
/*#__PURE__*/
curry3(function (delay, task, scheduler) {
return scheduler.scheduleTask(0, delay, -1, task);
}); // Schedule a task to run periodically, with the
// first run starting asap
var periodic =
/*#__PURE__*/
curry3(function (period, task, scheduler) {
return scheduler.scheduleTask(0, 0, period, task);
}); // Cancel a scheduledTask
// is true
var cancelAllTasks =
/*#__PURE__*/
curry2(function (predicate, scheduler) {
return scheduler.cancelAll(predicate);
});
var schedulerRelativeTo =
/*#__PURE__*/
curry2(function (offset, scheduler) {
return new RelativeScheduler(offset, scheduler);
});
var newDefaultScheduler = function newDefaultScheduler() {
return new Scheduler(newDefaultTimer(), new Timeline());
};
var newDefaultTimer = function newDefaultTimer() {
return new ClockTimer(newPlatformClock());
};
var classCallCheck$1 = function classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var disposeNone = function disposeNone() {
return NONE;
};
var NONE =
/*#__PURE__*/
new (function () {
function DisposeNone() {
classCallCheck$1(this, DisposeNone);
}
DisposeNone.prototype.dispose = function dispose() {};
return DisposeNone;
}())();
var isDisposeNone = function isDisposeNone(d) {
return d === NONE;
};
/** @license MIT License (c) copyright 2010-2017 original author or authors */
// Wrap an existing disposable (which may not already have been once()d)
// so that it will only dispose its underlying resource at most once.
var disposeOnce = function disposeOnce(disposable) {
return new DisposeOnce(disposable);
};
var DisposeOnce =
/*#__PURE__*/
function () {
function DisposeOnce(disposable) {
classCallCheck$1(this, DisposeOnce);
this.disposed = false;
this.disposable = disposable;
}
DisposeOnce.prototype.dispose = function dispose() {
if (!this.disposed) {
this.disposed = true;
this.disposable.dispose();
this.disposable = undefined;
}
};
return DisposeOnce;
}();
// disposed/released. It aggregates a function to dispose
// the resource and a handle to a key/id/handle/reference
// that identifies the resource
var DisposeWith =
/*#__PURE__*/
function () {
function DisposeWith(dispose, resource) {
classCallCheck$1(this, DisposeWith);
this._dispose = dispose;
this._resource = resource;
}
DisposeWith.prototype.dispose = function dispose() {
this._dispose(this._resource);
};
return DisposeWith;
}();
/** @license MIT License (c) copyright 2010 original author or authors */
// Aggregate a list of disposables into a DisposeAll
var disposeAll = function disposeAll(ds) {
var merged = reduce(merge, [], ds);
return merged.length === 0 ? disposeNone() : new DisposeAll(merged);
}; // Convenience to aggregate 2 disposables
var disposeBoth =
/*#__PURE__*/
curry2(function (d1, d2) {
return disposeAll([d1, d2]);
});
var merge = function merge(ds, d) {
return isDisposeNone(d) ? ds : d instanceof DisposeAll ? ds.concat(d.disposables) : append(d, ds);
};
var DisposeAll =
/*#__PURE__*/
function () {
function DisposeAll(disposables) {
classCallCheck$1(this, DisposeAll);
this.disposables = disposables;
}
DisposeAll.prototype.dispose = function dispose() {
throwIfErrors(disposeCollectErrors(this.disposables));
};
return DisposeAll;
}(); // Dispose all, safely collecting errors into an array
var disposeCollectErrors = function disposeCollectErrors(disposables) {
return reduce(appendIfError, [], disposables);
}; // Call dispose and if throws, append thrown error to errors
var appendIfError = function appendIfError(errors, d) {
try {
d.dispose();
} catch (e) {
errors.push(e);
}
return errors;
}; // Throw DisposeAllError if errors is non-empty
var throwIfErrors = function throwIfErrors(errors) {
if (errors.length > 0) {
throw new DisposeAllError(errors.length + ' errors', errors);
}
};
var DisposeAllError =
/*#__PURE__*/
function (Error) {
function DisposeAllError(message, errors) {
Error.call(this, message);
this.message = message;
this.name = DisposeAllError.name;
this.errors = errors;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, DisposeAllError);
}
this.stack = '' + this.stack + formatErrorStacks(this.errors);
}
DisposeAllError.prototype =
/*#__PURE__*/
Object.create(Error.prototype);
return DisposeAllError;
}(Error);
var formatErrorStacks = function formatErrorStacks(errors) {
return reduce(formatErrorStack, '', errors);
};
var formatErrorStack = function formatErrorStack(s, e, i) {
return s + ('\n[' + (i + 1) + '] ' + e.stack);
};
/** @license MIT License (c) copyright 2010-2017 original author or authors */
// Try to dispose the disposable. If it throws, send
// the error to sink.error with the provided Time value
var tryDispose =
/*#__PURE__*/
curry3(function (t, disposable, sink) {
try {
disposable.dispose();
} catch (e) {
sink.error(t, e);
}
});
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
function fatalError(e) {
setTimeout(rethrow, 0, e);
}
function rethrow(e) {
throw e;
}
var classCallCheck$2 = function classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var inherits = function inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + _typeof(superClass));
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (_typeof(call) === "object" || typeof call === "function") ? call : self;
};
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var propagateTask$1 = function propagateTask(run, value, sink) {
return new PropagateTask(run, value, sink);
};
var propagateEventTask$1 = function propagateEventTask(value, sink) {
return propagateTask$1(runEvent, value, sink);
};
var propagateEndTask = function propagateEndTask(sink) {
return propagateTask$1(runEnd, undefined, sink);
};
var propagateErrorTask$1 = function propagateErrorTask(value, sink) {
return propagateTask$1(runError, value, sink);
};
var PropagateTask =
/*#__PURE__*/
function () {
function PropagateTask(run, value, sink) {
classCallCheck$2(this, PropagateTask);
this._run = run;
this.value = value;
this.sink = sink;
this.active = true;
}
PropagateTask.prototype.dispose = function dispose$$1() {
this.active = false;
};
PropagateTask.prototype.run = function run(t) {
if (!this.active) {
return;
}
var run = this._run;
run(t, this.value, this.sink);
};
PropagateTask.prototype.error = function error(t, e) {
// TODO: Remove this check and just do this.sink.error(t, e)?
if (!this.active) {
return fatalError(e);
}
this.sink.error(t, e);
};
return PropagateTask;
}();
var runEvent = function runEvent(t, x, sink) {
return sink.event(t, x);
};
var runEnd = function runEnd(t, _, sink) {
return sink.end(t);
};
var runError = function runError(t, e, sink) {
return sink.error(t, e);
};
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var empty = function empty() {
return EMPTY;
};
var isCanonicalEmpty = function isCanonicalEmpty(stream) {
return stream === EMPTY;
};
var Empty =
/*#__PURE__*/
function () {
function Empty() {
classCallCheck$2(this, Empty);
}
Empty.prototype.run = function run(sink, scheduler$$1) {
return asap(propagateEndTask(sink), scheduler$$1);
};
return Empty;
}();
var EMPTY =
/*#__PURE__*/
new Empty();
var Never =
/*#__PURE__*/
function () {
function Never() {
classCallCheck$2(this, Never);
}
Never.prototype.run = function run() {
return disposeNone();
};
return Never;
}();
var NEVER =
/*#__PURE__*/
new Never();
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var at = function at(t, x) {
return new At(t, x);
};
var At =
/*#__PURE__*/
function () {
function At(t, x) {
classCallCheck$2(this, At);
this.time = t;
this.value = x;
}
At.prototype.run = function run(sink, scheduler$$1) {
return delay(this.time, propagateTask$1(runAt, this.value, sink), scheduler$$1);
};
return At;
}();
function runAt(t, x, sink) {
sink.event(t, x);
sink.end(t);
}
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var now = function now(x) {
return at(0, x);
};
var Periodic =
/*#__PURE__*/
function () {
function Periodic(period) {
classCallCheck$2(this, Periodic);
this.period = period;
}
Periodic.prototype.run = function run(sink, scheduler$$1) {
return periodic(this.period, propagateEventTask$1(undefined, sink), scheduler$$1);
};
return Periodic;
}();
/** @license MIT License (c) copyright 2010-2017 original author or authors */
/** @author Brian Cavalier */
var Pipe =
/*#__PURE__*/
function () {
function Pipe(sink) {
classCallCheck$2(this, Pipe);
this.sink = sink;
}
Pipe.prototype.event = function event(t, x) {
return this.sink.event(t, x);
};
Pipe.prototype.end = function end(t) {
return this.sink.end(t);
};
Pipe.prototype.error = function error(t, e) {
return this.sink.error(t, e);
};
return Pipe;
}();
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Filter =
/*#__PURE__*/
function () {
function Filter(p, source) {
classCallCheck$2(this, Filter);
this.p = p;
this.source = source;
}
Filter.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new FilterSink(this.p, sink), scheduler$$1);
};
/**
* Create a filtered source, fusing adjacent filter.filter if possible
* @param {function(x:*):boolean} p filtering predicate
* @param {{run:function}} source source to filter
* @returns {Filter} filtered source
*/
Filter.create = function create(p, source) {
if (isCanonicalEmpty(source)) {
return source;
}
if (source instanceof Filter) {
return new Filter(and(source.p, p), source.source);
}
return new Filter(p, source);
};
return Filter;
}();
var FilterSink =
/*#__PURE__*/
function (_Pipe) {
inherits(FilterSink, _Pipe);
function FilterSink(p, sink) {
classCallCheck$2(this, FilterSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.p = p;
return _this;
}
FilterSink.prototype.event = function event(t, x) {
var p = this.p;
p(x) && this.sink.event(t, x);
};
return FilterSink;
}(Pipe);
var and = function and(p, q) {
return function (x) {
return p(x) && q(x);
};
};
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var FilterMap =
/*#__PURE__*/
function () {
function FilterMap(p, f, source) {
classCallCheck$2(this, FilterMap);
this.p = p;
this.f = f;
this.source = source;
}
FilterMap.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new FilterMapSink(this.p, this.f, sink), scheduler$$1);
};
return FilterMap;
}();
var FilterMapSink =
/*#__PURE__*/
function (_Pipe) {
inherits(FilterMapSink, _Pipe);
function FilterMapSink(p, f, sink) {
classCallCheck$2(this, FilterMapSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.p = p;
_this.f = f;
return _this;
}
FilterMapSink.prototype.event = function event(t, x) {
var f = this.f;
var p = this.p;
p(x) && this.sink.event(t, f(x));
};
return FilterMapSink;
}(Pipe);
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Map$1 =
/*#__PURE__*/
function () {
function Map(f, source) {
classCallCheck$2(this, Map);
this.f = f;
this.source = source;
}
Map.prototype.run = function run(sink, scheduler$$1) {
// eslint-disable-line no-extend-native
return this.source.run(new MapSink(this.f, sink), scheduler$$1);
};
/**
* Create a mapped source, fusing adjacent map.map, filter.map,
* and filter.map.map if possible
* @param {function(*):*} f mapping function
* @param {{run:function}} source source to map
* @returns {Map|FilterMap} mapped source, possibly fused
*/
Map.create = function create(f, source) {
if (isCanonicalEmpty(source)) {
return empty();
}
if (source instanceof Map) {
return new Map(compose(f, source.f), source.source);
}
if (source instanceof Filter) {
return new FilterMap(source.p, f, source.source);
}
return new Map(f, source);
};
return Map;
}();
var MapSink =
/*#__PURE__*/
function (_Pipe) {
inherits(MapSink, _Pipe);
function MapSink(f, sink) {
classCallCheck$2(this, MapSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.f = f;
return _this;
}
MapSink.prototype.event = function event(t, x) {
var f = this.f;
this.sink.event(t, f(x));
};
return MapSink;
}(Pipe);
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var SettableDisposable =
/*#__PURE__*/
function () {
function SettableDisposable() {
classCallCheck$2(this, SettableDisposable);
this.disposable = undefined;
this.disposed = false;
}
SettableDisposable.prototype.setDisposable = function setDisposable(disposable$$1) {
if (this.disposable !== void 0) {
throw new Error('setDisposable called more than once');
}
this.disposable = disposable$$1;
if (this.disposed) {
disposable$$1.dispose();
}
};
SettableDisposable.prototype.dispose = function dispose$$1() {
if (this.disposed) {
return;
}
this.disposed = true;
if (this.disposable !== void 0) {
this.disposable.dispose();
}
};
return SettableDisposable;
}();
var Slice =
/*#__PURE__*/
function () {
function Slice(bounds, source) {
classCallCheck$2(this, Slice);
this.source = source;
this.bounds = bounds;
}
Slice.prototype.run = function run(sink, scheduler$$1) {
var disposable$$1 = new SettableDisposable();
var sliceSink = new SliceSink(this.bounds.min, this.bounds.max - this.bounds.min, sink, disposable$$1);
disposable$$1.setDisposable(this.source.run(sliceSink, scheduler$$1));
return disposable$$1;
};
return Slice;
}();
var SliceSink =
/*#__PURE__*/
function (_Pipe) {
inherits(SliceSink, _Pipe);
function SliceSink(skip, take, sink, disposable$$1) {
classCallCheck$2(this, SliceSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.skip = skip;
_this.take = take;
_this.disposable = disposable$$1;
return _this;
}
SliceSink.prototype.event = function event(t, x) {
/* eslint complexity: [1, 4] */
if (this.skip > 0) {
this.skip -= 1;
return;
}
if (this.take === 0) {
return;
}
this.take -= 1;
this.sink.event(t, x);
if (this.take === 0) {
this.disposable.dispose();
this.sink.end(t);
}
};
return SliceSink;
}(Pipe);
var TakeWhile =
/*#__PURE__*/
function () {
function TakeWhile(p, source) {
classCallCheck$2(this, TakeWhile);
this.p = p;
this.source = source;
}
TakeWhile.prototype.run = function run(sink, scheduler$$1) {
var disposable$$1 = new SettableDisposable();
var takeWhileSink = new TakeWhileSink(this.p, sink, disposable$$1);
disposable$$1.setDisposable(this.source.run(takeWhileSink, scheduler$$1));
return disposable$$1;
};
return TakeWhile;
}();
var TakeWhileSink =
/*#__PURE__*/
function (_Pipe2) {
inherits(TakeWhileSink, _Pipe2);
function TakeWhileSink(p, sink, disposable$$1) {
classCallCheck$2(this, TakeWhileSink);
var _this2 = possibleConstructorReturn(this, _Pipe2.call(this, sink));
_this2.p = p;
_this2.active = true;
_this2.disposable = disposable$$1;
return _this2;
}
TakeWhileSink.prototype.event = function event(t, x) {
if (!this.active) {
return;
}
var p = this.p;
this.active = p(x);
if (this.active) {
this.sink.event(t, x);
} else {
this.disposable.dispose();
this.sink.end(t);
}
};
return TakeWhileSink;
}(Pipe);
var SkipWhile =
/*#__PURE__*/
function () {
function SkipWhile(p, source) {
classCallCheck$2(this, SkipWhile);
this.p = p;
this.source = source;
}
SkipWhile.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new SkipWhileSink(this.p, sink), scheduler$$1);
};
return SkipWhile;
}();
var SkipWhileSink =
/*#__PURE__*/
function (_Pipe3) {
inherits(SkipWhileSink, _Pipe3);
function SkipWhileSink(p, sink) {
classCallCheck$2(this, SkipWhileSink);
var _this3 = possibleConstructorReturn(this, _Pipe3.call(this, sink));
_this3.p = p;
_this3.skipping = true;
return _this3;
}
SkipWhileSink.prototype.event = function event(t, x) {
if (this.skipping) {
var p = this.p;
this.skipping = p(x);
if (this.skipping) {
return;
}
}
this.sink.event(t, x);
};
return SkipWhileSink;
}(Pipe);
var SkipAfter =
/*#__PURE__*/
function () {
function SkipAfter(p, source) {
classCallCheck$2(this, SkipAfter);
this.p = p;
this.source = source;
}
SkipAfter.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new SkipAfterSink(this.p, sink), scheduler$$1);
};
return SkipAfter;
}();
var SkipAfterSink =
/*#__PURE__*/
function (_Pipe4) {
inherits(SkipAfterSink, _Pipe4);
function SkipAfterSink(p, sink) {
classCallCheck$2(this, SkipAfterSink);
var _this4 = possibleConstructorReturn(this, _Pipe4.call(this, sink));
_this4.p = p;
_this4.skipping = false;
return _this4;
}
SkipAfterSink.prototype.event = function event(t, x) {
if (this.skipping) {
return;
}
var p = this.p;
this.skipping = p(x);
this.sink.event(t, x);
if (this.skipping) {
this.sink.end(t);
}
};
return SkipAfterSink;
}(Pipe);
var ZipItems =
/*#__PURE__*/
function () {
function ZipItems(f, items, source) {
classCallCheck$2(this, ZipItems);
this.f = f;
this.items = items;
this.source = source;
}
ZipItems.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new ZipItemsSink(this.f, this.items, sink), scheduler$$1);
};
return ZipItems;
}();
var ZipItemsSink =
/*#__PURE__*/
function (_Pipe) {
inherits(ZipItemsSink, _Pipe);
function ZipItemsSink(f, items, sink) {
classCallCheck$2(this, ZipItemsSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.f = f;
_this.items = items;
_this.index = 0;
return _this;
}
ZipItemsSink.prototype.event = function event(t, b) {
var f = this.f;
this.sink.event(t, f(this.items[this.index], b));
this.index += 1;
};
return ZipItemsSink;
}(Pipe);
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var runEffects$1 =
/*#__PURE__*/
curry2(function (stream, scheduler$$1) {
return new Promise(function (resolve, reject) {
return runStream(stream, scheduler$$1, resolve, reject);
});
});
function runStream(stream, scheduler$$1, resolve, reject) {
var disposable$$1 = new SettableDisposable();
var observer = new RunEffectsSink(resolve, reject, disposable$$1);
disposable$$1.setDisposable(stream.run(observer, scheduler$$1));
}
var RunEffectsSink =
/*#__PURE__*/
function () {
function RunEffectsSink(end, error, disposable$$1) {
classCallCheck$2(this, RunEffectsSink);
this._end = end;
this._error = error;
this._disposable = disposable$$1;
this.active = true;
}
RunEffectsSink.prototype.event = function event(t, x) {};
RunEffectsSink.prototype.end = function end(t) {
if (!this.active) {
return;
}
this._dispose(this._error, this._end, undefined);
};
RunEffectsSink.prototype.error = function error(t, e) {
this._dispose(this._error, this._error, e);
};
RunEffectsSink.prototype._dispose = function _dispose(error, end, x) {
this.active = false;
tryDispose$1(error, end, x, this._disposable);
};
return RunEffectsSink;
}();
function tryDispose$1(error, end, x, disposable$$1) {
try {
disposable$$1.dispose();
} catch (e) {
error(e);
return;
}
end(x);
}
/** @license MIT License (c) copyright 2010-2017 original author or authors */
// Run a Stream, sending all its events to the
// provided Sink.
var run$1 = function run(sink, scheduler$$1, stream) {
return stream.run(sink, scheduler$$1);
};
var RelativeSink =
/*#__PURE__*/
function () {
function RelativeSink(offset, sink) {
classCallCheck$2(this, RelativeSink);
this.sink = sink;
this.offset = offset;
}
RelativeSink.prototype.event = function event(t, x) {
this.sink.event(t + this.offset, x);
};
RelativeSink.prototype.error = function error(t, e) {
this.sink.error(t + this.offset, e);
};
RelativeSink.prototype.end = function end(t) {
this.sink.end(t + this.offset);
};
return RelativeSink;
}(); // Create a stream with its own local clock
// This transforms time from the provided scheduler's clock to a stream-local
// clock (which starts at 0), and then *back* to the scheduler's clock before
// propagating events to sink. In other words, upstream sources will see local times,
// and downstream sinks will see non-local (original) times.
var withLocalTime$1 = function withLocalTime(origin, stream) {
return new WithLocalTime(origin, stream);
};
var WithLocalTime =
/*#__PURE__*/
function () {
function WithLocalTime(origin, source) {
classCallCheck$2(this, WithLocalTime);
this.origin = origin;
this.source = source;
}
WithLocalTime.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(relativeSink(this.origin, sink), schedulerRelativeTo(this.origin, scheduler$$1));
};
return WithLocalTime;
}(); // Accumulate offsets instead of nesting RelativeSinks, which can happen
// with higher-order stream and combinators like continueWith when they're
// applied recursively.
var relativeSink = function relativeSink(origin, sink) {
return sink instanceof RelativeSink ? new RelativeSink(origin + sink.offset, sink.sink) : new RelativeSink(origin, sink);
};
var Loop =
/*#__PURE__*/
function () {
function Loop(stepper, seed, source) {
classCallCheck$2(this, Loop);
this.step = stepper;
this.seed = seed;
this.source = source;
}
Loop.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new LoopSink(this.step, this.seed, sink), scheduler$$1);
};
return Loop;
}();
var LoopSink =
/*#__PURE__*/
function (_Pipe) {
inherits(LoopSink, _Pipe);
function LoopSink(stepper, seed, sink) {
classCallCheck$2(this, LoopSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.step = stepper;
_this.seed = seed;
return _this;
}
LoopSink.prototype.event = function event(t, x) {
var result = this.step(this.seed, x);
this.seed = result.seed;
this.sink.event(t, result.value);
};
return LoopSink;
}(Pipe);
var Scan =
/*#__PURE__*/
function () {
function Scan(f, z, source) {
classCallCheck$2(this, Scan);
this.source = source;
this.f = f;
this.value = z;
}
Scan.prototype.run = function run(sink, scheduler$$1) {
var d1 = asap(propagateEventTask$1(this.value, sink), scheduler$$1);
var d2 = this.source.run(new ScanSink(this.f, this.value, sink), scheduler$$1);
return disposeBoth(d1, d2);
};
return Scan;
}();
var ScanSink =
/*#__PURE__*/
function (_Pipe) {
inherits(ScanSink, _Pipe);
function ScanSink(f, z, sink) {
classCallCheck$2(this, ScanSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.f = f;
_this.value = z;
return _this;
}
ScanSink.prototype.event = function event(t, x) {
var f = this.f;
this.value = f(this.value, x);
this.sink.event(t, this.value);
};
return ScanSink;
}(Pipe);
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var continueWith$1 = function continueWith(f, stream) {
return new ContinueWith(f, stream);
};
var ContinueWith =
/*#__PURE__*/
function () {
function ContinueWith(f, source) {
classCallCheck$2(this, ContinueWith);
this.f = f;
this.source = source;
}
ContinueWith.prototype.run = function run(sink, scheduler$$1) {
return new ContinueWithSink(this.f, this.source, sink, scheduler$$1);
};
return ContinueWith;
}();
var ContinueWithSink =
/*#__PURE__*/
function (_Pipe) {
inherits(ContinueWithSink, _Pipe);
function ContinueWithSink(f, source, sink, scheduler$$1) {
classCallCheck$2(this, ContinueWithSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.f = f;
_this.scheduler = scheduler$$1;
_this.active = true;
_this.disposable = disposeOnce(source.run(_this, scheduler$$1));
return _this;
}
ContinueWithSink.prototype.event = function event(t, x) {
if (!this.active) {
return;
}
this.sink.event(t, x);
};
ContinueWithSink.prototype.end = function end(t) {
if (!this.active) {
return;
}
tryDispose(t, this.disposable, this.sink);
this._startNext(t, this.sink);
};
ContinueWithSink.prototype._startNext = function _startNext(t, sink) {
try {
this.disposable = this._continue(this.f, t, sink);
} catch (e) {
sink.error(t, e);
}
};
ContinueWithSink.prototype._continue = function _continue(f, t, sink) {
return run$1(sink, this.scheduler, withLocalTime$1(t, f()));
};
ContinueWithSink.prototype.dispose = function dispose$$1() {
this.active = false;
return this.disposable.dispose();
};
return ContinueWithSink;
}(Pipe);
/** @license MIT License (c) copyright 2010-2017 original author or authors */
var startWith$1 = function startWith(x, stream) {
return continueWith$1(function () {
return stream;
}, now(x));
};
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
/**
* Transform each value in the stream by applying f to each
* @param {function(*):*} f mapping function
* @param {Stream} stream stream to map
* @returns {Stream} stream containing items transformed by f
*/
var map$2 = function map$$1(f, stream) {
return Map$1.create(f, stream);
};
/**
* Perform a side effect for each item in the stream
* @param {function(x:*):*} f side effect to execute for each item. The
* return value will be discarded.
* @param {Stream} stream stream to tap
* @returns {Stream} new stream containing the same items as this stream
*/
var tap$1 = function tap(f, stream) {
return new Tap(f, stream);
};
var Tap =
/*#__PURE__*/
function () {
function Tap(f, source) {
classCallCheck$2(this, Tap);
this.source = source;
this.f = f;
}
Tap.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new TapSink(this.f, sink), scheduler$$1);
};
return Tap;
}();
var TapSink =
/*#__PURE__*/
function (_Pipe) {
inherits(TapSink, _Pipe);
function TapSink(f, sink) {
classCallCheck$2(this, TapSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.f = f;
return _this;
}
TapSink.prototype.event = function event(t, x) {
var f = this.f;
f(x);
this.sink.event(t, x);
};
return TapSink;
}(Pipe);
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var IndexSink =
/*#__PURE__*/
function (_Sink) {
inherits(IndexSink, _Sink);
function IndexSink(i, sink) {
classCallCheck$2(this, IndexSink);
var _this = possibleConstructorReturn(this, _Sink.call(this, sink));
_this.index = i;
_this.active = true;
_this.value = undefined;
return _this;
}
IndexSink.prototype.event = function event(t, x) {
if (!this.active) {
return;
}
this.value = x;
this.sink.event(t, this);
};
IndexSink.prototype.end = function end(t) {
if (!this.active) {
return;
}
this.active = false;
this.sink.event(t, this);
};
return IndexSink;
}(Pipe);
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
function invoke(f, args) {
/* eslint complexity: [2,7] */
switch (args.length) {
case 0:
return f();
case 1:
return f(args[0]);
case 2:
return f(args[0], args[1]);
case 3:
return f(args[0], args[1], args[2]);
case 4:
return f(args[0], args[1], args[2], args[3]);
case 5:
return f(args[0], args[1], args[2], args[3], args[4]);
default:
return f.apply(void 0, args);
}
}
var Combine =
/*#__PURE__*/
function () {
function Combine(f, sources) {
classCallCheck$2(this, Combine);
this.f = f;
this.sources = sources;
}
Combine.prototype.run = function run(sink, scheduler$$1) {
var l = this.sources.length;
var disposables = new Array(l);
var sinks = new Array(l);
var mergeSink = new CombineSink(disposables, sinks, sink, this.f);
for (var indexSink, i = 0; i < l; ++i) {
indexSink = sinks[i] = new IndexSink(i, mergeSink);
disposables[i] = this.sources[i].run(indexSink, scheduler$$1);
}
return disposeAll(disposables);
};
return Combine;
}();
var CombineSink =
/*#__PURE__*/
function (_Pipe) {
inherits(CombineSink, _Pipe);
function CombineSink(disposables, sinks, sink, f) {
classCallCheck$2(this, CombineSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.disposables = disposables;
_this.sinks = sinks;
_this.f = f;
var l = sinks.length;
_this.awaiting = l;
_this.values = new Array(l);
_this.hasValue = new Array(l).fill(false);
_this.activeCount = sinks.length;
return _this;
}
CombineSink.prototype.event = function event(t, indexedValue) {
if (!indexedValue.active) {
this._dispose(t, indexedValue.index);
return;
}
var i = indexedValue.index;
var awaiting = this._updateReady(i);
this.values[i] = indexedValue.value;
if (awaiting === 0) {
this.sink.event(t, invoke(this.f, this.values));
}
};
CombineSink.prototype._updateReady = function _updateReady(index) {
if (this.awaiting > 0) {
if (!this.hasValue[index]) {
this.hasValue[index] = true;
this.awaiting -= 1;
}
}
return this.awaiting;
};
CombineSink.prototype._dispose = function _dispose(t, index) {
tryDispose(t, this.disposables[index], this.sink);
if (--this.activeCount === 0) {
this.sink.end(t);
}
};
return CombineSink;
}(Pipe);
/** @license MIT License (c) copyright 2010 original author or authors */
/**
* Doubly linked list
* @constructor
*/
var LinkedList =
/*#__PURE__*/
function () {
function LinkedList() {
classCallCheck$2(this, LinkedList);
this.head = null;
this.length = 0;
}
/**
* Add a node to the end of the list
* @param {{prev:Object|null, next:Object|null, dispose:function}} x node to add
*/
LinkedList.prototype.add = function add(x) {
if (this.head !== null) {
this.head.prev = x;
x.next = this.head;
}
this.head = x;
++this.length;
};
/**
* Remove the provided node from the list
* @param {{prev:Object|null, next:Object|null, dispose:function}} x node to remove
*/
LinkedList.prototype.remove = function remove$$1(x) {
// eslint-disable-line complexity
--this.length;
if (x === this.head) {
this.head = this.head.next;
}
if (x.next !== null) {
x.next.prev = x.prev;
x.next = null;
}
if (x.prev !== null) {
x.prev.next = x.next;
x.prev = null;
}
};
/**
* @returns {boolean} true iff there are no nodes in the list
*/
LinkedList.prototype.isEmpty = function isEmpty() {
return this.length === 0;
};
/**
* Dispose all nodes
* @returns {void}
*/
LinkedList.prototype.dispose = function dispose$$1() {
if (this.isEmpty()) {
return;
}
var head = this.head;
this.head = null;
this.length = 0;
while (head !== null) {
head.dispose();
head = head.next;
}
};
return LinkedList;
}();
var MergeConcurrently =
/*#__PURE__*/
function () {
function MergeConcurrently(f, concurrency, source) {
classCallCheck$2(this, MergeConcurrently);
this.f = f;
this.concurrency = concurrency;
this.source = source;
}
MergeConcurrently.prototype.run = function run(sink, scheduler$$1) {
return new Outer(this.f, this.concurrency, this.source, sink, scheduler$$1);
};
return MergeConcurrently;
}();
var Outer =
/*#__PURE__*/
function () {
function Outer(f, concurrency, source, sink, scheduler$$1) {
classCallCheck$2(this, Outer);
this.f = f;
this.concurrency = concurrency;
this.sink = sink;
this.scheduler = scheduler$$1;
this.pending = [];
this.current = new LinkedList();
this.disposable = disposeOnce(source.run(this, scheduler$$1));
this.active = true;
}
Outer.prototype.event = function event(t, x) {
this._addInner(t, x);
};
Outer.prototype._addInner = function _addInner(t, x) {
if (this.current.length < this.concurrency) {
this._startInner(t, x);
} else {
this.pending.push(x);
}
};
Outer.prototype._startInner = function _startInner(t, x) {
try {
this._initInner(t, x);
} catch (e) {
this.error(t, e);
}
};
Outer.prototype._initInner = function _initInner(t, x) {
var innerSink = new Inner(t, this, this.sink);
innerSink.disposable = mapAndRun(this.f, t, x, innerSink, this.scheduler);
this.current.add(innerSink);
};
Outer.prototype.end = function end(t) {
this.active = false;
tryDispose(t, this.disposable, this.sink);
this._checkEnd(t);
};
Outer.prototype.error = function error(t, e) {
this.active = false;
this.sink.error(t, e);
};
Outer.prototype.dispose = function dispose$$1() {
this.active = false;
this.pending.length = 0;
this.disposable.dispose();
this.current.dispose();
};
Outer.prototype._endInner = function _endInner(t, inner) {
this.current.remove(inner);
tryDispose(t, inner, this);
if (this.pending.length === 0) {
this._checkEnd(t);
} else {
this._startInner(t, this.pending.shift());
}
};
Outer.prototype._checkEnd = function _checkEnd(t) {
if (!this.active && this.current.isEmpty()) {
this.sink.end(t);
}
};
return Outer;
}();
var mapAndRun = function mapAndRun(f, t, x, sink, scheduler$$1) {
return f(x).run(sink, schedulerRelativeTo(t, scheduler$$1));
};
var Inner =
/*#__PURE__*/
function () {
function Inner(time, outer, sink) {
classCallCheck$2(this, Inner);
this.prev = this.next = null;
this.time = time;
this.outer = outer;
this.sink = sink;
this.disposable = void 0;
}
Inner.prototype.event = function event(t, x) {
this.sink.event(t + this.time, x);
};
Inner.prototype.end = function end(t) {
this.outer._endInner(t + this.time, this);
};
Inner.prototype.error = function error(t, e) {
this.outer.error(t + this.time, e);
};
Inner.prototype.dispose = function dispose$$1() {
return this.disposable.dispose();
};
return Inner;
}();
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
/**
* @returns {Stream} stream containing events from two streams in time order.
* If two events are simultaneous they will be merged in arbitrary order.
*/
function merge$1(stream1, stream2) {
return mergeArray([stream1, stream2]);
}
/**
* @param {Array} streams array of stream to merge
* @returns {Stream} stream containing events from all input observables
* in time order. If two events are simultaneous they will be merged in
* arbitrary order.
*/
var mergeArray = function mergeArray(streams) {
return mergeStreams(withoutCanonicalEmpty(streams));
};
/**
* This implements fusion/flattening for merge. It will
* fuse adjacent merge operations. For example:
* - a.merge(b).merge(c) effectively becomes merge(a, b, c)
* - merge(a, merge(b, c)) effectively becomes merge(a, b, c)
* It does this by concatenating the sources arrays of
* any nested Merge sources, in effect "flattening" nested
* merge operations into a single merge.
*/
var mergeStreams = function mergeStreams(streams) {
return streams.length === 0 ? empty() : streams.length === 1 ? streams[0] : new Merge(reduce(appendSources, [], streams));
};
var withoutCanonicalEmpty = function withoutCanonicalEmpty(streams) {
return streams.filter(isNotCanonicalEmpty);
};
var isNotCanonicalEmpty = function isNotCanonicalEmpty(stream) {
return !isCanonicalEmpty(stream);
};
var appendSources = function appendSources(sources, stream) {
return sources.concat(stream instanceof Merge ? stream.sources : stream);
};
var Merge =
/*#__PURE__*/
function () {
function Merge(sources) {
classCallCheck$2(this, Merge);
this.sources = sources;
}
Merge.prototype.run = function run(sink, scheduler$$1) {
var l = this.sources.length;
var disposables = new Array(l);
var sinks = new Array(l);
var mergeSink = new MergeSink(disposables, sinks, sink);
for (var indexSink, i = 0; i < l; ++i) {
indexSink = sinks[i] = new IndexSink(i, mergeSink);
disposables[i] = this.sources[i].run(indexSink, scheduler$$1);
}
return disposeAll(disposables);
};
return Merge;
}();
var MergeSink =
/*#__PURE__*/
function (_Pipe) {
inherits(MergeSink, _Pipe);
function MergeSink(disposables, sinks, sink) {
classCallCheck$2(this, MergeSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.disposables = disposables;
_this.activeCount = sinks.length;
return _this;
}
MergeSink.prototype.event = function event(t, indexValue) {
if (!indexValue.active) {
this._dispose(t, indexValue.index);
return;
}
this.sink.event(t, indexValue.value);
};
MergeSink.prototype._dispose = function _dispose(t, index) {
tryDispose(t, this.disposables[index], this.sink);
if (--this.activeCount === 0) {
this.sink.end(t);
}
};
return MergeSink;
}(Pipe);
var Snapshot =
/*#__PURE__*/
function () {
function Snapshot(f, values, sampler) {
classCallCheck$2(this, Snapshot);
this.f = f;
this.values = values;
this.sampler = sampler;
}
Snapshot.prototype.run = function run(sink, scheduler$$1) {
var sampleSink = new SnapshotSink(this.f, sink);
var valuesDisposable = this.values.run(sampleSink.latest, scheduler$$1);
var samplerDisposable = this.sampler.run(sampleSink, scheduler$$1);
return disposeBoth(samplerDisposable, valuesDisposable);
};
return Snapshot;
}();
var SnapshotSink =
/*#__PURE__*/
function (_Pipe) {
inherits(SnapshotSink, _Pipe);
function SnapshotSink(f, sink) {
classCallCheck$2(this, SnapshotSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.f = f;
_this.latest = new LatestValueSink(_this);
return _this;
}
SnapshotSink.prototype.event = function event(t, x) {
if (this.latest.hasValue) {
var f = this.f;
this.sink.event(t, f(this.latest.value, x));
}
};
return SnapshotSink;
}(Pipe);
var LatestValueSink =
/*#__PURE__*/
function (_Pipe2) {
inherits(LatestValueSink, _Pipe2);
function LatestValueSink(sink) {
classCallCheck$2(this, LatestValueSink);
var _this2 = possibleConstructorReturn(this, _Pipe2.call(this, sink));
_this2.hasValue = false;
return _this2;
}
LatestValueSink.prototype.event = function event(t, x) {
this.value = x;
this.hasValue = true;
};
LatestValueSink.prototype.end = function end() {};
return LatestValueSink;
}(Pipe); // Copied and modified from https://github.com/invertase/denque
// MIT License
// These constants were extracted directly from denque's shift()
// It's not clear exactly why the authors chose these particular
// values, but given denque's stated goals, it seems likely that
// they were chosen for speed/memory reasons.
// Max value of _head at which Queue is willing to shink
// its internal array
var HEAD_MAX_SHRINK = 2; // Min value of _tail at which Queue is willing to shink
// its internal array
var TAIL_MIN_SHRINK = 10000;
var Queue =
/*#__PURE__*/
function () {
function Queue() {
classCallCheck$2(this, Queue);
this._head = 0;
this._tail = 0;
this._capacityMask = 0x3;
this._list = new Array(4);
}
Queue.prototype.push = function push(x) {
var tail$$1 = this._tail;
this._list[tail$$1] = x;
this._tail = tail$$1 + 1 & this._capacityMask;
if (this._tail === this._head) {
this._growArray();
}
if (this._head < this._tail) {
return this._tail - this._head;
} else {
return this._capacityMask + 1 - (this._head - this._tail);
}
};
Queue.prototype.shift = function shift() {
var head = this._head;
if (head === this._tail) {
return undefined;
}
var x = this._list[head];
this._list[head] = undefined;
this._head = head + 1 & this._capacityMask;
if (head < HEAD_MAX_SHRINK && this._tail > TAIL_MIN_SHRINK && this._tail <= this._list.length >>> 2) {
this._shrinkArray();
}
return x;
};
Queue.prototype.isEmpty = function isEmpty() {
return this._head === this._tail;
};
Queue.prototype.length = function length() {
if (this._head === this._tail) {
return 0;
} else if (this._head < this._tail) {
return this._tail - this._head;
} else {
return this._capacityMask + 1 - (this._head - this._tail);
}
};
Queue.prototype._growArray = function _growArray() {
if (this._head) {
// copy existing data, head to end, then beginning to tail.
this._list = this._copyArray();
this._head = 0;
} // head is at 0 and array is now full, safe to extend
this._tail = this._list.length;
this._list.length *= 2;
this._capacityMask = this._capacityMask << 1 | 1;
};
Queue.prototype._shrinkArray = function _shrinkArray() {
this._list.length >>>= 1;
this._capacityMask >>>= 1;
};
Queue.prototype._copyArray = function _copyArray() {
var newArray = [];
var list = this._list;
var len = list.length;
var i = void 0;
for (i = this._head; i < len; i++) {
newArray.push(list[i]);
}
for (i = 0; i < this._tail; i++) {
newArray.push(list[i]);
}
return newArray;
};
return Queue;
}();
var Zip =
/*#__PURE__*/
function () {
function Zip(f, sources) {
classCallCheck$2(this, Zip);
this.f = f;
this.sources = sources;
}
Zip.prototype.run = function run(sink, scheduler$$1) {
var l = this.sources.length;
var disposables = new Array(l);
var sinks = new Array(l);
var buffers = new Array(l);
var zipSink = new ZipSink(this.f, buffers, sinks, sink);
for (var indexSink, i = 0; i < l; ++i) {
buffers[i] = new Queue();
indexSink = sinks[i] = new IndexSink(i, zipSink);
disposables[i] = this.sources[i].run(indexSink, scheduler$$1);
}
return disposeAll(disposables);
};
return Zip;
}();
var ZipSink =
/*#__PURE__*/
function (_Pipe) {
inherits(ZipSink, _Pipe);
function ZipSink(f, buffers, sinks, sink) {
classCallCheck$2(this, ZipSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.f = f;
_this.sinks = sinks;
_this.buffers = buffers;
return _this;
}
ZipSink.prototype.event = function event(t, indexedValue) {
/* eslint complexity: [1, 5] */
if (!indexedValue.active) {
this._dispose(t, indexedValue.index);
return;
}
var buffers = this.buffers;
var buffer = buffers[indexedValue.index];
buffer.push(indexedValue.value);
if (buffer.length() === 1) {
if (!ready(this.buffers)) {
return;
}
emitZipped(this.f, t, buffers, this.sink);
if (ended(this.buffers, this.sinks)) {
this.sink.end(t);
}
}
};
ZipSink.prototype._dispose = function _dispose(t, index) {
var buffer = this.buffers[index];
if (buffer.isEmpty()) {
this.sink.end(t);
}
};
return ZipSink;
}(Pipe);
var emitZipped = function emitZipped(f, t, buffers, sink) {
return sink.event(t, invoke(f, map(head, buffers)));
};
var head = function head(buffer) {
return buffer.shift();
};
function ended(buffers, sinks) {
for (var i = 0, l = buffers.length; i < l; ++i) {
if (buffers[i].isEmpty() && !sinks[i].active) {
return true;
}
}
return false;
}
function ready(buffers) {
for (var i = 0, l = buffers.length; i < l; ++i) {
if (buffers[i].isEmpty()) {
return false;
}
}
return true;
}
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
/**
* Given a stream of streams, return a new stream that adopts the behavior
* of the most recent inner stream.
* @param {Stream} stream of streams on which to switch
* @returns {Stream} switching stream
*/
var switchLatest = function switchLatest(stream) {
return isCanonicalEmpty(stream) ? empty() : new Switch(stream);
};
var Switch =
/*#__PURE__*/
function () {
function Switch(source) {
classCallCheck$2(this, Switch);
this.source = source;
}
Switch.prototype.run = function run(sink, scheduler$$1) {
var switchSink = new SwitchSink(sink, scheduler$$1);
return disposeBoth(switchSink, this.source.run(switchSink, scheduler$$1));
};
return Switch;
}();
var SwitchSink =
/*#__PURE__*/
function () {
function SwitchSink(sink, scheduler$$1) {
classCallCheck$2(this, SwitchSink);
this.sink = sink;
this.scheduler = scheduler$$1;
this.current = null;
this.ended = false;
}
SwitchSink.prototype.event = function event(t, stream) {
this._disposeCurrent(t);
this.current = new Segment(stream, t, Infinity, this, this.sink, this.scheduler);
};
SwitchSink.prototype.end = function end(t) {
this.ended = true;
this._checkEnd(t);
};
SwitchSink.prototype.error = function error(t, e) {
this.ended = true;
this.sink.error(t, e);
};
SwitchSink.prototype.dispose = function dispose$$1() {
return this._disposeCurrent(currentTime(this.scheduler));
};
SwitchSink.prototype._disposeCurrent = function _disposeCurrent(t) {
if (this.current !== null) {
return this.current._dispose(t);
}
};
SwitchSink.prototype._disposeInner = function _disposeInner(t, inner) {
inner._dispose(t);
if (inner === this.current) {
this.current = null;
}
};
SwitchSink.prototype._checkEnd = function _checkEnd(t) {
if (this.ended && this.current === null) {
this.sink.end(t);
}
};
SwitchSink.prototype._endInner = function _endInner(t, inner) {
this._disposeInner(t, inner);
this._checkEnd(t);
};
SwitchSink.prototype._errorInner = function _errorInner(t, e, inner) {
this._disposeInner(t, inner);
this.sink.error(t, e);
};
return SwitchSink;
}();
var Segment =
/*#__PURE__*/
function () {
function Segment(source, min, max, outer, sink, scheduler$$1) {
classCallCheck$2(this, Segment);
this.min = min;
this.max = max;
this.outer = outer;
this.sink = sink;
this.disposable = source.run(this, schedulerRelativeTo(min, scheduler$$1));
}
Segment.prototype.event = function event(t, x) {
var time = Math.max(0, t + this.min);
if (time < this.max) {
this.sink.event(time, x);
}
};
Segment.prototype.end = function end(t) {
this.outer._endInner(t + this.min, this);
};
Segment.prototype.error = function error(t, e) {
this.outer._errorInner(t + this.min, e, this);
};
Segment.prototype._dispose = function _dispose(t) {
tryDispose(t + this.min, this.disposable, this.sink);
};
return Segment;
}();
var SkipRepeats =
/*#__PURE__*/
function () {
function SkipRepeats(equals, source) {
classCallCheck$2(this, SkipRepeats);
this.equals = equals;
this.source = source;
}
SkipRepeats.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new SkipRepeatsSink(this.equals, sink), scheduler$$1);
};
return SkipRepeats;
}();
var SkipRepeatsSink =
/*#__PURE__*/
function (_Pipe) {
inherits(SkipRepeatsSink, _Pipe);
function SkipRepeatsSink(equals, sink) {
classCallCheck$2(this, SkipRepeatsSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.equals = equals;
_this.value = void 0;
_this.init = true;
return _this;
}
SkipRepeatsSink.prototype.event = function event(t, x) {
if (this.init) {
this.init = false;
this.value = x;
this.sink.event(t, x);
} else if (!this.equals(this.value, x)) {
this.value = x;
this.sink.event(t, x);
}
};
return SkipRepeatsSink;
}(Pipe);
var Until =
/*#__PURE__*/
function () {
function Until(maxSignal, source) {
classCallCheck$2(this, Until);
this.maxSignal = maxSignal;
this.source = source;
}
Until.prototype.run = function run(sink, scheduler$$1) {
var min = new Bound(-Infinity, sink);
var max = new UpperBound(this.maxSignal, sink, scheduler$$1);
var disposable$$1 = this.source.run(new TimeWindowSink(min, max, sink), scheduler$$1);
return disposeAll([min, max, disposable$$1]);
};
return Until;
}();
var Since =
/*#__PURE__*/
function () {
function Since(minSignal, source) {
classCallCheck$2(this, Since);
this.minSignal = minSignal;
this.source = source;
}
Since.prototype.run = function run(sink, scheduler$$1) {
var min = new LowerBound(this.minSignal, sink, scheduler$$1);
var max = new Bound(Infinity, sink);
var disposable$$1 = this.source.run(new TimeWindowSink(min, max, sink), scheduler$$1);
return disposeAll([min, max, disposable$$1]);
};
return Since;
}();
var Bound =
/*#__PURE__*/
function (_Pipe) {
inherits(Bound, _Pipe);
function Bound(value, sink) {
classCallCheck$2(this, Bound);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.value = value;
return _this;
}
Bound.prototype.event = function event() {};
Bound.prototype.end = function end() {};
Bound.prototype.dispose = function dispose$$1() {};
return Bound;
}(Pipe);
var TimeWindowSink =
/*#__PURE__*/
function (_Pipe2) {
inherits(TimeWindowSink, _Pipe2);
function TimeWindowSink(min, max, sink) {
classCallCheck$2(this, TimeWindowSink);
var _this2 = possibleConstructorReturn(this, _Pipe2.call(this, sink));
_this2.min = min;
_this2.max = max;
return _this2;
}
TimeWindowSink.prototype.event = function event(t, x) {
if (t >= this.min.value && t < this.max.value) {
this.sink.event(t, x);
}
};
return TimeWindowSink;
}(Pipe);
var LowerBound =
/*#__PURE__*/
function (_Pipe3) {
inherits(LowerBound, _Pipe3);
function LowerBound(signal, sink, scheduler$$1) {
classCallCheck$2(this, LowerBound);
var _this3 = possibleConstructorReturn(this, _Pipe3.call(this, sink));
_this3.value = Infinity;
_this3.disposable = signal.run(_this3, scheduler$$1);
return _this3;
}
LowerBound.prototype.event = function event(t
/*, x */
) {
if (t < this.value) {
this.value = t;
}
};
LowerBound.prototype.end = function end() {};
LowerBound.prototype.dispose = function dispose$$1() {
return this.disposable.dispose();
};
return LowerBound;
}(Pipe);
var UpperBound =
/*#__PURE__*/
function (_Pipe4) {
inherits(UpperBound, _Pipe4);
function UpperBound(signal, sink, scheduler$$1) {
classCallCheck$2(this, UpperBound);
var _this4 = possibleConstructorReturn(this, _Pipe4.call(this, sink));
_this4.value = Infinity;
_this4.disposable = signal.run(_this4, scheduler$$1);
return _this4;
}
UpperBound.prototype.event = function event(t, x) {
if (t < this.value) {
this.value = t;
this.sink.end(t);
}
};
UpperBound.prototype.end = function end() {};
UpperBound.prototype.dispose = function dispose$$1() {
return this.disposable.dispose();
};
return UpperBound;
}(Pipe);
var Delay =
/*#__PURE__*/
function () {
function Delay(dt, source) {
classCallCheck$2(this, Delay);
this.dt = dt;
this.source = source;
}
Delay.prototype.run = function run(sink, scheduler$$1) {
var delaySink = new DelaySink(this.dt, sink, scheduler$$1);
return disposeBoth(delaySink, this.source.run(delaySink, scheduler$$1));
};
return Delay;
}();
var DelaySink =
/*#__PURE__*/
function (_Pipe) {
inherits(DelaySink, _Pipe);
function DelaySink(dt, sink, scheduler$$1) {
classCallCheck$2(this, DelaySink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.dt = dt;
_this.scheduler = scheduler$$1;
return _this;
}
DelaySink.prototype.dispose = function dispose$$1() {
var _this2 = this;
cancelAllTasks(function (task) {
return task.sink === _this2.sink;
}, this.scheduler);
};
DelaySink.prototype.event = function event(t, x) {
delay(this.dt, propagateEventTask$1(x, this.sink), this.scheduler);
};
DelaySink.prototype.end = function end(t) {
delay(this.dt, propagateEndTask(this.sink), this.scheduler);
};
return DelaySink;
}(Pipe);
var Throttle =
/*#__PURE__*/
function () {
function Throttle(period, source) {
classCallCheck$2(this, Throttle);
this.period = period;
this.source = source;
}
Throttle.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new ThrottleSink(this.period, sink), scheduler$$1);
};
return Throttle;
}();
var ThrottleSink =
/*#__PURE__*/
function (_Pipe) {
inherits(ThrottleSink, _Pipe);
function ThrottleSink(period, sink) {
classCallCheck$2(this, ThrottleSink);
var _this = possibleConstructorReturn(this, _Pipe.call(this, sink));
_this.time = 0;
_this.period = period;
return _this;
}
ThrottleSink.prototype.event = function event(t, x) {
if (t >= this.time) {
this.time = t + this.period;
this.sink.event(t, x);
}
};
return ThrottleSink;
}(Pipe);
var Debounce =
/*#__PURE__*/
function () {
function Debounce(dt, source) {
classCallCheck$2(this, Debounce);
this.dt = dt;
this.source = source;
}
Debounce.prototype.run = function run(sink, scheduler$$1) {
return new DebounceSink(this.dt, this.source, sink, scheduler$$1);
};
return Debounce;
}();
var DebounceSink =
/*#__PURE__*/
function () {
function DebounceSink(dt, source, sink, scheduler$$1) {
classCallCheck$2(this, DebounceSink);
this.dt = dt;
this.sink = sink;
this.scheduler = scheduler$$1;
this.value = void 0;
this.timer = null;
this.disposable = source.run(this, scheduler$$1);
}
DebounceSink.prototype.event = function event(t, x) {
this._clearTimer();
this.value = x;
this.timer = delay(this.dt, new DebounceTask(this, x), this.scheduler);
};
DebounceSink.prototype._event = function _event(t, x) {
this._clearTimer();
this.sink.event(t, x);
};
DebounceSink.prototype.end = function end(t) {
if (this._clearTimer()) {
this.sink.event(t, this.value);
this.value = undefined;
}
this.sink.end(t);
};
DebounceSink.prototype.error = function error(t, x) {
this._clearTimer();
this.sink.error(t, x);
};
DebounceSink.prototype.dispose = function dispose$$1() {
this._clearTimer();
this.disposable.dispose();
};
DebounceSink.prototype._clearTimer = function _clearTimer() {
if (this.timer === null) {
return false;
}
this.timer.dispose();
this.timer = null;
return true;
};
return DebounceSink;
}();
var DebounceTask =
/*#__PURE__*/
function () {
function DebounceTask(debounce, value) {
classCallCheck$2(this, DebounceTask);
this.debounce = debounce;
this.value = value;
}
DebounceTask.prototype.run = function run(t) {
this.debounce._event(t, this.value);
};
DebounceTask.prototype.error = function error(t, e) {
this.debounce.error(t, e);
};
DebounceTask.prototype.dispose = function dispose$$1() {};
return DebounceTask;
}();
var Await =
/*#__PURE__*/
function () {
function Await(source) {
classCallCheck$2(this, Await);
this.source = source;
}
Await.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(new AwaitSink(sink, scheduler$$1), scheduler$$1);
};
return Await;
}();
var AwaitSink =
/*#__PURE__*/
function () {
function AwaitSink(sink, scheduler$$1) {
var _this = this;
classCallCheck$2(this, AwaitSink);
this.sink = sink;
this.scheduler = scheduler$$1;
this.queue = Promise.resolve(); // Pre-create closures, to avoid creating them per event
this._eventBound = function (x) {
return _this.sink.event(currentTime(_this.scheduler), x);
};
this._endBound = function () {
return _this.sink.end(currentTime(_this.scheduler));
};
this._errorBound = function (e) {
return _this.sink.error(currentTime(_this.scheduler), e);
};
}
AwaitSink.prototype.event = function event(t, promise) {
var _this2 = this;
this.queue = this.queue.then(function () {
return _this2._event(promise);
}).catch(this._errorBound);
};
AwaitSink.prototype.end = function end(t) {
this.queue = this.queue.then(this._endBound).catch(this._errorBound);
};
AwaitSink.prototype.error = function error(t, e) {
var _this3 = this; // Don't resolve error values, propagate directly
this.queue = this.queue.then(function () {
return _this3._errorBound(e);
}).catch(fatalError);
};
AwaitSink.prototype._event = function _event(promise) {
return promise.then(this._eventBound);
};
return AwaitSink;
}();
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var SafeSink =
/*#__PURE__*/
function () {
function SafeSink(sink) {
classCallCheck$2(this, SafeSink);
this.sink = sink;
this.active = true;
}
SafeSink.prototype.event = function event(t, x) {
if (!this.active) {
return;
}
this.sink.event(t, x);
};
SafeSink.prototype.end = function end(t, x) {
if (!this.active) {
return;
}
this.disable();
this.sink.end(t, x);
};
SafeSink.prototype.error = function error(t, e) {
this.disable();
this.sink.error(t, e);
};
SafeSink.prototype.disable = function disable() {
this.active = false;
return this.sink;
};
return SafeSink;
}();
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
function tryEvent(t, x, sink) {
try {
sink.event(t, x);
} catch (e) {
sink.error(t, e);
}
}
function tryEnd(t, sink) {
try {
sink.end(t);
} catch (e) {
sink.error(t, e);
}
}
var ErrorStream =
/*#__PURE__*/
function () {
function ErrorStream(e) {
classCallCheck$2(this, ErrorStream);
this.value = e;
}
ErrorStream.prototype.run = function run(sink, scheduler$$1) {
return asap(propagateErrorTask$1(this.value, sink), scheduler$$1);
};
return ErrorStream;
}();
var RecoverWith =
/*#__PURE__*/
function () {
function RecoverWith(f, source) {
classCallCheck$2(this, RecoverWith);
this.f = f;
this.source = source;
}
RecoverWith.prototype.run = function run(sink, scheduler$$1) {
return new RecoverWithSink(this.f, this.source, sink, scheduler$$1);
};
return RecoverWith;
}();
var RecoverWithSink =
/*#__PURE__*/
function () {
function RecoverWithSink(f, source, sink, scheduler$$1) {
classCallCheck$2(this, RecoverWithSink);
this.f = f;
this.sink = new SafeSink(sink);
this.scheduler = scheduler$$1;
this.disposable = source.run(this, scheduler$$1);
}
RecoverWithSink.prototype.event = function event(t, x) {
tryEvent(t, x, this.sink);
};
RecoverWithSink.prototype.end = function end(t) {
tryEnd(t, this.sink);
};
RecoverWithSink.prototype.error = function error(t, e) {
var nextSink = this.sink.disable();
tryDispose(t, this.disposable, this.sink);
this._startNext(t, e, nextSink);
};
RecoverWithSink.prototype._startNext = function _startNext(t, x, sink) {
try {
this.disposable = this._continue(this.f, t, x, sink);
} catch (e) {
sink.error(t, e);
}
};
RecoverWithSink.prototype._continue = function _continue(f, t, x, sink) {
return run$1(sink, this.scheduler, withLocalTime$1(t, f(x)));
};
RecoverWithSink.prototype.dispose = function dispose$$1() {
return this.disposable.dispose();
};
return RecoverWithSink;
}();
var Multicast =
/*#__PURE__*/
function () {
function Multicast(source) {
classCallCheck$2(this, Multicast);
this.source = new MulticastSource(source);
}
Multicast.prototype.run = function run(sink, scheduler$$1) {
return this.source.run(sink, scheduler$$1);
};
return Multicast;
}();
var MulticastSource =
/*#__PURE__*/
function () {
function MulticastSource(source) {
classCallCheck$2(this, MulticastSource);
this.source = source;
this.sinks = [];
this.disposable = disposeNone();
}
MulticastSource.prototype.run = function run(sink, scheduler$$1) {
var n = this.add(sink);
if (n === 1) {
this.disposable = this.source.run(this, scheduler$$1);
}
return disposeOnce(new MulticastDisposable(this, sink));
};
MulticastSource.prototype.dispose = function dispose$$1() {
var disposable$$1 = this.disposable;
this.disposable = disposeNone();
return disposable$$1.dispose();
};
MulticastSource.prototype.add = function add(sink) {
this.sinks = append(sink, this.sinks);
return this.sinks.length;
};
MulticastSource.prototype.remove = function remove$$1(sink) {
var i = findIndex(sink, this.sinks); // istanbul ignore next
if (i >= 0) {
this.sinks = remove(i, this.sinks);
}
return this.sinks.length;
};
MulticastSource.prototype.event = function event(time, value) {
var s = this.sinks;
if (s.length === 1) {
return s[0].event(time, value);
}
for (var i = 0; i < s.length; ++i) {
tryEvent(time, value, s[i]);
}
};
MulticastSource.prototype.end = function end(time) {
var s = this.sinks;
for (var i = 0; i < s.length; ++i) {
tryEnd(time, s[i]);
}
};
MulticastSource.prototype.error = function error(time, err) {
var s = this.sinks;
for (var i = 0; i < s.length; ++i) {
s[i].error(time, err);
}
};
return MulticastSource;
}();
var MulticastDisposable =
/*#__PURE__*/
function () {
function MulticastDisposable(source, sink) {
classCallCheck$2(this, MulticastDisposable);
this.source = source;
this.sink = sink;
}
MulticastDisposable.prototype.dispose = function dispose$$1() {
if (this.source.remove(this.sink) === 0) {
this.source.dispose();
}
};
return MulticastDisposable;
}();
// Observing
var runEffects$$1 =
/*#__PURE__*/
curry2(runEffects$1);
// Extending
var startWith$$1 =
/*#__PURE__*/
curry2(startWith$1); // -----------------------------------------------------------------------
// Transforming
var map$1 =
/*#__PURE__*/
curry2(map$2);
var tap$$1 =
/*#__PURE__*/
curry2(tap$1);
// Merging
var merge$$1 =
/*#__PURE__*/
curry2(merge$1); // -----------------------------------------------------------------------
var currentTime$1 = function currentTime(scheduler) {
return scheduler.currentTime();
}; // Schedule a task to run as soon as possible, but
/** @license MIT License (c) copyright 2015-2016 original author or authors */
/** @author Brian Cavalier */
// domEvent :: (EventTarget t, Event e) => String -> t -> boolean=false -> Stream e
var domEvent = function domEvent(event, node, capture) {
if (capture === void 0) capture = false;
return new DomEvent(event, node, capture);
};
var mousedown = function mousedown(node, capture) {
if (capture === void 0) capture = false;
return domEvent('mousedown', node, capture);
};
var mouseup = function mouseup(node, capture) {
if (capture === void 0) capture = false;
return domEvent('mouseup', node, capture);
};
var mousemove = function mousemove(node, capture) {
if (capture === void 0) capture = false;
return domEvent('mousemove', node, capture);
};
var DomEvent = function DomEvent(event, node, capture) {
this.event = event;
this.node = node;
this.capture = capture;
};
DomEvent.prototype.run = function run(sink, scheduler$$1) {
var this$1 = this;
var send = function send(e) {
return tryEvent$1(currentTime$1(scheduler$$1), e, sink);
};
var dispose = function dispose() {
return this$1.node.removeEventListener(this$1.event, send, this$1.capture);
};
this.node.addEventListener(this.event, send, this.capture);
return {
dispose: dispose
};
};
function tryEvent$1(t, x, sink) {
try {
sink.event(t, x);
} catch (e) {
sink.error(t, e);
}
}
//
var DROP = 0;
var GRAB = 1;
var DRAG = 2; // The area where we want to do the dragging
var area = document.querySelector('.dragging-area'); // The thing we want to make draggable
var draggable = document.querySelector('.draggable'); // A higher-order stream (stream whose items are themselves streams)
// A mousedown DOM event generates a stream event which is
// a stream of 1 GRAB followed by DRAGs (ie mousemoves).
var makeDraggable = function makeDraggable(area, draggable) {
var drag = map$1(beginDrag(area, draggable), tap$$1(preventDefault, mousedown(draggable))); // A mouseup DOM event generates a stream event which is a
// stream containing a DROP.
var drop = map$1(endDrag(draggable), mouseup(area)); // Merge the drag and drop streams.
// Then use switch() to ensure that the resulting stream behaves
// like the drag stream until an event occurs on the drop stream. Then
// it will behave like the drop stream until the drag stream starts
// producing events again.
// This effectively *toggles behavior* between dragging behavior and
// dropped behavior.
return switchLatest(merge$$1(drag, drop));
};
var preventDefault = function preventDefault(e) {
return e.preventDefault();
};
var beginDrag = function beginDrag(area, draggable) {
return function (e) {
// Memorize click position within the box
var dragOffset = {
dx: e.clientX - draggable.offsetLeft,
dy: e.clientY - draggable.offsetTop
};
return startWith$$1(eventToDragInfo(GRAB, draggable, e), map$1(function (e) {
return eventToDragInfo(DRAG, draggable, e, dragOffset);
}, mousemove(area)));
};
};
var endDrag = function endDrag(draggable) {
return function (e) {
return now(eventToDragInfo(DROP, draggable, e));
};
}; // dragOffset is undefined and unused for actions other than DRAG.
var eventToDragInfo = function eventToDragInfo(action, target, e, dragOffset) {
return {
action: action,
target: target,
x: e.clientX,
y: e.clientY,
offset: dragOffset
};
};
var handleDrag = function handleDrag(dragInfo) {
var el = dragInfo.target;
if (dragInfo.action === GRAB) {
el.classList.add('dragging');
return;
}
if (dragInfo.action === DROP) {
el.classList.remove('dragging');
return;
}
var els = el.style;
els.left = dragInfo.x - dragInfo.offset.dx + 'px';
els.top = dragInfo.y - dragInfo.offset.dy + 'px';
};
runEffects$$1(tap$$1(handleDrag, makeDraggable(area, draggable)), newDefaultScheduler());
}());
//# sourceMappingURL=app.js.map
|
'use strict'
var la = require('lazy-ass')
var check = require('check-more-types')
var log = require('debug')('next-update')
require('console.json')
var print = require('./print-modules-table')
var stats = require('./stats')
var clc = require('cli-color')
var getSuccess = stats.getSuccessStats
var q = require('q')
function ignore () {}
function reportAvailable (available, currentVersions, options) {
la(check.array(available), 'expect an array of info objects', available)
if (!available.length) {
console.log('nothing new is available')
return []
}
log('report available')
log(available)
log('current versions')
log(JSON.stringify(currentVersions))
la(check.maybe.object(currentVersions),
'expected current versions as an object, but was', currentVersions)
function getCurrentVersion (name) {
la(check.unemptyString(name), 'missing name')
if (!currentVersions) {
return
}
if (check.string(currentVersions[name])) {
return currentVersions[name]
}
if (check.object(currentVersions[name])) {
la(check.string(currentVersions[name].version),
'missing version for', name, 'in', currentVersions)
return currentVersions[name].version
}
}
var chain = q()
var updateStats = {}
available.forEach(function (info) {
la(check.unemptyString(info.name), 'missing module name', info)
la(check.array(info.versions), 'missing module versions', info)
var currentVersion = getCurrentVersion(info.name)
log('version for', info.name, currentVersion)
if (currentVersion) {
la(check.unemptyString(currentVersion),
'missing version', currentVersion, 'for', info.name)
updateStats[info.name] = {
name: info.name,
from: currentVersion
}
}
if (info.versions.length === 1) {
if (currentVersion) {
chain = chain.then(function () {
return getSuccess({
name: info.name,
from: currentVersion,
to: info.versions[0]
}).then(function (stats) {
updateStats[info.name] = stats
}).catch(ignore)
})
}
}
})
return chain.then(function () {
var modules = []
available.forEach(function (info) {
la(check.unemptyString(info.name), 'missing module name', info)
la(check.array(info.versions), 'missing module versions', info)
var sep = ', '
var versions
if (info.versions.length < 5) {
versions = info.versions.join(sep)
} else {
versions = info.versions.slice(0, 2)
.concat('...')
.concat(info.versions.slice(info.versions.length - 2))
.join(sep)
}
var stats = updateStats[info.name]
if (!stats) {
return
}
la(check.object(stats), 'could not get stats for', info.name,
'all', updateStats, 'available stats', info)
modules.push({
name: info.name,
version: versions,
from: stats.from,
stats: stats
})
})
console.log('\navailable updates:')
if (modules.length) {
print(modules, options)
console.log('update stats from', clc.underline(stats.url))
} else {
console.log(available)
console.log('no stats is available yet for these updates')
}
return available
})
}
module.exports = reportAvailable
|
import * as types from '../constants/actionTypes';
import fetch from '../core/fetch';
function updateRankings(rankings) {
return {
type: types.UPDATE_FANTASY_FOOTBALL_RANKINGS,
rankingsList: rankings
}
}
export function getRankings() {
let url = '/api/fantasy-football-rankings'
return async (dispatch, getState) => {
const state = getState()
const rankings = state.fantasyFootballRankings || {}
const emptyRankings = Object.keys(rankings).length === 0
if (!emptyRankings) {
Promise.resolve()
}
try {
const resp = await fetch(url)
const data = await resp.json()
dispatch(updateRankings(data))
} catch (error) {
console.log('get fantasy football rankings error : ', error)
}
}
}
|
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['../nodejs/jasmine-custom-message.spec.js']
}; |
/*!
* OOUI v0.40.4
* https://www.mediawiki.org/wiki/OOUI
*
* Copyright 2011–2020 OOUI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2020-10-07T21:25:50Z
*/
( function ( OO ) {
'use strict';
/**
* Toolbars are complex interface components that permit users to easily access a variety
* of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional
* commands that are part of the toolbar, but not configured as tools.
*
* Individual tools are customized and then registered with a
* {@link OO.ui.ToolFactory tool factory}, which creates the tools on demand. Each tool has a
* symbolic name (used when registering the tool), a title (e.g., ‘Insert image’), and an icon.
*
* Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be
* {@link OO.ui.MenuToolGroup menus} of tools, {@link OO.ui.ListToolGroup lists} of tools, or a
* single {@link OO.ui.BarToolGroup bar} of tools. The arrangement and order of the toolgroups is
* customized when the toolbar is set up. Tools can be presented in any order, but each can only
* appear once in the toolbar.
*
* The toolbar can be synchronized with the state of the external "application", like a text
* editor's editing area, marking tools as active/inactive (e.g. a 'bold' tool would be shown as
* active when the text cursor was inside bolded text) or enabled/disabled (e.g. a table caption
* tool would be disabled while the user is not editing a table). A state change is signalled by
* emitting the {@link #event-updateState 'updateState' event}, which calls Tools'
* {@link OO.ui.Tool#onUpdateState onUpdateState method}.
*
* The following is an example of a basic toolbar.
*
* @example
* // Example of a toolbar
* // Create the toolbar
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // We will be placing status text in this element when tools are used
* var $area = $( '<p>' ).text( 'Toolbar example' );
*
* // Define the tools that we're going to place in our toolbar
*
* // Create a class inheriting from OO.ui.Tool
* function SearchTool() {
* SearchTool.super.apply( this, arguments );
* }
* OO.inheritClass( SearchTool, OO.ui.Tool );
* // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
* // of 'icon' and 'title' (displayed icon and text).
* SearchTool.static.name = 'search';
* SearchTool.static.icon = 'search';
* SearchTool.static.title = 'Search...';
* // Defines the action that will happen when this tool is selected (clicked).
* SearchTool.prototype.onSelect = function () {
* $area.text( 'Search tool clicked!' );
* // Never display this tool as "active" (selected).
* this.setActive( false );
* };
* SearchTool.prototype.onUpdateState = function () {};
* // Make this tool available in our toolFactory and thus our toolbar
* toolFactory.register( SearchTool );
*
* // Register two more tools, nothing interesting here
* function SettingsTool() {
* SettingsTool.super.apply( this, arguments );
* }
* OO.inheritClass( SettingsTool, OO.ui.Tool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.icon = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.prototype.onSelect = function () {
* $area.text( 'Settings tool clicked!' );
* this.setActive( false );
* };
* SettingsTool.prototype.onUpdateState = function () {};
* toolFactory.register( SettingsTool );
*
* // Register two more tools, nothing interesting here
* function StuffTool() {
* StuffTool.super.apply( this, arguments );
* }
* OO.inheritClass( StuffTool, OO.ui.Tool );
* StuffTool.static.name = 'stuff';
* StuffTool.static.icon = 'ellipsis';
* StuffTool.static.title = 'More stuff';
* StuffTool.prototype.onSelect = function () {
* $area.text( 'More stuff tool clicked!' );
* this.setActive( false );
* };
* StuffTool.prototype.onUpdateState = function () {};
* toolFactory.register( StuffTool );
*
* // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
* // little popup window (a PopupWidget).
* function HelpTool( toolGroup, config ) {
* OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
* padded: true,
* label: 'Help',
* head: true
* } }, config ) );
* this.popup.$body.append( '<p>I am helpful!</p>' );
* }
* OO.inheritClass( HelpTool, OO.ui.PopupTool );
* HelpTool.static.name = 'help';
* HelpTool.static.icon = 'help';
* HelpTool.static.title = 'Help';
* toolFactory.register( HelpTool );
*
* // Finally define which tools and in what order appear in the toolbar. Each tool may only be
* // used once (but not all defined tools must be used).
* toolbar.setup( [
* {
* // 'bar' tool groups display tools' icons only, side-by-side.
* type: 'bar',
* include: [ 'search', 'help' ]
* },
* {
* // 'list' tool groups display both the titles and icons, in a dropdown list.
* type: 'list',
* indicator: 'down',
* label: 'More',
* include: [ 'settings', 'stuff' ]
* }
* // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
* // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
* // since it's more complicated to use. (See the next example snippet on this page.)
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* var contentFrame = new OO.ui.PanelLayout( {
* expanded: false,
* padded: true
* } );
* frame.$element.append(
* toolbar.$element,
* contentFrame.$element.append( $area )
* );
* $( document.body ).append( frame.$element );
*
* // Here is where the toolbar is actually built. This must be done after inserting it into the
* // document.
* toolbar.initialize();
* toolbar.emit( 'updateState' );
*
* The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
* {@link #event-updateState 'updateState' event}.
*
* @example
* // Create the toolbar
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // We will be placing status text in this element when tools are used
* var $area = $( '<p>' ).text( 'Toolbar example' );
*
* // Define the tools that we're going to place in our toolbar
*
* // Create a class inheriting from OO.ui.Tool
* function SearchTool() {
* SearchTool.super.apply( this, arguments );
* }
* OO.inheritClass( SearchTool, OO.ui.Tool );
* // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
* // of 'icon' and 'title' (displayed icon and text).
* SearchTool.static.name = 'search';
* SearchTool.static.icon = 'search';
* SearchTool.static.title = 'Search...';
* // Defines the action that will happen when this tool is selected (clicked).
* SearchTool.prototype.onSelect = function () {
* $area.text( 'Search tool clicked!' );
* // Never display this tool as "active" (selected).
* this.setActive( false );
* };
* SearchTool.prototype.onUpdateState = function () {};
* // Make this tool available in our toolFactory and thus our toolbar
* toolFactory.register( SearchTool );
*
* // Register two more tools, nothing interesting here
* function SettingsTool() {
* SettingsTool.super.apply( this, arguments );
* this.reallyActive = false;
* }
* OO.inheritClass( SettingsTool, OO.ui.Tool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.icon = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.prototype.onSelect = function () {
* $area.text( 'Settings tool clicked!' );
* // Toggle the active state on each click
* this.reallyActive = !this.reallyActive;
* this.setActive( this.reallyActive );
* // To update the menu label
* this.toolbar.emit( 'updateState' );
* };
* SettingsTool.prototype.onUpdateState = function () {};
* toolFactory.register( SettingsTool );
*
* // Register two more tools, nothing interesting here
* function StuffTool() {
* StuffTool.super.apply( this, arguments );
* this.reallyActive = false;
* }
* OO.inheritClass( StuffTool, OO.ui.Tool );
* StuffTool.static.name = 'stuff';
* StuffTool.static.icon = 'ellipsis';
* StuffTool.static.title = 'More stuff';
* StuffTool.prototype.onSelect = function () {
* $area.text( 'More stuff tool clicked!' );
* // Toggle the active state on each click
* this.reallyActive = !this.reallyActive;
* this.setActive( this.reallyActive );
* // To update the menu label
* this.toolbar.emit( 'updateState' );
* };
* StuffTool.prototype.onUpdateState = function () {};
* toolFactory.register( StuffTool );
*
* // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
* // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
* function HelpTool( toolGroup, config ) {
* OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
* padded: true,
* label: 'Help',
* head: true
* } }, config ) );
* this.popup.$body.append( '<p>I am helpful!</p>' );
* }
* OO.inheritClass( HelpTool, OO.ui.PopupTool );
* HelpTool.static.name = 'help';
* HelpTool.static.icon = 'help';
* HelpTool.static.title = 'Help';
* toolFactory.register( HelpTool );
*
* // Finally define which tools and in what order appear in the toolbar. Each tool may only be
* // used once (but not all defined tools must be used).
* toolbar.setup( [
* {
* // 'bar' tool groups display tools' icons only, side-by-side.
* type: 'bar',
* include: [ 'search', 'help' ]
* },
* {
* // 'menu' tool groups display both the titles and icons, in a dropdown menu.
* // Menu label indicates which items are selected.
* type: 'menu',
* indicator: 'down',
* include: [ 'settings', 'stuff' ]
* }
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* var contentFrame = new OO.ui.PanelLayout( {
* expanded: false,
* padded: true
* } );
* frame.$element.append(
* toolbar.$element,
* contentFrame.$element.append( $area )
* );
* $( document.body ).append( frame.$element );
*
* // Here is where the toolbar is actually built. This must be done after inserting it into the
* // document.
* toolbar.initialize();
* toolbar.emit( 'updateState' );
*
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
* @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
* @param {Object} [config] Configuration options
* @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are
* included in the toolbar, but are not configured as tools. By default, actions are displayed on
* the right side of the toolbar.
* @cfg {string} [position='top'] Whether the toolbar is positioned above ('top') or below
* ('bottom') content.
* @cfg {jQuery} [$overlay] An overlay for the popup.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*/
OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
config = toolFactory;
toolFactory = config.toolFactory;
toolGroupFactory = config.toolGroupFactory;
}
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Toolbar.super.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
OO.ui.mixin.GroupElement.call( this, config );
// Properties
this.toolFactory = toolFactory;
this.toolGroupFactory = toolGroupFactory;
this.groupsByName = {};
this.activeToolGroups = 0;
this.tools = {};
this.position = config.position || 'top';
this.$bar = $( '<div>' );
this.$actions = $( '<div>' );
this.$popups = $( '<div>' );
this.initialized = false;
this.narrowThreshold = null;
this.onWindowResizeHandler = this.onWindowResize.bind( this );
this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) ||
this.$element;
// Events
this.$element
.add( this.$bar ).add( this.$group ).add( this.$actions )
.on( 'mousedown keydown', this.onPointerDown.bind( this ) );
// Initialization
this.$group.addClass( 'oo-ui-toolbar-tools' );
if ( config.actions ) {
this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
}
this.$popups.addClass( 'oo-ui-toolbar-popups' );
this.$bar
.addClass( 'oo-ui-toolbar-bar' )
.append( this.$group, '<div style="clear:both"></div>' );
// Possible classes: oo-ui-toolbar-position-top, oo-ui-toolbar-position-bottom
this.$element
.addClass( 'oo-ui-toolbar oo-ui-toolbar-position-' + this.position )
.append( this.$bar );
this.$overlay.append( this.$popups );
};
/* Setup */
OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement );
/* Events */
/**
* @event updateState
*
* An 'updateState' event must be emitted on the Toolbar (by calling
* `toolbar.emit( 'updateState' )`) every time the state of the application using the toolbar
* changes, and an update to the state of tools is required.
*
* @param {...Mixed} data Application-defined parameters
*/
/**
* @event active
*
* An 'active' event is emitted when the number of active toolgroups increases from 0, or
* returns to 0.
*
* @param {boolean} There are active toolgroups in this toolbar
*/
/* Methods */
/**
* Get the tool factory.
*
* @return {OO.ui.ToolFactory} Tool factory
*/
OO.ui.Toolbar.prototype.getToolFactory = function () {
return this.toolFactory;
};
/**
* Get the toolgroup factory.
*
* @return {OO.Factory} Toolgroup factory
*/
OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
return this.toolGroupFactory;
};
/**
* Handles mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
* @return {undefined|boolean} False to prevent default if event is handled
*/
OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
$closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
if (
!$closestWidgetToEvent.length ||
$closestWidgetToEvent[ 0 ] ===
$closestWidgetToToolbar[ 0 ]
) {
return false;
}
};
/**
* Handle window resize event.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.Toolbar.prototype.onWindowResize = function () {
this.$element.add( this.$popups ).toggleClass(
'oo-ui-toolbar-narrow',
this.$bar[ 0 ].clientWidth <= this.getNarrowThreshold()
);
};
/**
* Get the (lazily-computed) width threshold for applying the oo-ui-toolbar-narrow
* class.
*
* @private
* @return {number} Width threshold in pixels
*/
OO.ui.Toolbar.prototype.getNarrowThreshold = function () {
if ( this.narrowThreshold === null ) {
this.narrowThreshold = this.$group[ 0 ].offsetWidth + this.$actions[ 0 ].offsetWidth;
}
return this.narrowThreshold;
};
/**
* Sets up handles and preloads required information for the toolbar to work.
* This must be called after it is attached to a visible document and before doing anything else.
*/
OO.ui.Toolbar.prototype.initialize = function () {
if ( !this.initialized ) {
this.initialized = true;
$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
this.onWindowResize();
}
};
/**
* Set up the toolbar.
*
* The toolbar is set up with a list of toolgroup configurations that specify the type of
* toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or
* {@link OO.ui.ListToolGroup list}) to add and which tools to include, exclude, promote, or demote
* within that toolgroup. Please see {@link OO.ui.ToolGroup toolgroups} for more information about
* including tools in toolgroups.
*
* @param {Object.<string,Array>} groups List of toolgroup configurations
* @param {string} [groups.name] Symbolic name for this toolgroup
* @param {string} [groups.type] Toolgroup type, should exist in the toolgroup factory
* @param {Array|string} [groups.include] Tools to include in the toolgroup
* @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
* @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
* @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
*/
OO.ui.Toolbar.prototype.setup = function ( groups ) {
var i, len, type, toolGroup, groupConfig,
items = [],
defaultType = 'bar';
// Cleanup previous groups
this.reset();
// Build out new groups
for ( i = 0, len = groups.length; i < len; i++ ) {
groupConfig = groups[ i ];
if ( groupConfig.include === '*' ) {
// Apply defaults to catch-all groups
if ( groupConfig.type === undefined ) {
groupConfig.type = 'list';
}
if ( groupConfig.label === undefined ) {
groupConfig.label = OO.ui.msg( 'ooui-toolbar-more' );
}
}
// Check type has been registered
type = this.getToolGroupFactory().lookup( groupConfig.type ) ?
groupConfig.type : defaultType;
toolGroup = this.getToolGroupFactory().create( type, this, groupConfig );
items.push( toolGroup );
this.groupsByName[ groupConfig.name ] = toolGroup;
toolGroup.connect( this, {
active: 'onToolGroupActive'
} );
}
this.addItems( items );
};
/**
* Handle active events from tool groups
*
* @param {boolean} active Tool group has become active, inactive if false
* @fires active
*/
OO.ui.Toolbar.prototype.onToolGroupActive = function ( active ) {
if ( active ) {
this.activeToolGroups++;
if ( this.activeToolGroups === 1 ) {
this.emit( 'active', true );
}
} else {
this.activeToolGroups--;
if ( this.activeToolGroups === 0 ) {
this.emit( 'active', false );
}
}
};
/**
* Get a toolgroup by name
*
* @param {string} name Group name
* @return {OO.ui.ToolGroup|null} Tool group, or null if none found by that name
*/
OO.ui.Toolbar.prototype.getToolGroupByName = function ( name ) {
return this.groupsByName[ name ] || null;
};
/**
* Remove all tools and toolgroups from the toolbar.
*/
OO.ui.Toolbar.prototype.reset = function () {
var i, len;
this.groupsByName = {};
this.tools = {};
for ( i = 0, len = this.items.length; i < len; i++ ) {
this.items[ i ].destroy();
}
this.clearItems();
};
/**
* Destroy the toolbar.
*
* Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar.
* Call this method whenever you are done using a toolbar.
*/
OO.ui.Toolbar.prototype.destroy = function () {
$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
this.reset();
this.$element.remove();
};
/**
* Check if the tool is available.
*
* Available tools are ones that have not yet been added to the toolbar.
*
* @param {string} name Symbolic name of tool
* @return {boolean} Tool is available
*/
OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
return !this.tools[ name ];
};
/**
* Prevent tool from being used again.
*
* @param {OO.ui.Tool} tool Tool to reserve
*/
OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
this.tools[ tool.getName() ] = tool;
};
/**
* Allow tool to be used again.
*
* @param {OO.ui.Tool} tool Tool to release
*/
OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
delete this.tools[ tool.getName() ];
};
/**
* Get accelerator label for tool.
*
* The OOUI library does not contain an accelerator system, but this is the hook for one. To
* use an accelerator system, subclass the toolbar and override this method, which is meant to
* return a label that describes the accelerator keys for the tool passed (by symbolic name) to
* the method.
*
* @param {string} name Symbolic name of tool
* @return {string|undefined} Tool accelerator label if available
*/
OO.ui.Toolbar.prototype.getToolAccelerator = function () {
return undefined;
};
/**
* Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute
* {@link OO.ui.Toolbar toolbars}.
* Each tool is configured with a static name, title, and icon and is customized with the command
* to carry out when the tool is selected. Tools must also be registered with a
* {@link OO.ui.ToolFactory tool factory}, which creates the tools on demand.
*
* Every Tool subclass must implement two methods:
*
* - {@link #onUpdateState}
* - {@link #onSelect}
*
* Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
* {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which
* determine how the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an
* example.
*
* For more information, please see the [OOUI documentation on MediaWiki][1].
* [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars
*
* @abstract
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {OO.ui.ToolGroup} toolGroup
* @param {Object} [config] Configuration options
* @cfg {string|Function} [title] Title text or a function that returns text. If this config is
* omitted, the value of the {@link #static-title static title} property is used.
*
* The title is used in different ways depending on the type of toolgroup that contains the tool.
* The title is used as a tooltip if the tool is part of a {@link OO.ui.BarToolGroup bar}
* toolgroup, or as the label text if the tool is part of a {@link OO.ui.ListToolGroup list} or
* {@link OO.ui.MenuToolGroup menu} toolgroup.
*
* For bar toolgroups, a description of the accelerator key is appended to the title if an
* accelerator key is associated with an action by the same name as the tool and accelerator
* functionality has been added to the application.
* To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the
* {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
*/
OO.ui.Tool = function OoUiTool( toolGroup, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
config = toolGroup;
toolGroup = config.toolGroup;
}
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Tool.super.call( this, config );
// Properties
this.toolGroup = toolGroup;
this.toolbar = this.toolGroup.getToolbar();
this.active = false;
this.$title = $( '<span>' );
this.$accel = $( '<span>' );
this.$link = $( '<a>' );
this.title = null;
this.checkIcon = new OO.ui.IconWidget( {
icon: 'check',
classes: [ 'oo-ui-tool-checkIcon' ]
} );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
$tabIndexed: this.$link
}, config ) );
// Events
this.toolbar.connect( this, {
updateState: 'onUpdateState'
} );
// Initialization
this.$title.addClass( 'oo-ui-tool-title' );
this.$accel
.addClass( 'oo-ui-tool-accel' )
.prop( {
// This may need to be changed if the key names are ever localized,
// but for now they are essentially written in English
dir: 'ltr',
lang: 'en'
} );
this.$link
.addClass( 'oo-ui-tool-link' )
.append( this.checkIcon.$element, this.$icon, this.$title, this.$accel )
.attr( 'role', 'button' );
// Don't show keyboard shortcuts on mobile as users are unlikely to have
// a physical keyboard, and likely to have limited screen space.
if ( !OO.ui.isMobile() ) {
this.$link.append( this.$accel );
}
this.$element
.data( 'oo-ui-tool', this )
.addClass( 'oo-ui-tool' )
.addClass( 'oo-ui-tool-name-' +
this.constructor.static.name.replace( /^([^/]+)\/([^/]+).*$/, '$1-$2' ) )
.toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel )
.append( this.$link );
this.setTitle( config.title || this.constructor.static.title );
};
/* Setup */
OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.Tool.static.tagName = 'span';
/**
* Symbolic name of tool.
*
* The symbolic name is used internally to register the tool with a
* {@link OO.ui.ToolFactory ToolFactory}. It can also be used when adding tools to toolgroups.
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.Tool.static.name = '';
/**
* Symbolic name of the group.
*
* The group name is used to associate tools with each other so that they can be selected later by
* a {@link OO.ui.ToolGroup toolgroup}.
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.Tool.static.group = '';
/**
* Tool title text or a function that returns title text. The value of the static property is
* overridden if the #title config option is used.
*
* @abstract
* @static
* @inheritable
* @property {string|Function}
*/
OO.ui.Tool.static.title = '';
/**
* Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
* Normally only the icon is displayed, or only the label if no icon is given.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.Tool.static.displayBothIconAndLabel = false;
/**
* Add tool to catch-all groups automatically.
*
* A catch-all group, which contains all tools that do not currently belong to a toolgroup,
* can be included in a toolgroup using the wildcard selector, an asterisk (*).
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.Tool.static.autoAddToCatchall = true;
/**
* Add tool to named groups automatically.
*
* By default, tools that are configured with a static ‘group’ property are added
* to that group and will be selected when the symbolic name of the group is specified (e.g., when
* toolgroups include tools by group name).
*
* @static
* @property {boolean}
* @inheritable
*/
OO.ui.Tool.static.autoAddToGroup = true;
/**
* Check if this tool is compatible with given data.
*
* This is a stub that can be overridden to provide support for filtering tools based on an
* arbitrary piece of information (e.g., where the cursor is in a document). The implementation
* must also call this method so that the compatibility check can be performed.
*
* @static
* @inheritable
* @param {Mixed} data Data to check
* @return {boolean} Tool can be used with data
*/
OO.ui.Tool.static.isCompatibleWith = function () {
return false;
};
/* Methods */
/**
* Handle the toolbar state being updated. This method is called when the
* {@link OO.ui.Toolbar#event-updateState 'updateState' event} is emitted on the
* {@link OO.ui.Toolbar Toolbar} that uses this tool, and should set the state of this tool
* depending on application state (usually by calling #setDisabled to enable or disable the tool,
* or #setActive to mark is as currently in-use or not).
*
* This is an abstract method that must be overridden in a concrete subclass.
*
* @method
* @protected
* @abstract
*/
OO.ui.Tool.prototype.onUpdateState = null;
/**
* Handle the tool being selected. This method is called when the user triggers this tool,
* usually by clicking on its label/icon.
*
* This is an abstract method that must be overridden in a concrete subclass.
*
* @method
* @protected
* @abstract
*/
OO.ui.Tool.prototype.onSelect = null;
/**
* Check if the tool is active.
*
* Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
* with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
*
* @return {boolean} Tool is active
*/
OO.ui.Tool.prototype.isActive = function () {
return this.active;
};
/**
* Make the tool appear active or inactive.
*
* This method should be called within #onSelect or #onUpdateState event handlers to make the tool
* appear pressed or not.
*
* @param {boolean} state Make tool appear active
*/
OO.ui.Tool.prototype.setActive = function ( state ) {
this.active = !!state;
this.$element.toggleClass( 'oo-ui-tool-active', this.active );
this.updateThemeClasses();
};
/**
* Set the tool #title.
*
* @param {string|Function} title Title text or a function that returns text
* @chainable
* @return {OO.ui.Tool} The tool, for chaining
*/
OO.ui.Tool.prototype.setTitle = function ( title ) {
this.title = OO.ui.resolveMsg( title );
this.updateTitle();
return this;
};
/**
* Get the tool #title.
*
* @return {string} Title text
*/
OO.ui.Tool.prototype.getTitle = function () {
return this.title;
};
/**
* Get the tool's symbolic name.
*
* @return {string} Symbolic name of tool
*/
OO.ui.Tool.prototype.getName = function () {
return this.constructor.static.name;
};
/**
* Update the title.
*/
OO.ui.Tool.prototype.updateTitle = function () {
var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
accelTooltips = this.toolGroup.constructor.static.accelTooltips,
accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
tooltipParts = [];
this.$title.text( this.title );
this.$accel.text( accel );
if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
tooltipParts.push( this.title );
}
if ( accelTooltips && typeof accel === 'string' && accel.length ) {
tooltipParts.push( accel );
}
if ( tooltipParts.length ) {
this.$link.attr( 'title', tooltipParts.join( ' ' ) );
} else {
this.$link.removeAttr( 'title' );
}
};
/**
* @inheritdoc OO.ui.mixin.IconElement
*/
OO.ui.Tool.prototype.setIcon = function ( icon ) {
// Mixin method
OO.ui.mixin.IconElement.prototype.setIcon.call( this, icon );
this.$element.toggleClass( 'oo-ui-tool-with-icon', !!this.icon );
return this;
};
/**
* Destroy tool.
*
* Destroying the tool removes all event handlers and the tool’s DOM elements.
* Call this method whenever you are done using a tool.
*/
OO.ui.Tool.prototype.destroy = function () {
this.toolbar.disconnect( this );
this.$element.remove();
};
/**
* ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a
* {@link OO.ui.Toolbar toolbar}.
* The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or
* {@link OO.ui.MenuToolGroup menu}) to which a tool belongs determines how the tool is arranged
* and displayed in the toolbar. Toolgroups themselves are created on demand with a
* {@link OO.ui.ToolGroupFactory toolgroup factory}.
*
* Toolgroups can contain individual tools, groups of tools, or all available tools, as specified
* using the `include` config option. See OO.ui.ToolFactory#extract on documentation of the format.
* The options `exclude`, `promote`, and `demote` support the same formats.
*
* See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in
* general, please see the [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars
*
* @abstract
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.mixin.GroupElement
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
* @cfg {Array|string} [include] List of tools to include in the toolgroup, see above.
* @cfg {Array|string} [exclude] List of tools to exclude from the toolgroup, see above.
* @cfg {Array|string} [promote] List of tools to promote to the beginning of the toolgroup,
* see above.
* @cfg {Array|string} [demote] List of tools to demote to the end of the toolgroup, see above.
* This setting is particularly useful when tools have been added to the toolgroup
* en masse (e.g., via the catch-all selector).
*/
OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.ToolGroup.super.call( this, config );
// Mixin constructors
OO.ui.mixin.GroupElement.call( this, config );
// Properties
this.toolbar = toolbar;
this.tools = {};
this.pressed = null;
this.autoDisabled = false;
this.include = config.include || [];
this.exclude = config.exclude || [];
this.promote = config.promote || [];
this.demote = config.demote || [];
this.onDocumentMouseKeyUpHandler = this.onDocumentMouseKeyUp.bind( this );
// Events
this.$group.on( {
mousedown: this.onMouseKeyDown.bind( this ),
mouseup: this.onMouseKeyUp.bind( this ),
keydown: this.onMouseKeyDown.bind( this ),
keyup: this.onMouseKeyUp.bind( this ),
focus: this.onMouseOverFocus.bind( this ),
blur: this.onMouseOutBlur.bind( this ),
mouseover: this.onMouseOverFocus.bind( this ),
mouseout: this.onMouseOutBlur.bind( this )
} );
this.toolbar.getToolFactory().connect( this, {
register: 'onToolFactoryRegister'
} );
this.aggregate( {
disable: 'itemDisable'
} );
this.connect( this, {
itemDisable: 'updateDisabled',
disable: 'onDisable'
} );
// Initialization
this.$group.addClass( 'oo-ui-toolGroup-tools' );
this.$element
.addClass( 'oo-ui-toolGroup' )
.append( this.$group );
this.onDisable( this.isDisabled() );
this.populate();
};
/* Setup */
OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement );
/* Events */
/**
* @event update
*/
/**
* @event active
*
* An 'active' event is emitted when any popup is shown/hidden.
*
* @param {boolean} The popup is visible
*/
/* Static Properties */
/**
* Show labels in tooltips.
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.ToolGroup.static.titleTooltips = false;
/**
* Show acceleration labels in tooltips.
*
* Note: The OOUI library does not include an accelerator system, but does contain
* a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
* override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
* meant to return a label that describes the accelerator keys for a given tool (e.g., Control+M
* key combination).
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.ToolGroup.static.accelTooltips = false;
/**
* Automatically disable the toolgroup when all tools are disabled
*
* @static
* @inheritable
* @property {boolean}
*/
OO.ui.ToolGroup.static.autoDisable = true;
/**
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.ToolGroup.static.name = null;
/* Methods */
/**
* @inheritdoc
*/
OO.ui.ToolGroup.prototype.isDisabled = function () {
return this.autoDisabled ||
OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
};
/**
* @inheritdoc
*/
OO.ui.ToolGroup.prototype.updateDisabled = function () {
var i, item, allDisabled = true;
if ( this.constructor.static.autoDisable ) {
for ( i = this.items.length - 1; i >= 0; i-- ) {
item = this.items[ i ];
if ( !item.isDisabled() ) {
allDisabled = false;
break;
}
}
this.autoDisabled = allDisabled;
}
OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
};
/**
* Handle disable events.
*
* @protected
* @param {boolean} isDisabled
*/
OO.ui.ToolGroup.prototype.onDisable = function ( isDisabled ) {
this.$group.toggleClass( 'oo-ui-toolGroup-disabled-tools', isDisabled );
this.$group.toggleClass( 'oo-ui-toolGroup-enabled-tools', !isDisabled );
};
/**
* Handle mouse down and key down events.
*
* @protected
* @param {jQuery.Event} e Mouse down or key down event
* @return {undefined|boolean} False to prevent default if event is handled
*/
OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) {
if (
!this.isDisabled() && (
e.which === OO.ui.MouseButtons.LEFT ||
e.which === OO.ui.Keys.SPACE ||
e.which === OO.ui.Keys.ENTER
)
) {
this.pressed = this.findTargetTool( e );
if ( this.pressed ) {
this.pressed.setActive( true );
this.getElementDocument().addEventListener(
'mouseup',
this.onDocumentMouseKeyUpHandler,
true
);
this.getElementDocument().addEventListener(
'keyup',
this.onDocumentMouseKeyUpHandler,
true
);
return false;
}
}
};
/**
* Handle document mouse up and key up events.
*
* @protected
* @param {MouseEvent|KeyboardEvent} e Mouse up or key up event
*/
OO.ui.ToolGroup.prototype.onDocumentMouseKeyUp = function ( e ) {
this.getElementDocument().removeEventListener(
'mouseup',
this.onDocumentMouseKeyUpHandler,
true
);
this.getElementDocument().removeEventListener(
'keyup',
this.onDocumentMouseKeyUpHandler,
true
);
// onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
// released, but since `this.pressed` will no longer be true, the second call will be ignored.
this.onMouseKeyUp( e );
};
/**
* Handle mouse up and key up events.
*
* @protected
* @param {MouseEvent|KeyboardEvent} e Mouse up or key up event
*/
OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) {
var tool = this.findTargetTool( e );
if (
!this.isDisabled() && this.pressed && this.pressed === tool && (
e.which === OO.ui.MouseButtons.LEFT ||
e.which === OO.ui.Keys.SPACE ||
e.which === OO.ui.Keys.ENTER
)
) {
this.pressed.onSelect();
this.pressed = null;
e.preventDefault();
e.stopPropagation();
}
this.pressed = null;
};
/**
* Handle mouse over and focus events.
*
* @protected
* @param {jQuery.Event} e Mouse over or focus event
*/
OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) {
var tool = this.findTargetTool( e );
if ( this.pressed && this.pressed === tool ) {
this.pressed.setActive( true );
}
};
/**
* Handle mouse out and blur events.
*
* @protected
* @param {jQuery.Event} e Mouse out or blur event
*/
OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) {
var tool = this.findTargetTool( e );
if ( this.pressed && this.pressed === tool ) {
this.pressed.setActive( false );
}
};
/**
* Get the closest tool to a jQuery.Event.
*
* Only tool links are considered, which prevents other elements in the tool such as popups from
* triggering tool group interactions.
*
* @private
* @param {jQuery.Event} e
* @return {OO.ui.Tool|null} Tool, `null` if none was found
*/
OO.ui.ToolGroup.prototype.findTargetTool = function ( e ) {
var tool,
$item = $( e.target ).closest( '.oo-ui-tool-link' );
if ( $item.length ) {
tool = $item.parent().data( 'oo-ui-tool' );
}
return tool && !tool.isDisabled() ? tool : null;
};
/**
* Handle tool registry register events.
*
* If a tool is registered after the group is created, we must repopulate the list to account for:
*
* - a tool being added that may be included
* - a tool already included being overridden
*
* @protected
* @param {string} name Symbolic name of tool
*/
OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
this.populate();
};
/**
* Get the toolbar that contains the toolgroup.
*
* @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
*/
OO.ui.ToolGroup.prototype.getToolbar = function () {
return this.toolbar;
};
/**
* Add and remove tools based on configuration.
*/
OO.ui.ToolGroup.prototype.populate = function () {
var i, len, name, tool,
toolFactory = this.toolbar.getToolFactory(),
names = {},
add = [],
remove = [],
list = this.toolbar.getToolFactory().getTools(
this.include, this.exclude, this.promote, this.demote
);
// Build a list of needed tools
for ( i = 0, len = list.length; i < len; i++ ) {
name = list[ i ];
if (
// Tool exists
toolFactory.lookup( name ) &&
// Tool is available or is already in this group
( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
) {
// Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool
// before creating it, but we can't call reserveTool() yet because we haven't created
// the tool.
this.toolbar.tools[ name ] = true;
tool = this.tools[ name ];
if ( !tool ) {
// Auto-initialize tools on first use
this.tools[ name ] = tool = toolFactory.create( name, this );
tool.updateTitle();
}
this.toolbar.reserveTool( tool );
add.push( tool );
names[ name ] = true;
}
}
// Remove tools that are no longer needed
for ( name in this.tools ) {
if ( !names[ name ] ) {
this.tools[ name ].destroy();
this.toolbar.releaseTool( this.tools[ name ] );
remove.push( this.tools[ name ] );
delete this.tools[ name ];
}
}
if ( remove.length ) {
this.removeItems( remove );
}
// Update emptiness state
if ( add.length ) {
this.$element.removeClass( 'oo-ui-toolGroup-empty' );
} else {
this.$element.addClass( 'oo-ui-toolGroup-empty' );
}
// Re-add tools (moving existing ones to new locations)
this.addItems( add );
// Disabled state may depend on items
this.updateDisabled();
};
/**
* Destroy toolgroup.
*/
OO.ui.ToolGroup.prototype.destroy = function () {
var name;
this.clearItems();
this.toolbar.getToolFactory().disconnect( this );
for ( name in this.tools ) {
this.toolbar.releaseTool( this.tools[ name ] );
this.tools[ name ].disconnect( this ).destroy();
delete this.tools[ name ];
}
this.$element.remove();
};
/**
* A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools},
* {@link OO.ui.PopupTool PopupTools}, and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be
* registered with a tool factory. Tools are registered by their symbolic name. See
* {@link OO.ui.Toolbar toolbars} for an example.
*
* For more information about toolbars in general, please see the
* [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars
*
* @class
* @extends OO.Factory
* @constructor
*/
OO.ui.ToolFactory = function OoUiToolFactory() {
// Parent constructor
OO.ui.ToolFactory.super.call( this );
};
/* Setup */
OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
/* Methods */
/**
* Get tools from the factory.
*
* @param {Array|string} [include] Included tools, see #extract for format
* @param {Array|string} [exclude] Excluded tools, see #extract for format
* @param {Array|string} [promote] Promoted tools, see #extract for format
* @param {Array|string} [demote] Demoted tools, see #extract for format
* @return {string[]} List of tools
*/
OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
var i, len, included, promoted, demoted,
auto = [],
used = {};
// Collect included and not excluded tools
included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
// Promotion
promoted = this.extract( promote, used );
demoted = this.extract( demote, used );
// Auto
for ( i = 0, len = included.length; i < len; i++ ) {
if ( !used[ included[ i ] ] ) {
auto.push( included[ i ] );
}
}
return promoted.concat( auto ).concat( demoted );
};
/**
* Get a flat list of names from a list of names or groups.
*
* Normally, `collection` is an array of tool specifications. Tools can be specified in the
* following ways:
*
* - To include an individual tool, use the symbolic name: `{ name: 'tool-name' }` or `'tool-name'`.
* - To include all tools in a group, use the group name: `{ group: 'group-name' }`. (To assign the
* tool to a group, use OO.ui.Tool.static.group.)
*
* Alternatively, to include all tools that are not yet assigned to any other toolgroup, use the
* catch-all selector `'*'`.
*
* If `used` is passed, tool names that appear as properties in this object will be considered
* already assigned, and will not be returned even if specified otherwise. The tool names extracted
* by this function call will be added as new properties in the object.
*
* @private
* @param {Array|string} collection List of tools, see above
* @param {Object} [used] Object containing information about used tools, see above
* @return {string[]} List of extracted tool names
*/
OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
var i, len, item, name, tool,
names = [];
collection = !Array.isArray( collection ) ? [ collection ] : collection;
for ( i = 0, len = collection.length; i < len; i++ ) {
item = collection[ i ];
if ( item === '*' ) {
for ( name in this.registry ) {
tool = this.registry[ name ];
if (
// Only add tools by group name when auto-add is enabled
tool.static.autoAddToCatchall &&
// Exclude already used tools
( !used || !used[ name ] )
) {
names.push( name );
if ( used ) {
used[ name ] = true;
}
}
}
} else {
// Allow plain strings as shorthand for named tools
if ( typeof item === 'string' ) {
item = { name: item };
}
if ( OO.isPlainObject( item ) ) {
if ( item.group ) {
for ( name in this.registry ) {
tool = this.registry[ name ];
if (
// Include tools with matching group
tool.static.group === item.group &&
// Only add tools by group name when auto-add is enabled
tool.static.autoAddToGroup &&
// Exclude already used tools
( !used || !used[ name ] )
) {
names.push( name );
if ( used ) {
used[ name ] = true;
}
}
}
// Include tools with matching name and exclude already used tools
} else if ( item.name && ( !used || !used[ item.name ] ) ) {
names.push( item.name );
if ( used ) {
used[ item.name ] = true;
}
}
}
}
}
return names;
};
/**
* ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes
* must specify a symbolic name and be registered with the factory. The following classes are
* registered by default:
*
* - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
* - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
* - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
*
* See {@link OO.ui.Toolbar toolbars} for an example.
*
* For more information about toolbars in general, please see the
* [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars
*
* @class
* @extends OO.Factory
* @constructor
*/
OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
var i, l, defaultClasses;
// Parent constructor
OO.Factory.call( this );
defaultClasses = this.constructor.static.getDefaultClasses();
// Register default toolgroups
for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
this.register( defaultClasses[ i ] );
}
};
/* Setup */
OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
/* Static Methods */
/**
* Get a default set of classes to be registered on construction.
*
* @return {Function[]} Default classes
*/
OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
return [
OO.ui.BarToolGroup,
OO.ui.ListToolGroup,
OO.ui.MenuToolGroup
];
};
/**
* Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}.
* Each popup tool is configured with a static name, title, and icon, as well with as any popup
* configurations. Unlike other tools, popup tools do not require that developers specify an
* #onSelect or #onUpdateState method, as these methods have been implemented already.
*
* // Example of a popup tool. When selected, a popup tool displays
* // a popup window.
* function HelpTool( toolGroup, config ) {
* OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
* padded: true,
* label: 'Help',
* head: true
* } }, config ) );
* this.popup.$body.append( '<p>I am helpful!</p>' );
* };
* OO.inheritClass( HelpTool, OO.ui.PopupTool );
* HelpTool.static.name = 'help';
* HelpTool.static.icon = 'help';
* HelpTool.static.title = 'Help';
* toolFactory.register( HelpTool );
*
* For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}.
* For more information about toolbars in general, please see the
* [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars
*
* @abstract
* @class
* @extends OO.ui.Tool
* @mixins OO.ui.mixin.PopupElement
*
* @constructor
* @param {OO.ui.ToolGroup} toolGroup
* @param {Object} [config] Configuration options
*/
OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
config = toolGroup;
toolGroup = config.toolGroup;
}
// Parent constructor
OO.ui.PopupTool.super.call( this, toolGroup, config );
// Mixin constructors
OO.ui.mixin.PopupElement.call( this, config );
// Events
this.popup.connect( this, {
toggle: 'onPopupToggle'
} );
// Initialization
this.popup.setAutoFlip( false );
this.popup.setPosition( toolGroup.getToolbar().position === 'bottom' ? 'above' : 'below' );
this.$element.addClass( 'oo-ui-popupTool' );
this.popup.$element.addClass( 'oo-ui-popupTool-popup' );
this.toolbar.$popups.append( this.popup.$element );
};
/* Setup */
OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement );
/* Methods */
/**
* Handle the tool being selected.
*
* @inheritdoc
*/
OO.ui.PopupTool.prototype.onSelect = function () {
if ( !this.isDisabled() ) {
this.popup.toggle();
}
return false;
};
/**
* Handle the toolbar state being updated.
*
* @inheritdoc
*/
OO.ui.PopupTool.prototype.onUpdateState = function () {
};
/**
* Handle popup visibility being toggled.
*
* @param {boolean} isVisible
*/
OO.ui.PopupTool.prototype.onPopupToggle = function ( isVisible ) {
this.setActive( isVisible );
this.toolGroup.emit( 'active', isVisible );
};
/**
* A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
* and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
* inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
* the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
* when the ToolGroupTool is selected.
*
* // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2',
* // defined elsewhere.
*
* function SettingsTool() {
* SettingsTool.super.apply( this, arguments );
* };
* OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.static.groupConfig = {
* icon: 'settings',
* label: 'ToolGroupTool',
* include: [ 'setting1', 'setting2' ]
* };
* toolFactory.register( SettingsTool );
*
* For more information, please see the [OOUI documentation on MediaWiki][1].
*
* Please note that this implementation is subject to change per [T74159] [2].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars#ToolGroupTool
* [2]: https://phabricator.wikimedia.org/T74159
*
* @abstract
* @class
* @extends OO.ui.Tool
*
* @constructor
* @param {OO.ui.ToolGroup} toolGroup
* @param {Object} [config] Configuration options
*/
OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
config = toolGroup;
toolGroup = config.toolGroup;
}
// Parent constructor
OO.ui.ToolGroupTool.super.call( this, toolGroup, config );
// Properties
this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
// Events
this.innerToolGroup.connect( this, {
disable: 'onToolGroupDisable',
// Re-emit active events from the innerToolGroup on the parent toolGroup
active: this.toolGroup.emit.bind( this.toolGroup, 'active' )
} );
// Initialization
this.$link.remove();
this.$element
.addClass( 'oo-ui-toolGroupTool' )
.append( this.innerToolGroup.$element );
};
/* Setup */
OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
/* Static Properties */
/**
* Toolgroup configuration.
*
* The toolgroup configuration consists of the tools to include, as well as an icon and label
* to use for the bar item. Tools can be included by symbolic name, group, or with the
* wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
*
* @property {Object.<string,Array>}
*/
OO.ui.ToolGroupTool.static.groupConfig = {};
/* Methods */
/**
* Handle the tool being selected.
*
* @inheritdoc
*/
OO.ui.ToolGroupTool.prototype.onSelect = function () {
this.innerToolGroup.setActive( !this.innerToolGroup.active );
return false;
};
/**
* Synchronize disabledness state of the tool with the inner toolgroup.
*
* @private
* @param {boolean} disabled Element is disabled
*/
OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) {
this.setDisabled( disabled );
};
/**
* Handle the toolbar state being updated.
*
* @inheritdoc
*/
OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
this.setActive( false );
};
/**
* Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
*
* @param {Object.<string,Array>} group Toolgroup configuration. Please see
* {@link OO.ui.ToolGroup toolgroup} for more information.
* @return {OO.ui.ListToolGroup}
*/
OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
if ( group.include === '*' ) {
// Apply defaults to catch-all groups
if ( group.label === undefined ) {
group.label = OO.ui.msg( 'ooui-toolbar-more' );
}
}
return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
};
/**
* BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
* create {@link OO.ui.Toolbar toolbars} (the other types of groups are
* {@link OO.ui.MenuToolGroup MenuToolGroup} and {@link OO.ui.ListToolGroup ListToolGroup}).
* The {@link OO.ui.Tool tools} in a BarToolGroup are displayed by icon in a single row. The
* title of the tool is displayed when users move the mouse over the tool.
*
* BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
* is set up.
*
* @example
* // Example of a BarToolGroup with two tools
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // We will be placing status text in this element when tools are used
* var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
*
* // Define the tools that we're going to place in our toolbar
*
* // Create a class inheriting from OO.ui.Tool
* function SearchTool() {
* SearchTool.super.apply( this, arguments );
* }
* OO.inheritClass( SearchTool, OO.ui.Tool );
* // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
* // of 'icon' and 'title' (displayed icon and text).
* SearchTool.static.name = 'search';
* SearchTool.static.icon = 'search';
* SearchTool.static.title = 'Search...';
* // Defines the action that will happen when this tool is selected (clicked).
* SearchTool.prototype.onSelect = function () {
* $area.text( 'Search tool clicked!' );
* // Never display this tool as "active" (selected).
* this.setActive( false );
* };
* SearchTool.prototype.onUpdateState = function () {};
* // Make this tool available in our toolFactory and thus our toolbar
* toolFactory.register( SearchTool );
*
* // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
* // little popup window (a PopupWidget).
* function HelpTool( toolGroup, config ) {
* OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
* padded: true,
* label: 'Help',
* head: true
* } }, config ) );
* this.popup.$body.append( '<p>I am helpful!</p>' );
* }
* OO.inheritClass( HelpTool, OO.ui.PopupTool );
* HelpTool.static.name = 'help';
* HelpTool.static.icon = 'help';
* HelpTool.static.title = 'Help';
* toolFactory.register( HelpTool );
*
* // Finally define which tools and in what order appear in the toolbar. Each tool may only be
* // used once (but not all defined tools must be used).
* toolbar.setup( [
* {
* // 'bar' tool groups display tools by icon only
* type: 'bar',
* include: [ 'search', 'help' ]
* }
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* var contentFrame = new OO.ui.PanelLayout( {
* expanded: false,
* padded: true
* } );
* frame.$element.append(
* toolbar.$element,
* contentFrame.$element.append( $area )
* );
* $( document.body ).append( frame.$element );
*
* // Here is where the toolbar is actually built. This must be done after inserting it into the
* // document.
* toolbar.initialize();
*
* For more information about how to add tools to a bar tool group, please see
* {@link OO.ui.ToolGroup toolgroup}.
* For more information about toolbars in general, please see the
* [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars
*
* @class
* @extends OO.ui.ToolGroup
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
*/
OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Parent constructor
OO.ui.BarToolGroup.super.call( this, toolbar, config );
// Initialization
this.$element.addClass( 'oo-ui-barToolGroup' );
this.$group.addClass( 'oo-ui-barToolGroup-tools' );
};
/* Setup */
OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.BarToolGroup.static.titleTooltips = true;
/**
* @static
* @inheritdoc
*/
OO.ui.BarToolGroup.static.accelTooltips = true;
/**
* @static
* @inheritdoc
*/
OO.ui.BarToolGroup.static.name = 'bar';
/**
* PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
* and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup (an overlaid menu or list of
* tools with an optional icon and label). This class can be used for other base classes that
* also use this functionality.
*
* @abstract
* @class
* @extends OO.ui.ToolGroup
* @mixins OO.ui.mixin.IconElement
* @mixins OO.ui.mixin.IndicatorElement
* @mixins OO.ui.mixin.LabelElement
* @mixins OO.ui.mixin.TitledElement
* @mixins OO.ui.mixin.FlaggedElement
* @mixins OO.ui.mixin.ClippableElement
* @mixins OO.ui.mixin.FloatableElement
* @mixins OO.ui.mixin.TabIndexedElement
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
* @cfg {string} [header] Text to display at the top of the popup
*/
OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Configuration initialization
config = $.extend( {
indicator: config.indicator === undefined ?
( toolbar.position === 'bottom' ? 'up' : 'down' ) : config.indicator
}, config );
// Parent constructor
OO.ui.PopupToolGroup.super.call( this, toolbar, config );
// Properties
this.active = false;
this.dragging = false;
// Don't conflict with parent method of the same name
this.onPopupDocumentMouseKeyUpHandler = this.onPopupDocumentMouseKeyUp.bind( this );
this.$handle = $( '<span>' );
// Mixin constructors
OO.ui.mixin.IconElement.call( this, config );
OO.ui.mixin.IndicatorElement.call( this, config );
OO.ui.mixin.LabelElement.call( this, config );
OO.ui.mixin.TitledElement.call( this, config );
OO.ui.mixin.FlaggedElement.call( this, config );
OO.ui.mixin.ClippableElement.call( this, $.extend( {
$clippable: this.$group
}, config ) );
OO.ui.mixin.FloatableElement.call( this, $.extend( {
$floatable: this.$group,
$floatableContainer: this.$handle,
hideWhenOutOfView: false,
verticalPosition: this.toolbar.position === 'bottom' ? 'above' : 'below'
}, config ) );
OO.ui.mixin.TabIndexedElement.call( this, $.extend( {
$tabIndexed: this.$handle
}, config ) );
// Events
this.$handle.on( {
keydown: this.onHandleMouseKeyDown.bind( this ),
keyup: this.onHandleMouseKeyUp.bind( this ),
mousedown: this.onHandleMouseKeyDown.bind( this ),
mouseup: this.onHandleMouseKeyUp.bind( this )
} );
// Initialization
this.$handle
.addClass( 'oo-ui-popupToolGroup-handle' )
.attr( 'role', 'button' )
.attr( 'aria-expanded', 'false' )
.append( this.$icon, this.$label, this.$indicator );
// If the pop-up should have a header, add it to the top of the toolGroup.
// Note: If this feature is useful for other widgets, we could abstract it into an
// OO.ui.HeaderedElement mixin constructor.
if ( config.header !== undefined ) {
this.$group
.prepend( $( '<span>' )
.addClass( 'oo-ui-popupToolGroup-header' )
.text( config.header )
);
}
this.$element
.addClass( 'oo-ui-popupToolGroup' )
.prepend( this.$handle );
this.$group.addClass( 'oo-ui-popupToolGroup-tools' );
this.toolbar.$popups.append( this.$group );
};
/* Setup */
OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.FlaggedElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.FloatableElement );
OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement );
/* Methods */
/**
* @inheritdoc
*/
OO.ui.PopupToolGroup.prototype.setDisabled = function () {
// Parent method
OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
if ( this.isDisabled() && this.isElementAttached() ) {
this.setActive( false );
}
};
/**
* Handle document mouse up and key up events.
*
* @protected
* @param {MouseEvent|KeyboardEvent} e Mouse up or key up event
*/
OO.ui.PopupToolGroup.prototype.onPopupDocumentMouseKeyUp = function ( e ) {
var $target = $( e.target );
// Only deactivate when clicking outside the dropdown element
if ( $target.closest( '.oo-ui-popupToolGroup' )[ 0 ] === this.$element[ 0 ] ) {
return;
}
if ( $target.closest( '.oo-ui-popupToolGroup-tools' )[ 0 ] === this.$group[ 0 ] ) {
return;
}
this.setActive( false );
};
/**
* @inheritdoc
*/
OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) {
// Only close toolgroup when a tool was actually selected
if (
!this.isDisabled() && this.pressed && this.pressed === this.findTargetTool( e ) && (
e.which === OO.ui.MouseButtons.LEFT ||
e.which === OO.ui.Keys.SPACE ||
e.which === OO.ui.Keys.ENTER
)
) {
this.setActive( false );
}
return OO.ui.PopupToolGroup.super.prototype.onMouseKeyUp.call( this, e );
};
/**
* @inheritdoc
*/
OO.ui.PopupToolGroup.prototype.onMouseKeyDown = function ( e ) {
var $focused, $firstFocusable, $lastFocusable;
// Shift-Tab on the first tool in the group jumps to the handle.
// Tab on the last tool in the group jumps to the next group.
if ( !this.isDisabled() && e.which === OO.ui.Keys.TAB ) {
// We can't use this.items because ListToolGroup inserts the extra fake
// expand/collapse tool.
$focused = $( document.activeElement );
$firstFocusable = OO.ui.findFocusable( this.$group );
if ( $focused[ 0 ] === $firstFocusable[ 0 ] && e.shiftKey ) {
this.$handle.trigger( 'focus' );
return false;
}
$lastFocusable = OO.ui.findFocusable( this.$group, true );
if ( $focused[ 0 ] === $lastFocusable[ 0 ] && !e.shiftKey ) {
// Focus this group's handle and let the browser's tab handling happen
// (no 'return false').
// This way we don't have to fiddle with other ToolGroups' business, or worry what to do
// if the next group is not a PopupToolGroup or doesn't exist at all.
this.$handle.trigger( 'focus' );
// Close the popup so that we don't move back inside it (if this is the last group).
this.setActive( false );
}
}
return OO.ui.PopupToolGroup.super.prototype.onMouseKeyDown.call( this, e );
};
/**
* Handle mouse up and key up events.
*
* @protected
* @param {jQuery.Event} e Mouse up or key up event
* @return {undefined|boolean} False to prevent default if event is handled
*/
OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) {
if (
!this.isDisabled() && (
e.which === OO.ui.MouseButtons.LEFT ||
e.which === OO.ui.Keys.SPACE ||
e.which === OO.ui.Keys.ENTER
)
) {
return false;
}
};
/**
* Handle mouse down and key down events.
*
* @protected
* @param {jQuery.Event} e Mouse down or key down event
* @return {undefined|boolean} False to prevent default if event is handled
*/
OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) {
var $focusable;
if ( !this.isDisabled() ) {
// Tab on the handle jumps to the first tool in the group (if the popup is open).
if ( e.which === OO.ui.Keys.TAB && !e.shiftKey ) {
$focusable = OO.ui.findFocusable( this.$group );
if ( $focusable.length ) {
$focusable.trigger( 'focus' );
return false;
}
}
if (
e.which === OO.ui.MouseButtons.LEFT ||
e.which === OO.ui.Keys.SPACE ||
e.which === OO.ui.Keys.ENTER
) {
this.setActive( !this.active );
return false;
}
}
};
/**
* Check if the tool group is active.
*
* @return {boolean} Tool group is active
*/
OO.ui.PopupToolGroup.prototype.isActive = function () {
return this.active;
};
/**
* Switch into 'active' mode.
*
* When active, the popup is visible. A mouseup event anywhere in the document will trigger
* deactivation.
*
* @param {boolean} value The active state to set
* @fires active
*/
OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
var containerWidth, containerLeft;
value = !!value;
if ( this.active !== value ) {
this.active = value;
if ( value ) {
this.getElementDocument().addEventListener(
'mouseup',
this.onPopupDocumentMouseKeyUpHandler,
true
);
this.getElementDocument().addEventListener(
'keyup',
this.onPopupDocumentMouseKeyUpHandler,
true
);
this.$clippable.css( 'left', '' );
this.$element.addClass( 'oo-ui-popupToolGroup-active' );
this.$group.addClass( 'oo-ui-popupToolGroup-active-tools' );
this.$handle.attr( 'aria-expanded', true );
this.togglePositioning( true );
this.toggleClipping( true );
// Try anchoring the popup to the left first
this.setHorizontalPosition( 'start' );
if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
// Anchoring to the left caused the popup to clip, so anchor it to the
// right instead.
this.setHorizontalPosition( 'end' );
}
if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
// Anchoring to the right also caused the popup to clip, so just make it fill the
// container.
containerWidth = this.$clippableScrollableContainer.width();
containerLeft = this.$clippableScrollableContainer[ 0 ] ===
document.documentElement ?
0 :
this.$clippableScrollableContainer.offset().left;
this.toggleClipping( false );
this.setHorizontalPosition( 'start' );
this.$clippable.css( {
'margin-left': -( this.$element.offset().left - containerLeft ),
width: containerWidth
} );
}
} else {
this.getElementDocument().removeEventListener(
'mouseup',
this.onPopupDocumentMouseKeyUpHandler,
true
);
this.getElementDocument().removeEventListener(
'keyup',
this.onPopupDocumentMouseKeyUpHandler,
true
);
this.$element.removeClass( 'oo-ui-popupToolGroup-active' );
this.$group.removeClass( 'oo-ui-popupToolGroup-active-tools' );
this.$handle.attr( 'aria-expanded', false );
this.togglePositioning( false );
this.toggleClipping( false );
}
this.emit( 'active', this.active );
this.updateThemeClasses();
}
};
/**
* ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
* create {@link OO.ui.Toolbar toolbars} (the other types of groups are
* {@link OO.ui.MenuToolGroup MenuToolGroup} and {@link OO.ui.BarToolGroup BarToolGroup}).
* The {@link OO.ui.Tool tools} in a ListToolGroup are displayed by label in a dropdown menu.
* The title of the tool is used as the label text. The menu itself can be configured with a label,
* icon, indicator, header, and title.
*
* ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a
* ‘More’ option that users can select to see the full list of tools. If a collapsed toolgroup is
* expanded, a ‘Fewer’ option permits users to collapse the list again.
*
* ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the
* toolbar is set up. The factory requires the ListToolGroup's symbolic name, 'list', which is
* specified along with the other configurations. For more information about how to add tools to a
* ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
*
* @example
* // Example of a ListToolGroup
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // Configure and register two tools
* function SettingsTool() {
* SettingsTool.super.apply( this, arguments );
* }
* OO.inheritClass( SettingsTool, OO.ui.Tool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.icon = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.prototype.onSelect = function () {
* this.setActive( false );
* };
* SettingsTool.prototype.onUpdateState = function () {};
* toolFactory.register( SettingsTool );
* // Register two more tools, nothing interesting here
* function StuffTool() {
* StuffTool.super.apply( this, arguments );
* }
* OO.inheritClass( StuffTool, OO.ui.Tool );
* StuffTool.static.name = 'stuff';
* StuffTool.static.icon = 'search';
* StuffTool.static.title = 'Change the world';
* StuffTool.prototype.onSelect = function () {
* this.setActive( false );
* };
* StuffTool.prototype.onUpdateState = function () {};
* toolFactory.register( StuffTool );
* toolbar.setup( [
* {
* // Configurations for list toolgroup.
* type: 'list',
* label: 'ListToolGroup',
* icon: 'ellipsis',
* title: 'This is the title, displayed when user moves the mouse over the list ' +
* 'toolgroup',
* header: 'This is the header',
* include: [ 'settings', 'stuff' ],
* allowCollapse: ['stuff']
* }
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* frame.$element.append(
* toolbar.$element
* );
* $( document.body ).append( frame.$element );
* // Build the toolbar. This must be done after the toolbar has been appended to the document.
* toolbar.initialize();
*
* For more information about toolbars in general, please see the
* [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars
*
* @class
* @extends OO.ui.PopupToolGroup
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
* @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible
* tools will only be displayed if users click the ‘More’ option displayed at the bottom of the
* list. If the list is expanded, a ‘Fewer’ option permits users to collapse the list again.
* Any tools that are included in the toolgroup, but are not designated as collapsible, will always
* be displayed.
* To open a collapsible list in its expanded state, set #expanded to 'true'.
* @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as
* collapsible. Unless #expanded is set to true, the collapsible tools will be collapsed when the
* list is first opened.
* @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools
* have been designated as collapsible. When expanded is set to true, all tools in the group will
* be displayed when the list is first opened. Users can collapse the list with a ‘Fewer’ option at
* the bottom.
*/
OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Configuration initialization
config = config || {};
// Properties (must be set before parent constructor, which calls #populate)
this.allowCollapse = config.allowCollapse;
this.forceExpand = config.forceExpand;
this.expanded = config.expanded !== undefined ? config.expanded : false;
this.collapsibleTools = [];
// Parent constructor
OO.ui.ListToolGroup.super.call( this, toolbar, config );
// Initialization
this.$element.addClass( 'oo-ui-listToolGroup' );
this.$group.addClass( 'oo-ui-listToolGroup-tools' );
};
/* Setup */
OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.ListToolGroup.static.name = 'list';
/* Methods */
/**
* @inheritdoc
*/
OO.ui.ListToolGroup.prototype.populate = function () {
var i, len, allowCollapse = [];
OO.ui.ListToolGroup.super.prototype.populate.call( this );
// Update the list of collapsible tools
if ( this.allowCollapse !== undefined ) {
allowCollapse = this.allowCollapse;
} else if ( this.forceExpand !== undefined ) {
allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
}
this.collapsibleTools = [];
for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
}
}
// Keep at the end, even when tools are added
this.$group.append( this.getExpandCollapseTool().$element );
this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
this.updateCollapsibleState();
};
/**
* Get the expand/collapse tool for this group
*
* @return {OO.ui.Tool} Expand collapse tool
*/
OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
var ExpandCollapseTool;
if ( this.expandCollapseTool === undefined ) {
ExpandCollapseTool = function () {
ExpandCollapseTool.super.apply( this, arguments );
};
OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
ExpandCollapseTool.prototype.onSelect = function () {
this.toolGroup.expanded = !this.toolGroup.expanded;
this.toolGroup.updateCollapsibleState();
this.setActive( false );
};
ExpandCollapseTool.prototype.onUpdateState = function () {
// Do nothing. Tool interface requires an implementation of this function.
};
ExpandCollapseTool.static.name = 'more-fewer';
this.expandCollapseTool = new ExpandCollapseTool( this );
}
return this.expandCollapseTool;
};
/**
* @inheritdoc
*/
OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) {
// Do not close the popup when the user wants to show more/fewer tools
if (
$( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length && (
e.which === OO.ui.MouseButtons.LEFT ||
e.which === OO.ui.Keys.SPACE ||
e.which === OO.ui.Keys.ENTER
)
) {
// HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation
// (which hides the popup list when a tool is selected) and call ToolGroup's implementation
// directly.
return OO.ui.ListToolGroup.super.super.prototype.onMouseKeyUp.call( this, e );
} else {
return OO.ui.ListToolGroup.super.prototype.onMouseKeyUp.call( this, e );
}
};
OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
var i, icon, len;
if ( this.toolbar.position !== 'bottom' ) {
icon = this.expanded ? 'collapse' : 'expand';
} else {
icon = this.expanded ? 'expand' : 'collapse';
}
this.getExpandCollapseTool()
.setIcon( icon )
.setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
this.collapsibleTools[ i ].toggle( this.expanded );
}
// Re-evaluate clipping, because our height has changed
this.clip();
};
/**
* MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
* create {@link OO.ui.Toolbar toolbars} (the other types of groups are
* {@link OO.ui.BarToolGroup BarToolGroup} and {@link OO.ui.ListToolGroup ListToolGroup}).
* MenuToolGroups contain selectable {@link OO.ui.Tool tools}, which are displayed by label in a
* dropdown menu. The tool's title is used as the label text, and the menu label is updated to
* reflect which tool or tools are currently selected. If no tools are selected, the menu label
* is empty. The menu can be configured with an indicator, icon, title, and/or header.
*
* MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the
* toolbar is set up.
*
* @example
* // Example of a MenuToolGroup
* var toolFactory = new OO.ui.ToolFactory();
* var toolGroupFactory = new OO.ui.ToolGroupFactory();
* var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
*
* // We will be placing status text in this element when tools are used
* var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the '
* + 'dropdown menu.' );
*
* // Define the tools that we're going to place in our toolbar
*
* function SettingsTool() {
* SettingsTool.super.apply( this, arguments );
* this.reallyActive = false;
* }
* OO.inheritClass( SettingsTool, OO.ui.Tool );
* SettingsTool.static.name = 'settings';
* SettingsTool.static.icon = 'settings';
* SettingsTool.static.title = 'Change settings';
* SettingsTool.prototype.onSelect = function () {
* $area.text( 'Settings tool clicked!' );
* // Toggle the active state on each click
* this.reallyActive = !this.reallyActive;
* this.setActive( this.reallyActive );
* // To update the menu label
* this.toolbar.emit( 'updateState' );
* };
* SettingsTool.prototype.onUpdateState = function () {};
* toolFactory.register( SettingsTool );
*
* function StuffTool() {
* StuffTool.super.apply( this, arguments );
* this.reallyActive = false;
* }
* OO.inheritClass( StuffTool, OO.ui.Tool );
* StuffTool.static.name = 'stuff';
* StuffTool.static.icon = 'ellipsis';
* StuffTool.static.title = 'More stuff';
* StuffTool.prototype.onSelect = function () {
* $area.text( 'More stuff tool clicked!' );
* // Toggle the active state on each click
* this.reallyActive = !this.reallyActive;
* this.setActive( this.reallyActive );
* // To update the menu label
* this.toolbar.emit( 'updateState' );
* };
* StuffTool.prototype.onUpdateState = function () {};
* toolFactory.register( StuffTool );
*
* // Finally define which tools and in what order appear in the toolbar. Each tool may only be
* // used once (but not all defined tools must be used).
* toolbar.setup( [
* {
* type: 'menu',
* header: 'This is the (optional) header',
* title: 'This is the (optional) title',
* include: [ 'settings', 'stuff' ]
* }
* ] );
*
* // Create some UI around the toolbar and place it in the document
* var frame = new OO.ui.PanelLayout( {
* expanded: false,
* framed: true
* } );
* var contentFrame = new OO.ui.PanelLayout( {
* expanded: false,
* padded: true
* } );
* frame.$element.append(
* toolbar.$element,
* contentFrame.$element.append( $area )
* );
* $( document.body ).append( frame.$element );
*
* // Here is where the toolbar is actually built. This must be done after inserting it into the
* // document.
* toolbar.initialize();
* toolbar.emit( 'updateState' );
*
* For more information about how to add tools to a MenuToolGroup, please see
* {@link OO.ui.ToolGroup toolgroup}.
* For more information about toolbars in general, please see the
* [OOUI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Toolbars
*
* @class
* @extends OO.ui.PopupToolGroup
*
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
*/
OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( toolbar ) && config === undefined ) {
config = toolbar;
toolbar = config.toolbar;
}
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.MenuToolGroup.super.call( this, toolbar, config );
// Events
this.toolbar.connect( this, {
updateState: 'onUpdateState'
} );
// Initialization
this.$element.addClass( 'oo-ui-menuToolGroup' );
this.$group.addClass( 'oo-ui-menuToolGroup-tools' );
};
/* Setup */
OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MenuToolGroup.static.name = 'menu';
/* Methods */
/**
* Handle the toolbar state being updated.
*
* When the state changes, the title of each active item in the menu will be joined together and
* used as a label for the group. The label will be empty if none of the items are active.
*
* @private
*/
OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
var name,
labelTexts = [];
for ( name in this.tools ) {
if ( this.tools[ name ].isActive() ) {
labelTexts.push( this.tools[ name ].getTitle() );
}
}
this.setLabel( labelTexts.join( ', ' ) || ' ' );
};
}( OO ) );
//# sourceMappingURL=oojs-ui-toolbars.js.map.json |
$("#zoom_01").elevateZoom();
$("#zoom_02").elevateZoom({ zoomType : "inner", cursor: "crosshair" });
$("#zoom_03").elevateZoom({
zoomType : "lens",
lensShape : "round",
lensSize : 200
});
|
import PropTypes from 'prop-types';
import React from 'react';
import ScheduleCard from './ScheduleCard';
import ScheduleContentHeading from './ScheduleContentHeading';
import { connect } from 'react-redux';
import { createUseStyles } from 'react-jss';
const useStyles = createUseStyles({
schedule: {
flex: '1 1 100%',
marginLeft: '15px',
marginRight: '15px'
},
cards: {
display: 'flex',
flexWrap: 'nowrap',
marginLeft: '-15px',
marginRight: '-15px'
},
card: {
flex: '1 1 50%',
marginLeft: '15px',
marginRight: '15px'
}
});
function ScheduleContent (props) {
const { mode } = props;
const classes = useStyles();
const schedules = getDisplayTargetSchedules(props);
return schedules.map((sc, i) => (
<div key={i} className={[classes.schedule, 'mb-3'].join(' ')}>
<ScheduleContentHeading schedule={sc} mode={mode} />
<div className={classes.cards}>
{sc.maps.map((mapInfo) => (
<div className={classes.card} key={mapInfo.key}>
<ScheduleCard
map={mapInfo}
mode={mode}
schedule={sc}
/>
</div>
))}
</div>
</div>
));
}
ScheduleContent.propTypes = {
locale: PropTypes.object,
mode: PropTypes.string.isRequired,
now: PropTypes.number.isRequired,
schedules: PropTypes.array.isRequired
};
function getDisplayTargetSchedules (props) {
const { now, schedules } = props;
const tmpList = schedules.filter(item => item.time[1] > now);
tmpList.sort((a, b) => a.time[1] - b.time[1]);
return tmpList.slice(0, 2);
}
function mapStateToProps (state) {
return {
locale: state.schedule.data ? state.schedule.data.locale : null,
now: Math.floor(state.schedule.currentTime / 1000)
};
}
function mapDispatchToProps (/* dispatch */) {
return {};
}
export default connect(mapStateToProps, mapDispatchToProps)(ScheduleContent);
|
var should = require('should');
var io = require('socket.io-client');
var config = require('./config_mocha');
var mainConfig = require('../../config_' + (process.env.NODE_ENV || 'dev'));
var socketURL = config.socketURL;
var options ={
transports: ['websocket'],
'force new connection': true
};
describe("Code Functions",function(){
var hostClient;
this.timeout(10000);
beforeEach(function(done){
hostClient = io.connect(socketURL, options);
hostClient.on('connect', function(data){
hostClient.emit('createRoom', {
name: mainConfig.testRoomName,
moderatorPass: '1234',
readOnly: false,
hostVersion: "0.1.4"
});
hostClient.on('roomCreated', function(){
done();
})
});
//set up a mock for the host behaviour
var fileAContent = "this is file a";
var fileBContent = "this is file b";
hostClient.on('changeCurrentFile', function(newFile){
switch(newFile){
case "a.txt":
hostClient.emit('refreshData', fileAContent, true);
break;
case "b.txt":
hostClient.emit('refreshData', fileBContent, true);
break;
case "unhosted.txt":
hostClient.emit('newChatMessage', 'changeCurrentFile for ' + newFile + ' refused... file is not hosted');
break;
case "readerror.txt":
hostClient.emit('newChatMessage', "error reading file " + newFile + ' ' + err);
break;
}
});
hostClient.on('saveCurrentFile', function(data){
if(data.file=="a.txt"){
fileAContent = data.body;
hostClient.emit('newChatMessage', "file save succeeded for file " + data.file);
}
if(data.file=="b.txt"){
fileBContent = data.body;
hostClient.emit('newChatMessage', "file save succeeded for file " + data.file);
}
//unmocked responses
//hostClient.emit('newChatMessage', 'file save for ' + data.file + ' refused... room is read only');
//hostClient.emit('newChatMessage', 'file save for ' + data.file + ' refused... file is not hosted');
});
});
afterEach(function(done){
hostClient.disconnect();
done();
});
it('Should sync open files for new clients', function(done){
var user1Client = io.connect(socketURL, options);
var user2Client;
user1Client.on('connect', function(data){
user1Client.emit('joinRoom', {room: mainConfig.testRoomName});
});
user1Client.on('roomJoined', function(){
//need to have access permissions to mess about with data so get moderator role
user1Client.emit('changeUserId', 'bob');
});
user1Client.on('userRoleChanged', function(userId, role){
role.should.equal('moderator');
user1Client.emit('changeCurrentFile', 'a.txt');
user1Client.on('refreshData', function(data){
data.should.equal('this is file a');
});
user2Client = io.connect(socketURL, options);
user2Client.on('connect', function(data){
user2Client.emit('joinRoom', {room: mainConfig.testRoomName});
user2Client.on('syncOpenFile', function(openFile){
openFile.body.should.equal('this is file a');
openFile.fileName.should.equal('a.txt');
openFile.isDirty.should.equal(false);
user1Client.disconnect();
user2Client.disconnect();
config.doneWithWait(done);
});
});
});//userrolechanged
});//it should
it('Should broadcast refreshData for existing clients on new file open', function(done){
var user1Client = io.connect(socketURL, options);
var user2Client;
user1Client.on('connect', function(data){
user1Client.emit('joinRoom', {room: mainConfig.testRoomName});
});
user1Client.on('roomJoined', function(){
//need to have access permissions to mess about with data so get moderator role
user1Client.emit('changeUserId', 'bob');
});
user1Client.on('userRoleChanged', function(userId, role){
role.should.equal('moderator');
user1Client.on('refreshData', function(data){
data.should.equal('this is file a');
});
user2Client = io.connect(socketURL, options);
user2Client.on('connect', function(data){
user2Client.emit('joinRoom', {room: mainConfig.testRoomName});
user1Client.emit('changeCurrentFile', 'a.txt');
user2Client.on('refreshData', function(data){
data.should.equal('this is file a');
user1Client.disconnect();
user2Client.disconnect();
config.doneWithWait(done);
});
});
});
});//it should
it('Should broadcast changeData for existing clients', function(done){
var user1Client = io.connect(socketURL, options);
var user2Client;refreshCounter = 0;
user1Client.on('connect', function(data){
user1Client.emit('joinRoom', {room: mainConfig.testRoomName});
user1Client.on('changeData', function(op){
op.origin.should.equal('+input');
user1Client.disconnect();
user2Client.disconnect();
config.doneWithWait(done);
});
user2Client = io.connect(socketURL, options);
user2Client.on('connect', function(data){
user2Client.emit('joinRoom', {room: mainConfig.testRoomName});
user2Client.on('roomJoined', function(){
user2Client.emit('changeUserId', 'charlene');
user2Client.emit('requestChangeRole', {userId:'charlene', newRole:'moderator', pass:'1234'});
user2Client.on('userRoleChanged', function(userId, role){
user2Client.emit('changeData', {origin:'+input'});
});
});
});
});
});//it should
it('Should hold changes for multiple files', function(done){
var user1Client = io.connect(socketURL, options);
var user2Client;
user1Client.on('connect', function(data){
user1Client.emit('joinRoom', {room: mainConfig.testRoomName});
});
user1Client.on('userRoleChanged', function(userId, role){
role.should.equal('moderator');
user1Client.emit('changeCurrentFile', 'a.txt');
user1Client.on('refreshData', function(data){
if(data==="this is file a"){
user1Client.emit('refreshData', 'this is file a modified', false);
user1Client.emit('changeCurrentFile', 'b.txt');
}
if(data==="this is file b"){
user2Client = io.connect(socketURL, options);
user2Client.on('connect', function(data){
user2Client.emit('joinRoom', {room: mainConfig.testRoomName});
user2Client.on('syncOpenFile', function(openFile){
if(openFile.fileName==='a.txt'){
openFile.body.should.equal('this is file a modified');
openFile.isDirty.should.equal(true);
user1Client.disconnect();
user2Client.disconnect();
config.doneWithWait(done);
}else if (openFile.fileName==='b.txt'){
openFile.body.should.equal('this is file b');
openFile.isDirty.should.equal(false);
}
});
});
}
});
});
});//it should
});//describe
//this is the shizzle |
/* global moment:true */
/**
* @module ember-flexberry
*/
import Ember from 'ember';
import FlexberryBaseComponent from './flexberry-base-component';
import { translationMacro as t } from 'ember-i18n';
/**
* DateTime picker component for Semantic UI (Semantic UI hasn't its own DateTime picker component yet).
*
* @class FlexberryDatetimePicker
* @extends FlexberryBaseComponent
*/
export default FlexberryBaseComponent.extend({
// String with input css classes.
classes: undefined,
classNames: ['ui', 'icon', 'input'],
// Flag to make control required.
required: false,
/**
* The placeholder attribute.
*
* @property placeholder
* @type String
* @default 't('components.flexberry-datepicker.placeholder')'
*/
placeholder: t('components.flexberry-datepicker.placeholder'),
// Flag to show time in control and time picker inside date picker.
hasTimePicker: false,
// Type of input element for render.
type: 'text',
// Input value.
value: undefined,
// Invalid date for set to model value when needed.
invalidDate: new Date('invalid'),
// Default display format.
dateTimeFormat: 'DD.MM.YYYY',
// The earliest date a user may select.
minDate: undefined,
// The latest date a user may select.
maxDate: undefined,
// Init component when DOM is ready.
didInsertElement: function() {
this.minDate = this.minDate === undefined ? moment('01.01.1900', this.dateTimeFormat) : moment(this.minDate, this.dateTimeFormat);
this.maxDate = this.maxDate === undefined ? moment('31.12.9999', this.dateTimeFormat) : moment(this.maxDate, this.dateTimeFormat);
var hasTimePicker = this.get('hasTimePicker');
if (hasTimePicker) {
this.dateTimeFormat = 'DD.MM.YYYY HH:mm:ss';
}
var val = this.get('value');
var startDate = moment(new Date());
if (val !== undefined && moment(val).isValid()) {
startDate = moment(val);
this.$('input').val(startDate.format(this.dateTimeFormat));
}
var readonly = this.get('readonly');
var _this = this;
var i18n = _this.get('i18n');
if (!readonly) {
this.$('input').daterangepicker(
{
startDate: startDate,
locale: {
applyLabel: i18n.t('components.flexberry-datepicker.apply-button-text'),
cancelLabel: i18n.t('components.flexberry-datepicker.cancel-button-text')
},
singleDatePicker: true,
showDropdowns: true,
timePicker: hasTimePicker,
timePickerIncrement: 1,
timePicker12Hour: false,
timePickerSeconds: true,
minDate: this.minDate,
maxDate: this.maxDate,
format: this.dateTimeFormat
},
function(start, end, label) {
_this.setValue(end);
});
this.$('i').click(function() {
_this.$('input').trigger('click');
});
this.$('input').on('apply.daterangepicker', function(ev, picker) {
var currentValue = _this.get('value');
var pickerDateString = moment(picker.endDate.toDate()).format(_this.dateTimeFormat);
// TODO: refactor
let tmp = !moment(moment(currentValue).format(_this.dateTimeFormat), _this.dateTimeFormat).isSame(moment(pickerDateString, _this.dateTimeFormat));
if (!currentValue || tmp) {
_this.setValue(picker.endDate);
}
});
this.$('input').on('cancel.daterangepicker', function(ev, picker) {
var currentInputValueString = _this.$('input').val();
var pickerDateString = picker.endDate.format(_this.dateTimeFormat);
// TODO: refactor
let tmp = moment(currentInputValueString, _this.dateTimeFormat);
let tmp2 = !moment(tmp.format(_this.dateTimeFormat), _this.dateTimeFormat).isSame(moment(pickerDateString, _this.dateTimeFormat));
if (tmp2) {
var oldPickerDateString = picker.endDate._i;
if (typeof (oldPickerDateString) === 'string' && currentInputValueString !== oldPickerDateString) {
_this.$('input').val(oldPickerDateString);
}
var currentValue = _this.get('value');
if (!moment(moment(currentValue).format(_this.dateTimeFormat), _this.dateTimeFormat).isSame(moment(pickerDateString, _this.dateTimeFormat))) {
_this.setValue(picker.endDate);
}
}
});
this.$('input').on('show.daterangepicker', function(ev, picker) {
if (!picker.endDate.isValid()) {
_this.$('input').data('daterangepicker').startDate = moment.invalid();
}
_this.setCalendarEnabledState();
});
this.$('input').keyup(function() {
var valueFromInput = _this.$(this).val();
_this.setValue(moment(valueFromInput, _this.dateTimeFormat));
});
}
},
setValue: function(dateFromPicker) {
var valueFromInput = this.$('input').val();
if (valueFromInput === '' && !dateFromPicker.isValid()) {
this.setEmptyValue();
} else {
var dateToSet = this.getDateToSet(dateFromPicker);
var currentValue = this.get('value');
// TODO: refactor
let tmp = moment(dateToSet).format(this.dateTimeFormat);
let tmp2 = !moment(tmp, this.dateTimeFormat).isSame(moment(moment(currentValue).format(this.dateTimeFormat), this.dateTimeFormat));
if (currentValue === null || tmp2) {
this.set('value', dateToSet);
this.setProperOffsetToCalendar();
}
}
this.setCalendarEnabledState();
},
setEmptyValue: function() {
var currentValue = this.get('value');
if (currentValue !== null) {
this.set('value', null);
this.setProperOffsetToCalendar();
}
},
getDateToSet: function(dateFromPicker) {
if (!dateFromPicker.isValid()) {
return this.invalidDate;
}
if (dateFromPicker.isBefore(this.minDate) || dateFromPicker.isAfter(this.maxDate)) {
return this.invalidDate;
}
return dateFromPicker.toDate();
},
setCalendarEnabledState: function() {
var dateToSet = this.getDateToSet(this.$('input').data('daterangepicker').endDate);
if ((!dateToSet || dateToSet === this.invalidDate) && this.hasTimePicker) {
this.$().parents('body').find('button.applyBtn').attr('disabled', 'disabled');
this.$('input').data('daterangepicker').startDate = moment.invalid();
} else {
this.$().parents('body').find('button.applyBtn').removeAttr('disabled');
}
},
setProperOffsetToCalendar: function() {
//Waiting for end of validation and displaying errors if model is not valid
var _this = this;
setTimeout(function() { _this.$('input').data('daterangepicker').move(); }, 500);
},
// Set proper start date when value changed outside of component.
valueChanged: Ember.observer('value', function() {
var val = this.get('value');
var currValueDateTime = moment(this.getDateToSet(moment(val)));
if (val && moment.isDate(val) && currValueDateTime.isValid()) {
var currInputDateTime = moment(moment(this.$('input').val(), this.dateTimeFormat).toDate());
// Change current date and time when changes were made outside of input element.
if (!currValueDateTime.isSame(currInputDateTime)) {
if (this.$('input').data('daterangepicker') !== undefined) {
this.$('input').data('daterangepicker').startDate = currValueDateTime;
this.$('input').data('daterangepicker').setEndDate(currValueDateTime);
} else {
this.$('input').val(currValueDateTime.format(this.dateTimeFormat));
}
}
} else if (val === null) {
var valueFromInput = this.$('input').val();
if (valueFromInput !== '') {
this.$('input').val('');
}
} else if (!currValueDateTime.isValid()) {
if (val !== this.invalidDate) {
this.set('value', this.invalidDate);
this.$('input').val(currValueDateTime.format(this.dateTimeFormat));
}
} else if (!moment.isDate(val)) {
this.set('value', currValueDateTime.toDate());
}
})
});
|
/**
* @license Highstock JS v9.3.1 (2021-11-05)
* @module highcharts/indicators/stochastic
* @requires highcharts
* @requires highcharts/modules/stock
*
* Indicator series type for Highcharts Stock
*
* (c) 2010-2021 Paweł Fus
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Stock/Indicators/Stochastic/StochasticIndicator.js';
|
/*! Monio: nothing.js
v0.8.0 (c) 2021 Kyle Simpson
MIT License: http://getify.mit-license.org
*/
!function UMD(n,o,e,t){"function"==typeof define&&define.amd?(e=Object.keys(e).map((n=>n.replace(/^\.\//,""))),define(n,e,t)):"undefined"!=typeof module&&module.exports?(e=Object.keys(e).map((n=>require(n))),module.exports=t(...e)):(e=Object.values(e).map((n=>o[n])),o[n]=t(...e))}("Nothing","undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:new Function("return this")(),{},(function DEF(){"use strict";var n={};let o={};function Nothing(){var o={map:noop,chain:noop,flatMap:noop,bind:noop,ap:noop,concat:noop,_inspect:function _inspect(){return`${o[Symbol.toStringTag]}()`},_is:function _is(o){return o===n},[Symbol.toStringTag]:"Nothing"};return o;function noop(){return o}}return o=Object.assign(Nothing,{of:Nothing,pure:Nothing,unit:Nothing,is:function is(o){return o&&"function"==typeof o._is&&o._is(n)},isEmpty:function isEmpty(n){return null==n}}),o})); |
/**
* Tom Select v1.7.3
* Licensed under the Apache License, Version 2.0 (the "License");
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('../../tom-select.js')) :
typeof define === 'function' && define.amd ? define(['../../tom-select'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TomSelect));
}(this, (function (TomSelect) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var TomSelect__default = /*#__PURE__*/_interopDefaultLegacy(TomSelect);
/**
* Plugin: "input_autogrow" (Tom Select)
*
* Licensed 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.
*
*/
TomSelect__default['default'].define('no_backspace_delete', function () {
var self = this;
var orig_deleteSelection = self.deleteSelection;
this.hook('instead', 'deleteSelection', function () {
if (self.activeItems.length) {
return orig_deleteSelection.apply(self, arguments);
}
return false;
});
});
})));
//# sourceMappingURL=no_backspace_delete.js.map
|
/**
* @license Highstock JS v8.1.2 (2020-06-16)
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Sebastian Bochan
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/cci', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'indicators/cci.src.js', [_modules['parts/Utilities.js']], function (U) {
/* *
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
* */
var isArray = U.isArray,
seriesType = U.seriesType;
/* eslint-disable valid-jsdoc */
// Utils:
/**
* @private
*/
function sumArray(array) {
return array.reduce(function (prev, cur) {
return prev + cur;
}, 0);
}
/**
* @private
*/
function meanDeviation(arr, sma) {
var len = arr.length,
sum = 0,
i;
for (i = 0; i < len; i++) {
sum += Math.abs(sma - (arr[i]));
}
return sum;
}
/* eslint-enable valid-jsdoc */
/**
* The CCI series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.cci
*
* @augments Highcharts.Series
*/
seriesType('cci', 'sma',
/**
* Commodity Channel Index (CCI). This series requires `linkedTo` option to
* be set.
*
* @sample stock/indicators/cci
* CCI indicator
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/cci
* @optionparent plotOptions.cci
*/
{
params: {
period: 14
}
},
/**
* @lends Highcharts.Series#
*/
{
getValues: function (series, params) {
var period = params.period,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
TP = [],
periodTP = [],
range = 1,
CCI = [],
xData = [],
yData = [],
CCIPoint,
p,
len,
smaTP,
TPtemp,
meanDev,
i;
// CCI requires close value
if (xVal.length <= period ||
!isArray(yVal[0]) ||
yVal[0].length !== 4) {
return;
}
// accumulate first N-points
while (range < period) {
p = yVal[range - 1];
TP.push((p[1] + p[2] + p[3]) / 3);
range++;
}
for (i = period; i <= yValLen; i++) {
p = yVal[i - 1];
TPtemp = (p[1] + p[2] + p[3]) / 3;
len = TP.push(TPtemp);
periodTP = TP.slice(len - period);
smaTP = sumArray(periodTP) / period;
meanDev = meanDeviation(periodTP, smaTP) / period;
CCIPoint = ((TPtemp - smaTP) / (0.015 * meanDev));
CCI.push([xVal[i - 1], CCIPoint]);
xData.push(xVal[i - 1]);
yData.push(CCIPoint);
}
return {
values: CCI,
xData: xData,
yData: yData
};
}
});
/**
* A `CCI` series. If the [type](#series.cci.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.cci
* @since 6.0.0
* @excluding dataParser, dataURL
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/cci
* @apioption series.cci
*/
''; // to include the above in the js output
});
_registerModule(_modules, 'masters/indicators/cci.src.js', [], function () {
});
})); |
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["MathJax_SansSerif-bold"],{160:[0,0,250,0,0],305:[458,0,256,54,201],567:[458,205,286,-71,232],915:[691,0,581,92,534],916:[694,0,917,60,856],920:[716,22,856,62,793],923:[694,0,672,41,630],926:[688,0,733,46,686],928:[691,0,794,92,702],931:[694,0,794,61,732],933:[715,0,856,62,793],934:[694,0,794,62,732],936:[694,0,856,61,794],937:[716,0,794,49,744],8211:[327,-240,550,0,549],8212:[327,-240,1100,0,1099],8216:[694,-443,306,81,226],8217:[694,-442,306,80,226],8220:[694,-443,558,138,520],8221:[694,-442,558,37,420]}),MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/SansSerif/Bold/Other.js"); |
(function (root, factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof module === "object" && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.hyphenationPatternsEu = factory();
}
})(this, function () {
var patterns = [],
hyphenation = [];
// copyright: Copyright (C) 1997, 2008 Juan M. Aguirregabiria
// title: Hyphenation patterns for Basque
// notice: This file is part of the hyph-utf8 package.
// See http://www.hyphenation.org/tex for more information on the package,
// and http://tp.lc.ehu.es/jma/basque.html for details on Basque hyphenation.
// language:
// name: Basque
// tag: eu
// version: June 2008
// authors:
// -
// name: Juan M. Aguirregabiria
// contact: juanmari.aguirregabiria (at) ehu.es
// licence:
// text: >
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this file and any associated documentation
// (the "Data Files") to deal in the Data Files
// without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, and/or sell copies of
// the Data Files, and to permit persons to whom the Data Files
// are furnished to do so, provided that
// (a) this copyright and permission notice appear with all copies
// of the Data Files,
// (b) this copyright and permission notice appear in associated
// documentation, and
// (c) there is clear notice in each modified Data File
// as well as in the documentation associated with the Data File(s)
// that the data has been modified.
//
// THE DATA FILES ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT OF THIRD PARTY RIGHTS.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
// NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
// DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
// DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THE DATA FILES.
//
// Except as contained in this notice, the name of a copyright holder
// shall not be used in advertising or otherwise to promote the sale,
// use or other dealings in these Data Files without prior
// written authorization of the copyright holder.
// changes:
// - >
// February 1997 Patterns created by Juan M. Aguirregabiria, based on the
// shyphen.sh script for Spanish by Julio Sanchez, September 1991.
// - >
// June 2008 Generating script rewritten in Ruby and adapted for native
// UTF-8 TeX engines, patterns renamed from bahyph.tex to
// hyph-eu.tex and added to the hyph-utf8 package. Functionality should
// not change apart from adding ñ by default.
// ==========================================
//
// Open vowels: a e o
// Closed vowels: i u
// Consonants: b c d f g j k l m n ñ p q r s t v w x y z
//
// Some of the patterns below represent combinations that never
// happen in Basque. Would they happen, they would be hyphenated
// according to the rules.
//
var patterns = [
// Rule SR1
// Vowels are kept together by the defaults
// Rule SR2
// Attach vowel groups to left consonant
"1ba",
"1be",
"1bo",
"1bi",
"1bu",
"1ca",
"1ce",
"1co",
"1ci",
"1cu",
"1da",
"1de",
"1do",
"1di",
"1du",
"1fa",
"1fe",
"1fo",
"1fi",
"1fu",
"1ga",
"1ge",
"1go",
"1gi",
"1gu",
"1ja",
"1je",
"1jo",
"1ji",
"1ju",
"1ka",
"1ke",
"1ko",
"1ki",
"1ku",
"1la",
"1le",
"1lo",
"1li",
"1lu",
"1ma",
"1me",
"1mo",
"1mi",
"1mu",
"1na",
"1ne",
"1no",
"1ni",
"1nu",
"1ña",
"1ñe",
"1ño",
"1ñi",
"1ñu",
"1pa",
"1pe",
"1po",
"1pi",
"1pu",
"1qa",
"1qe",
"1qo",
"1qi",
"1qu",
"1ra",
"1re",
"1ro",
"1ri",
"1ru",
"1sa",
"1se",
"1so",
"1si",
"1su",
"1ta",
"1te",
"1to",
"1ti",
"1tu",
"1va",
"1ve",
"1vo",
"1vi",
"1vu",
"1wa",
"1we",
"1wo",
"1wi",
"1wu",
"1xa",
"1xe",
"1xo",
"1xi",
"1xu",
"1ya",
"1ye",
"1yo",
"1yi",
"1yu",
"1za",
"1ze",
"1zo",
"1zi",
"1zu",
// Rule SR3
// Build legal consonant groups, leave other consonants bound to
// the previous group. This overrides part of the SR2 pattern group.
"1l2la",
"1l2le",
"1l2lo",
"1l2li",
"1l2lu",
"1r2ra",
"1r2re",
"1r2ro",
"1r2ri",
"1r2ru",
"1t2sa",
"1t2se",
"1t2so",
"1t2si",
"1t2su",
"1t2xa",
"1t2xe",
"1t2xo",
"1t2xi",
"1t2xu",
"1t2za",
"1t2ze",
"1t2zo",
"1t2zi",
"1t2zu",
"1b2la",
"1b2le",
"1b2lo",
"1b2li",
"1b2lu",
"1b2ra",
"1b2re",
"1b2ro",
"1b2ri",
"1b2ru",
"1d2ra",
"1d2re",
"1d2ro",
"1d2ri",
"1d2ru",
"1f2la",
"1f2le",
"1f2lo",
"1f2li",
"1f2lu",
"1f2ra",
"1f2re",
"1f2ro",
"1f2ri",
"1f2ru",
"1g2la",
"1g2le",
"1g2lo",
"1g2li",
"1g2lu",
"1g2ra",
"1g2re",
"1g2ro",
"1g2ri",
"1g2ru",
"1k2la",
"1k2le",
"1k2lo",
"1k2li",
"1k2lu",
"1k2ra",
"1k2re",
"1k2ro",
"1k2ri",
"1k2ru",
"1p2la",
"1p2le",
"1p2lo",
"1p2li",
"1p2lu",
"1p2ra",
"1p2re",
"1p2ro",
"1p2ri",
"1p2ru",
"1t2ra",
"1t2re",
"1t2ro",
"1t2ri",
"1t2ru",
// We now avoid some problematic breaks.
"su2b2r",
"su2b2l",
""
];
return {
patterns: patterns,
exceptions: hyphenation
};
});
|
import React from 'react';
import { shallow } from 'enzyme';
// app
import NavHeaderComponent from '../NavHeader.component';
const props = {
scene: {},
getScreenDetails: () => ({ options: {} }),
onToggleMenu: jest.fn()
};
test('NavHeader should render correctly', () => {
const wrapper = shallow(<NavHeaderComponent {...props} />);
expect(wrapper).toMatchSnapshot();
});
|
$(document).ready(function () {
$("#second").hide();
$("#third").hide();
$("#forth").hide();
//butttons at home
$("#firstb").click(function () {
$("#first").toggle();
});
$("#secondb").click(function () {
$("#second").toggle();
});
$("#thirdb").click(function () {
$("#third").toggle();
});
$("#forthb").click(function () {
$("#forth").toggle();
});
$(".searchimg").mouseover(function(){
$(this).css("opacity", "1.0");
});
$(".searchimg").mouseleave(function(){
$(this).css("opacity", "0.8");
});
});
|
/**
* Fx.Scroll.js
* @author : Agile Diagnosis
* @contributors : Boris Cherny <boris@agilediagnosis.com>
* @created : 2012-02-14
* @description : Scrolling functionality for Fx.js. Uses GPU-accelerated
* 3D transforms while properly updating scrollLeft and scrollTop.
* @requires : Fx.js
* @version : 0.1.0
*/
Fx.Scroll = (function(){
'use strict';
return function (element, direction) {
var self = this;
var isHorizontal = direction === 'horizontal';
var property = 'scroll' + (isHorizontal ? 'Left' : 'Top');
var oldScroll = 0;
var fxScroll = new Fx(element.parentNode, property);
var fxTranslate = new Fx(element, 'translate3d', {
animationStart: function() {
oldScroll = fxScroll.get()[0];
fxTranslate.set.apply(fxTranslate, getMatrix(oldScroll));
fxScroll.set(0);
},
animationEnd: function() {
var newScroll = fxTranslate.get()[isHorizontal ? 0 : 1];
fxTranslate.set(0,0,0);
fxScroll.set(-newScroll);
}
});
var set = function(x) {
fxTranslate.set.apply(this, getMatrix(x));
};
var to = function(x) {
fxTranslate.to.apply(this, getMatrix(x));
};
var getMatrix = function(x) {
return isHorizontal ? [-x, 0, 0] : [0, -x, 0];
};
// public API
self.set = set;
self.to = to;
};
})(); |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'toolbarswitch', 'eu', {
toolbarswitch: 'Switch toolbar'
});
|
describe('manualRowResize', function () {
var id = 'test';
var defaultRowHeight = 22;
beforeEach(function () {
this.$container = $('<div id="' + id + '"></div>').appendTo('body');
});
afterEach(function () {
if (this.$container) {
destroy();
this.$container.remove();
}
});
function resizeRow(displayedRowIndex, height) {
var $container = spec().$container;
var $th = $container.find('tbody tr:eq(' + displayedRowIndex + ') th:eq(0)');
$th.simulate('mouseover');
var $resizer = $container.find('.manualRowResizer');
var resizerPosition = $resizer.position();
$resizer.simulate('mousedown',{
clientY: resizerPosition.top
});
var delta = height - $th.height() - 2;
if (delta < 0) {
delta = 0;
}
$resizer.simulate('mousemove',{
clientY: resizerPosition.top + delta
});
$resizer.simulate('mouseup');
}
it("should change row heights at init", function () {
handsontable({
rowHeaders: true,
manualRowResize: [50, 40, 100]
});
expect(rowHeight(this.$container, 0)).toEqual(50);
expect(rowHeight(this.$container, 1)).toEqual(40);
expect(rowHeight(this.$container, 2)).toEqual(100);
});
it("should change the default row height with updateSettings", function () {
handsontable({
manualRowResize: true
});
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
expect(rowHeight(this.$container, 1)).toEqual(defaultRowHeight);
expect(rowHeight(this.$container, 2)).toEqual(defaultRowHeight);
updateSettings({
manualRowResize: [60, 50, 80]
});
expect(rowHeight(this.$container, 0)).toEqual(60);
expect(rowHeight(this.$container, 1)).toEqual(50);
expect(rowHeight(this.$container, 2)).toEqual(80);
});
it("should change the row height with updateSettings", function () {
handsontable({
manualRowResize: [60, 50, 80]
});
expect(rowHeight(this.$container, 0)).toEqual(60);
expect(rowHeight(this.$container, 1)).toEqual(50);
expect(rowHeight(this.$container, 2)).toEqual(80);
updateSettings({
manualRowResize: [30, 80, 100]
});
expect(rowHeight(this.$container, 0)).toEqual(30);
expect(rowHeight(this.$container, 1)).toEqual(80);
expect(rowHeight(this.$container, 2)).toEqual(100);
});
it("should reset row height", function () {
handsontable({
manualRowResize: true
});
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
expect(rowHeight(this.$container, 1)).toEqual(defaultRowHeight);
expect(rowHeight(this.$container, 2)).toEqual(defaultRowHeight);
updateSettings({
manualRowResize: true
});
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
expect(rowHeight(this.$container, 1)).toEqual(defaultRowHeight);
expect(rowHeight(this.$container, 2)).toEqual(defaultRowHeight);
});
it("should trigger afterRowResize event after row height changes", function () {
var afterRowResizeCallback = jasmine.createSpy('afterRowResizeCallback');
handsontable({
data: createSpreadsheetData(5, 5),
rowHeaders: true,
manualRowResize: true,
afterRowResize: afterRowResizeCallback
});
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
resizeRow(0, 100);
expect(afterRowResizeCallback).toHaveBeenCalledWith(0, 100, void 0, void 0, void 0, void 0);
expect(rowHeight(this.$container, 0)).toEqual(100);
});
it("should not trigger afterRowResize event if row height does not change (delta = 0)", function () {
var afterRowResizeCallback = jasmine.createSpy('afterRowResizeCallback');
handsontable({
data: createSpreadsheetData(5, 5),
rowHeaders: true,
manualRowResize: true,
afterRowResize: afterRowResizeCallback
});
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
resizeRow(0, defaultRowHeight);
expect(afterRowResizeCallback).not.toHaveBeenCalled();
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
});
it("should not trigger afterRowResize event after if row height does not change (no mousemove event)", function () {
var afterRowResizeCallback = jasmine.createSpy('afterRowResizeCallback');
handsontable({
data: createSpreadsheetData(5, 5),
rowHeaders: true,
manualRowResize: true,
afterRowResize: afterRowResizeCallback
});
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
var $th = this.$container.find('tbody tr:eq(0) th:eq(0)');
$th.simulate('mouseover');
var $resizer = this.$container.find('.manualRowResizer');
var resizerPosition = $resizer.position();
// var mouseDownEvent = new $.Event('mousedown', {pageY: resizerPosition.top});
$resizer.simulate('mousedown',{
clientY: resizerPosition.top
});
$resizer.simulate('mouseup');
expect(afterRowResizeCallback).not.toHaveBeenCalled();
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
});
it("should trigger an afterRowResize after row size changes, after double click", function () {
var afterRowResizeCallback = jasmine.createSpy('afterRowResizeCallback');
handsontable({
data: createSpreadsheetData(5, 5),
rowHeaders: true,
manualRowResize: true,
afterRowResize: afterRowResizeCallback
});
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
var $th = this.$container.find('tbody tr:eq(2) th:eq(0)');
$th.simulate('mouseover');
var $resizer = this.$container.find('.manualRowResizer');
var resizerPosition = $resizer.position();
$resizer.simulate('mousedown',{
clientY: resizerPosition.top
});
$resizer.simulate('mouseup');
$resizer.simulate('mousedown',{
clientY:resizerPosition.top
});
$resizer.simulate('mouseup');
waitsFor(function() {
return afterRowResizeCallback.calls.length > 0;
}, 'Row resize', 500);
runs(function () {
expect(afterRowResizeCallback.calls.length).toEqual(1);
expect(afterRowResizeCallback.calls[0].args[0]).toEqual(2);
expect(afterRowResizeCallback.calls[0].args[1]).toEqual(defaultRowHeight + 1);
expect(rowHeight(this.$container, 2)).toEqual(defaultRowHeight);
});
});
it("should not trigger afterRowResize event after if row height does not change (no dblclick event)", function () {
var afterRowResizeCallback = jasmine.createSpy('afterRowResizeCallback');
handsontable({
data: createSpreadsheetData(5, 5),
rowHeaders: true,
manualRowResize: true,
afterRowResize: afterRowResizeCallback
});
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
var $th = this.$container.find('tbody tr:eq(2) th:eq(0)');
$th.simulate('mouseover');
var $resizer = this.$container.find('.manualRowResizer');
var resizerPosition = $resizer.position();
$resizer.simulate('mousedown',{
clientY:resizerPosition.top
});
$resizer.simulate('mouseup');
expect(afterRowResizeCallback).not.toHaveBeenCalled();
expect(rowHeight(this.$container, 0)).toEqual(defaultRowHeight);
})
it("should display the resize handle in the correct place after the table has been scrolled", function () {
handsontable({
data: createSpreadsheetData(20, 20),
rowHeaders: true,
manualRowResize: true,
height: 100,
width: 200
});
var $rowHeader = this.$container.find('.ht_clone_left tbody tr:eq(2) th:eq(0)');
$rowHeader.simulate("mouseover");
var $handle = this.$container.find('.manualRowResizer');
$handle[0].style.background = "red";
expect($rowHeader.offset().left).toEqual($handle.offset().left);
expect($rowHeader.offset().top + $rowHeader.height() - 5).toEqual($handle.offset().top);
this.$container.scrollTop(200);
this.$container.scroll();
$rowHeader = this.$container.find('.ht_clone_left tbody tr:eq(2) th:eq(0)');
$rowHeader.simulate("mouseover");
expect($rowHeader.offset().left).toEqual($handle.offset().left);
expect($rowHeader.offset().top + $rowHeader.height() - 5).toEqual($handle.offset().top);
});
});
|
var path = require('path');
module.exports = function (grunt) {
var helpers = require('./external/amber-dev/lib/helpers');
grunt.loadTasks('./internal/grunt-tasks');
grunt.loadTasks('./external/amber-dev/tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-execute');
grunt.registerTask('default', ['peg', 'build:all']);
grunt.registerTask('build:all', ['amberc:amber', 'build:cli', 'amberc:dev']);
grunt.registerTask('build:cli', ['amberc:cli', 'requirejs:cli']);
grunt.registerTask('test', ['amdconfig:amber', 'requirejs:test_runner', 'execute:test_runner', 'clean:test_runner']);
grunt.registerTask('devel', ['amdconfig:amber']);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner: '/*!\n <%= pkg.title || pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> \n License: <%= pkg.license.type %> \n*/\n'
},
peg: {
parser: {
options: {
cache: true,
export_var: '$globals.SmalltalkParser'
},
src: 'support/parser.pegjs',
dest: 'support/parser.js'
}
},
amdconfig: {amber: {dest: 'config.js'}},
amberc: {
options: {
amber_dir: process.cwd(),
closure_jar: ''
},
amber: {
output_dir: 'src',
src: ['src/Kernel-Objects.st', 'src/Kernel-Classes.st', 'src/Kernel-Methods.st', 'src/Kernel-Collections.st',
'src/Kernel-Infrastructure.st', 'src/Kernel-Exceptions.st', 'src/Kernel-Announcements.st',
'src/Platform-Services.st', 'src/Platform-ImportExport.st', 'src/Platform-Browser.st',
'src/Compiler-Exceptions.st', 'src/Compiler-Core.st', 'src/Compiler-AST.st',
'src/Compiler-IR.st', 'src/Compiler-Inlining.st', 'src/Compiler-Semantic.st', 'src/Compiler-Interpreter.st',
'src/SUnit.st',
'src/Kernel-Tests.st', 'src/Compiler-Tests.st', 'src/SUnit-Tests.st'
],
jsGlobals: ['navigator']
},
cli: {
output_dir: 'external/amber-cli/src',
src: ['external/amber-cli/src/AmberCli.st'],
libraries: [
'Compiler-Exceptions', 'Compiler-Core', 'Compiler-AST',
'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic', 'Compiler-Interpreter', 'parser',
'SUnit', 'Platform-ImportExport',
'Kernel-Tests', 'Compiler-Tests', 'SUnit-Tests'
],
amd_namespace: 'amber_cli'
},
dev: {
output_dir: 'external/amber-dev/lib',
src: ['external/amber-dev/lib/NodeTestRunner.st'],
amd_namespace: 'amber_devkit'
}
},
requirejs: {
cli: {
options: {
mainConfigFile: "config.js",
rawText: {
"app": "(" + function () {
define(["amber/devel", "amber_cli/AmberCli"], function (amber) {
amber.initialize();
amber.globals.AmberCli._main();
});
} + "());"
},
pragmas: {
// none, for repl to have all info
},
include: ['config-node', 'app'],
insertRequire: ['app'],
optimize: "none",
wrap: helpers.nodeWrapperWithShebang,
out: "external/amber-cli/support/amber-cli.js"
}
},
test_runner: {
options: {
mainConfigFile: "config.js",
rawText: {
"app": "(" + function () {
define(["amber/devel", "amber_devkit/NodeTestRunner"], function (amber) {
amber.initialize();
amber.globals.NodeTestRunner._main();
});
} + "());"
},
paths: {"amber_devkit": helpers.libPath},
pragmas: {
// none, amber tests test contexts as well as eg. class copying which needs sources
},
include: ['config-node', 'app'],
insertRequire: ['app'],
optimize: "none",
wrap: helpers.nodeWrapperWithShebang,
out: "test_runner.js"
}
}
},
execute: {
test_runner: {
src: ['test_runner.js']
}
},
clean: {
test_runner: ['test_runner.js']
},
jshint: {
amber: ['src/*.js', 'support/[^p]*.js'],
cli: ['external/amber-cli/src/*.js', 'external/amber-cli/support/*.js'],
dev: ['external/amber-dev/lib/*.js'],
grunt: ['Gruntfile.js', 'internal/grunt-tasks/*.js', 'external/amber-dev/tasks/*.js']
}
});
};
|
// app/models/user.js
// load the things we need
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var userSchema = mongoose.Schema({
local : {
userId : String,
email : String,
userType : String,
password : String,
expireDate : Date,
createDate : Date,
firstName : String,
lastName : String,
phone : String,
zipcode : String,
city : String,
state : String,
checkedOutCopy : Number,
availableCopy : Number,
balance : Number,
address : String
}
});
// methods ======================
// generating a hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);
|
var mocha = require('mocha');
var expect = require('chai').expect;
var Immutable = require('immutable');
var Measures = require('../../../server/client/reducers/Measures');
describe('Measures Reducer', function(){
it('should create an immutable map from an object', function () {
var action = {};
action.measures = {
a: {
kind : 'qualitative',
},
b: {
kind : 'list',
}
};
action.type = 'SET_MEASURES';
var state = Measures(null, action);
expect(state.getIn(['a', 'kind'])).to.eql('qualitative');
});
it('should create a new measure', function () {
var action = {};
action.measures = {
a: {
kind: 'list'
}
};
action.type = 'SET_MEASURES';
var state = Measures(null, action);
var action = {};
action.measureId = 'b';
action.type = 'CREATE_MEASURE';
state = Measures(state, action);
expect(state.get('b')).to.not.eql(undefined);
});
it('should set kind', function () {
var action = {};
action.measures = {
a: {
kind: 'list'
}
};
action.type = 'SET_MEASURES';
var state = Measures(null, action);
var action = {};
action.kind = 'qualitative';
action.type = 'SET_KIND';
action.measureId = 'a';
var state = Measures(state, action);
expect(state.getIn(['a', 'kind'])).to.eql('qualitative');
});
it('should set unit', function () {
var action = {};
action.measures = {
a: {
kind: 'list'
}
};
action.type = 'SET_MEASURES';
var state = Measures(null, action);
var action = {};
action.unit = 'something';
action.type = 'SET_UNIT';
action.measureId = 'a';
var state = Measures(state, action);
expect(state.getIn(['a', 'unit'])).to.eql('something');
});
it('should set scale', function () {
var action = {};
action.measures = {
a: {
kind: 'list'
}
};
action.type = 'SET_MEASURES';
var state = Measures(null, action);
var action = {};
action.scale = 5;
action.type = 'SET_SCALE';
action.measureId = 'a';
var state = Measures(state, action);
expect(state.getIn(['a', 'scale'])).to.eql(5);
});
it('should add items to list', function () {
var action = {};
action.measures = {
a: {
kind: 'list',
list: [],
}
};
action.type = 'SET_MEASURES';
var state = Measures(null, action);
expect(state.getIn(['a', 'list']).size).to.eql(0);
var action = {};
action.item = 'hello';
action.measureId = 'a';
action.type = 'ADD_LIST_ITEM';
var state = Measures(state, action);
expect(state.getIn(['a', 'list']).size).to.eql(1);
});
it('should remove items from list', function () {
var action = {};
action.measures = {
a: {
kind: 'list',
list: ['hi', 'world'],
}
};
action.type = 'SET_MEASURES';
var state = Measures(null, action);
expect(state.getIn(['a', 'list']).size).to.eql(2);
var action = {};
action.item = 'world';
action.measureId = 'a';
action.type = 'REMOVE_LIST_ITEM';
var state = Measures(state, action);
expect(state.getIn(['a', 'list']).size).to.eql(1);
});
it('should set Measure Names', function () {
var action = {};
action.measures = {
a: {
kind: 'list',
list: ['hi', 'world'],
name: null
}
};
action.type = 'SET_MEASURES';
var state = Measures(null, action);
expect(state.getIn(['a', 'name'])).to.eql(null);
var action = {};
action.name = 'porcupines';
action.measureId = 'a';
action.type = 'SET_MEASURE_NAME';
var state = Measures(state, action);
expect(state.getIn(['a', 'name'])).to.eql('porcupines');
});
});
|
var Slide = require('../../../src/remark/models/slide');
describe('Slide', function () {
describe('properties', function () {
it('should be extracted', function () {
var slide = new Slide(1, {
source: '',
properties: {a: 'b', c: 'd'}
});
slide.properties.should.have.property('a', 'b');
slide.properties.should.have.property('c', 'd');
slide.source.should.equal('');
});
});
describe('inheritance', function () {
it('should inherit properties, source and notes', function () {
var template = new Slide(1, {
source: 'Some content.',
properties: {prop1: 'val1'},
notes: 'template notes'
})
, slide = new Slide(2, {
source: 'More content.',
properties: {prop2: 'val2'},
notes: 'slide notes'
}, template);
slide.properties.should.have.property('prop1', 'val1');
slide.properties.should.have.property('prop2', 'val2');
slide.source.should.equal('Some content.More content.');
slide.notes.should.equal('template notes\n\nslide notes');
});
it('should not inherit name property', function () {
var template = new Slide(1, {
source: 'Some content.',
properties: {name: 'name'}
})
, slide = new Slide(1, {source: 'More content.'}, template);
slide.properties.should.not.have.property('name');
});
it('should not inherit layout property', function () {
var template = new Slide(1, {
source: 'Some content.',
properties: {layout: true}
})
, slide = new Slide(1, {source: 'More content.'}, template);
slide.properties.should.not.have.property('layout');
});
it('should aggregate class property value', function () {
var template = new Slide(1, {
source: 'Some content.',
properties: {'class': 'a'}
})
, slide = new Slide(1, {
source: 'More content.',
properties: {'class': 'b'}
}, template);
slide.properties.should.have.property('class', 'a, b');
});
it('should not expand regular properties when inheriting template', function () {
var template = new Slide(1, {
source: '{{name}}',
properties: {name: 'a'}
})
, slide = new Slide(1, {
source: '',
properites: {name: 'b'}
}, template);
slide.source.should.equal('{{name}}');
});
});
describe('variables', function () {
it('should be expanded to matching properties', function () {
var slide = new Slide(1, {
source: 'prop1 = {{ prop1 }}',
properties: {prop1: 'val1'}
});
slide.expandVariables();
slide.source.should.equal('prop1 = val1');
});
it('should ignore escaped variables', function () {
var slide = new Slide(1, {
source: 'prop1 = \\{{ prop1 }}',
properties: {prop1: 'val1'}
});
slide.expandVariables();
slide.source.should.equal('prop1 = {{ prop1 }}');
});
it('should ignore undefined variables', function () {
var slide = new Slide(1, {source: 'prop1 = {{ prop1 }}'});
slide.expandVariables();
slide.source.should.equal('prop1 = {{ prop1 }}');
});
});
});
|
var mod = require('./module')
console.log(mod())
|
export { default } from 'ember-magma/components/magma-tabs-list-item';
|
/**
* Created by j.calabrese on 8/19/15.
*/
jest.dontMock('../js/utils/firebase-utils');
describe('firebase-utils', function () {
it('convert object with 4 objects to array with 4 items', function () {
var FirebaseUtils = require('../js/utils/firebase-utils');
//var jsonObject = "{'10923': {name: 'Domaine Rapet', year: '2012'}, '10984': {name: 'Domaine Calab', year: '2009'}, '10981': {name: 'Domaine Debroeck', year: '2003'}}";
var jsonObject = '{"-Jx43VqHjUsCbfOgDX3N":{"domain":"sdfsdfsdf","number":"9","text":"","type":"red","year":"2011"},"-Jx46poh2t9oopdC6GuX":{"domain":"Domaine Rapet","number":"8","text":"","type":"red","year":"2018"},"-Jx47e0wDMpeLZ12Sfra":{"domain":"fsdfdf","number":"67","text":"fdsfsdfsdf","type":"red","year":"2011"},"-Jx47u11tsrUncrCVl68":{"domain":"Domaine Beaune","number":"12","text":"REST","type":"red","year":"2017"}}';
var listObjects = JSON.parse(jsonObject);
var result = [
{"domain":"sdfsdfsdf","number":"9","text":"","type":"red","year":"2011"},
{"domain":"Domaine Rapet","number":"8","text":"","type":"red","year":"2018"},
{"domain":"fsdfdf","number":"67","text":"fdsfsdfsdf","type":"red","year":"2011"},
{"domain":"Domaine Beaune","number":"12","text":"REST","type":"red","year":"2017"}
];
var expected = FirebaseUtils.convertToArray(listObjects);
expect(expected.length).toBe(result.length);
expect(expected[0].domain).toBe(result[0].domain);
expect(expected[0].number).toBe(result[0].number);
expect(expected[2].domain).toBe(result[2].domain);
expect(expected[2].number).toBe(result[2].number);
});
}); |
const _ = {}
_.init = function(){
}
module.exports = {
init : () => _.init,
test : () => _
} |
import VideoCoverFallback from '../VideoCoverFallback';
import React from 'react';
import { shallow, mount } from 'enzyme';
describe('VideoCoverFallback', () => {
it('should update container ratio when mounted', () => {
const spy = jest.fn();
class WithSpy extends VideoCoverFallback {
constructor(props) {
super(props);
this.updateContainerRatio = spy;
}
}
mount(<WithSpy />);
expect(spy).toBeCalled();
});
it('should call onFallbackDidMount prop when mounted', () => {
const spy = jest.fn();
mount(<VideoCoverFallback onFallbackDidMount={spy} />);
expect(spy).toBeCalled();
});
it('should pass this.updateContainerRatio as parameter in onFallbackWillUnmount', () => {
let resizeNotifier;
const wrapper = mount(<VideoCoverFallback
onFallbackDidMount={result => {
resizeNotifier = result;
}}
/>);
expect(resizeNotifier).toEqual(wrapper.instance().updateContainerRatio);
});
it('should initialize window-resize eventlisteners if props.remeasureOnWindowResize is set', () => {
const spy = jest.fn();
class WithSpy extends VideoCoverFallback {
constructor(props) {
super(props);
this.initEventListeners = spy;
}
}
mount(<WithSpy remeasureOnWindowResize />);
expect(spy).toBeCalled();
});
it('should NOT initialize window-resize eventlisteners if props.remeasureOnWindowResize is not set', () => {
const spy = jest.fn();
class WithSpy extends VideoCoverFallback {
constructor(props) {
super(props);
this.initEventListeners = spy;
}
}
mount(<WithSpy />);
expect(spy).not.toBeCalled();
});
it('should remove eventlisteners before unmount', () => {
const spy = jest.fn();
class WithSpy extends VideoCoverFallback {
constructor(props) {
super(props);
this.removeEventListeners = spy;
}
}
const wrapper = mount(<WithSpy />);
wrapper.unmount();
expect(spy).toBeCalled();
});
it('should add/remove eventlisteners if props.remeasureOnWindowResize changes', () => {
const addSpy = jest.fn();
const removeSpy = jest.fn();
class WithSpy extends VideoCoverFallback {
constructor(props) {
super(props);
this.initEventListeners = addSpy;
this.removeEventListeners = removeSpy;
}
}
const wrapper = mount(<WithSpy />);
expect(addSpy).not.toBeCalled();
expect(removeSpy).not.toBeCalled();
wrapper.setProps({ remeasureOnWindowResize: true });
expect(addSpy).toBeCalled();
expect(removeSpy).not.toBeCalled();
wrapper.setProps({ remeasureOnWindowResize: false });
expect(addSpy).toBeCalled();
expect(removeSpy).toBeCalled();
});
it('should render a video tag inside a container-div', () => {
const wrapper = shallow(<VideoCoverFallback />);
expect(wrapper.find('div')).toExist();
expect(wrapper.find('div video')).toExist();
});
it('should pass props.className to the container-div', () => {
const wrapper = shallow(<VideoCoverFallback className="some-classname" />);
expect(wrapper).toHaveClassName('some-classname');
});
it('should invoke updateVideoRatio on loadedData media event', () => {
const spy = jest.fn();
class WithSpy extends VideoCoverFallback {
constructor(props) {
super(props);
this.updateVideoRatio = spy;
}
}
const wrapper = shallow(<WithSpy />);
const video = wrapper.find('video');
video.simulate('loadedData', {
target: {
videoWidth: 50,
videoHeight: 50,
},
});
expect(spy).toBeCalledWith(50, 50);
});
it('should apply all props.videoOptions to the video tag', () => {
const wrapper = shallow(<VideoCoverFallback
videoOptions={{
src: 'http://some-video-url.mp4',
}}
/>);
expect(wrapper.find('video')).toHaveProp('src', 'http://some-video-url.mp4');
});
describe('container-styles', () => {
it('should apply props.style to the container-div', () => {
const wrapper = shallow(<VideoCoverFallback
style={{
backgroundColor: 'teal',
lineHeight: '100px',
}}
/>);
expect(wrapper).toHaveStyle('backgroundColor', 'teal');
expect(wrapper).toHaveStyle('lineHeight', '100px');
});
it('should set width and height to 100% by default', () => {
const wrapper = shallow(<VideoCoverFallback />);
expect(wrapper).toHaveStyle('height', '100%');
expect(wrapper).toHaveStyle('width', '100%');
});
it('should be possible to override width and height via props.style', () => {
const wrapper = shallow(<VideoCoverFallback style={{ width: '50%', height: '50%' }} />);
expect(wrapper).toHaveStyle('height', '50%');
expect(wrapper).toHaveStyle('width', '50%');
});
it('should set position relative and overflow: hidden', () => {
const wrapper = shallow(<VideoCoverFallback />);
expect(wrapper).toHaveStyle('position', 'relative');
expect(wrapper).toHaveStyle('overflow', 'hidden');
});
it('should not be possible to override position and overflow', () => {
const wrapper = shallow(<VideoCoverFallback
style={{
position: 'fixed',
overflow: 'scroll',
}}
/>);
expect(wrapper).toHaveStyle('position', 'relative');
expect(wrapper).toHaveStyle('overflow', 'hidden');
});
});
// todo: maybe use generated test-data for this?
describe('video-styles', () => {
it('should have width auto, height 100% if innerRatio > outerRatio', () => {
const wrapper = shallow(<VideoCoverFallback />);
wrapper.setState({
innerRatio: 5,
outerRatio: 3,
});
expect(wrapper.find('video')).toHaveStyle('width', 'auto');
expect(wrapper.find('video')).toHaveStyle('height', '100%');
});
it('should have width 100%, height auto if innerRatio <= outerRatio', () => {
const wrapper = shallow(<VideoCoverFallback />);
wrapper.setState({
innerRatio: 3,
outerRatio: 5,
});
expect(wrapper.find('video')).toHaveStyle('width', '100%');
expect(wrapper.find('video')).toHaveStyle('height', 'auto');
});
});
describe('updateContainerRatio()', () => {
it('should set state.outerRatio to ratio of container width/height', () => {
const mockRef = {
getBoundingClientRect: () => {
const result = {
width: 4,
height: 5,
};
return result;
},
};
class WithRef extends VideoCoverFallback {
constructor(props) {
super(props);
this.containerRef = mockRef;
}
}
const wrapper = shallow(<WithRef />);
wrapper.instance().updateContainerRatio();
expect(wrapper).toHaveState('outerRatio', 4 / 5);
});
});
describe('updateVideoRatio()', () => {
it('should set state.innerRatio to ratio of video width/height', () => {
const wrapper = shallow(<VideoCoverFallback />);
expect(wrapper).toHaveState('innerRatio', undefined);
wrapper.instance().updateVideoRatio(4, 5);
expect(wrapper).toHaveState('innerRatio', 4 / 5);
});
});
});
|
var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; _Object$defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); _Object$defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
let Foo = /*#__PURE__*/_createClass(function Foo() {
"use strict";
_classCallCheck(this, Foo);
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:244dc32ed8898bce086968edc3d0d72d4d7e8be5bd8891f2f351a1518a116432
size 680
|
var ctracker;
function setup() {
// setup camera capture
var videoInput = createCapture(VIDEO);
videoInput.size(400, 300);
videoInput.position(0, 0);
// setup canvas
var cnv = createCanvas(400, 300);
cnv.position(0, 0);
// setup tracker
ctracker = new clm.tracker();
ctracker.init(pModel);
ctracker.start(videoInput.elt);
}
function draw() {
// get array of face marker positions [x, y] format
var positions = ctracker.getCurrentPosition();
if(positions.length > 0) {
var mouthH = positions[57][1] - positions[60][1];
var leftEyeH = positions[26][1] - positions[24][1];
var rightEyeH = positions[31][1] - positions[29][1];
var faceH = positions[7][1] - positions[33][1];
var mouthR = mouthH/faceH;
var leftEyeR = leftEyeH/faceH;
var rightEyeR = rightEyeH/faceH;
var t = leftEyeR > 0.075 ? "Let's party!" : "I'm sleepy.";
if (mouthR > 0.1) {
var u = new SpeechSynthesisUtterance(t);
speechSynthesis.speak(u);
} else {
speechSynthesis.cancel();
}
}
} |
import cookieProxy from 'appkit/utils/cookieProxy';
import auth from 'appkit/utils/auth';
import routeProxy from 'appkit/utils/routeProxy';
var ApplicationController = Ember.ObjectController.extend({
currentPathDidChange: function() {
Ember.currentPath = this.get('currentPath');
this.set('currentPath', this.get('currentPath'));
console.log('app.currentPath: ' + this.get('currentPath'));
}.observes('currentPath'),
loginModalMessage: function() {
return '您尚未登入,即將跳轉登入頁';
}.property(),
// 設定invoiceInterval跳窗按鈕
loginModalButton: [
Ember.Object.create({title: '確定', clicked: 'transitionToLogin'})
],
loadingData: function() {
return {
msg: '儲存中',
isMask: true,
isShow: false,
fadeInTime: 500,
fadeOutTime: 500,
delayTime: 0
};
}.property(),
didInsertElement: function() {
},
actions: {
// 導頁到login頁面
transitionToLogin: function() {
// 清除目前$.cookie並導頁到login頁面
auth.redirectForLogout();
this.send('hideLoginModal');
},
showGrowlNotifications: function(title, msg, type) {
var title = title || '';
var msg = msg || '';
var type = type || 'success';
console.log(type);
if (msg) {
Bootstrap.GNM.push(title, msg, type);
}
},
// 顯示Notification
showNotification: function(msg) {
console.log('showNotification');
var msg = msg || '欄位未通過驗證,無法送出';
Bootstrap.NM.push(msg, 'danger');
},
// 顯示未登入提示Modal
showLoginModal: function() {
console.log('into showLoginModal');
Bootstrap.ModalManager.show('loginModal');
},
// 隱藏未登入提示Modal
hideLoginModal: function() {
Bootstrap.ModalManager.hide('loginModal');
},
// 顯示login
showLoading: function(msg) {
this.set('loadingData.msg', msg);
this.set('loadingData.isShow', true);
},
// 隱藏login
hideLoading: function() {
this.set('loadingData.isShow', false);
}
}
});
export default ApplicationController; |
angular.module('roadmaps.factory', [])
.factory('RoadMapsFactory', function($http){
return {
};
}); |
import { EventEmitter } from 'events';
import qemuFactory from '../lib/qemu';
import rfbHandler from '../lib/rfb-handler';
import {
EV_STOP, EV_TIMER, RS_SESSION_EXPIRED,
EV_FRAME, EV_RESIZE, EV_KEYDOWN, EV_MOUSEMOVE,
} from '../constants/socket-events';
import {
x8664Executable, VM_MAX_SESSIONS, VM_MAX_TIME,
} from '../config/config';
const qemu = qemuFactory({ x8664Executable, VM_MAX_SESSIONS });
const vm = (emitter) => {
let timerInterval = undefined;
let rfb = undefined;
/*
isRunning: false,
port: undefined,
timer: VM_MAX_TIME,
os: {},
*/
let state = {};
function handleEvents(rfbEmitter, clientEmitter) {
rfbEmitter.on(EV_FRAME, frame => clientEmitter.emit(EV_FRAME, frame));
rfbEmitter.on(EV_RESIZE, rect => clientEmitter.emit(EV_RESIZE, rect));
clientEmitter.on(EV_KEYDOWN, keydown => rfbEmitter.emit(EV_KEYDOWN, keydown));
clientEmitter.on(EV_MOUSEMOVE, mousemove => rfbEmitter.emit(EV_MOUSEMOVE, mousemove));
}
function removeEvents(clientEmitter) {
clientEmitter.removeAllListeners(EV_KEYDOWN);
clientEmitter.removeAllListeners(EV_MOUSEMOVE);
}
function stop() {
if (state.isRunning) {
state.isRunning = false;
clearInterval(timerInterval);
rfb.stop();
qemu.stop(state.port);
}
removeEvents(emitter);
emitter.emit(EV_STOP);
}
function decrementTimer() {
state.timer--;
emitter.emit(EV_TIMER, { timer: state.timer });
if (state.timer <= 0) {
stop();
emitter.emit(EV_STOP, {
reason: RS_SESSION_EXPIRED,
});
}
}
function start(os) {
const port = qemu.start(os);
timerInterval = setInterval(decrementTimer, 1000);
state = {
...state,
isRunning: true,
timer: VM_MAX_TIME,
os,
port,
};
rfb = rfbHandler(port + 5900);
rfb.start();
handleEvents(rfb.emitter, emitter);
return state;
}
return {
start,
stop,
emitter,
};
};
const vmController = () => vm(Object.assign({}, EventEmitter.prototype));
export default vmController;
|
var negators = require('./negators.json');
module.exports = {
apply: function(tokens, cursor, tokenScore) {
if (cursor > 0) {
var prevtoken = tokens[cursor - 1];
if (negators[prevtoken]) {
tokenScore = -tokenScore;
}
}
return tokenScore;
}
};
|
import React from 'react'
import Icon from 'react-icon-base'
const IoAndroidMoreHorizontal = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m10.6 16.9c1.7 0 3.2 1.4 3.2 3.1s-1.5 3.1-3.2 3.1-3.1-1.4-3.1-3.1 1.4-3.1 3.1-3.1z m18.8 0c1.7 0 3.1 1.4 3.1 3.1s-1.4 3.1-3.1 3.1-3.1-1.4-3.1-3.1 1.4-3.1 3.1-3.1z m-9.4 0c1.7 0 3.1 1.4 3.1 3.1s-1.4 3.1-3.1 3.1-3.1-1.4-3.1-3.1 1.4-3.1 3.1-3.1z"/></g>
</Icon>
)
export default IoAndroidMoreHorizontal
|
/*
filedrag.js - HTML5 File Drag & Drop demonstration
Featured on SitePoint.com
Developed by Craig Buckler (@craigbuckler) of OptimalWorks.net
*/
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
// m.empty();
// m.innerHTML = msg + m.innerHTML;
m.innerHTML = msg;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
// Output(
// "<p>File information: <strong>" + file.name +
// "</strong> type: <strong>" + file.type +
// "</strong> size: <strong>" + file.size +
// "</strong> bytes</p>"
// );
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
//"<p><strong>" + file.name + ":</strong><br />" +
'<img class="img-responsive" src="' + e.target.result + '" />'
//'</p>'
);
}
reader.readAsDataURL(file);
}
// display text
// if (file.type.indexOf("text") == 0) {
// var reader = new FileReader();
// reader.onload = function(e) {
// Output(
// //"<p><strong>" + file.name + ":</strong></p><pre>" +
// //e.target.result.replace(/</g, "<").replace(/>/g, ">") +
// //"</pre>"
// );
// }
// reader.readAsText(file);
// }
}
// upload JPEG files
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
if (location.host.indexOf("sitepointstatic") >= 0) return
var xhr = new XMLHttpRequest();
if (xhr.upload && file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("upload").action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
//submitbutton.style.display = "none";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})(); |
import React from 'react'
import Icon from 'react-icon-base'
const FaBitbucket = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m22.7 19.2q0.2 1.4-1.1 2.2t-2.5 0.2q-0.9-0.4-1.2-1.3t0-1.9 1.1-1.3q0.8-0.4 1.6-0.2t1.5 0.8 0.6 1.5z m2.5-0.5q-0.3-2.4-2.6-3.7t-4.3-0.2q-1.5 0.6-2.3 1.9t-0.8 2.9q0.1 2 1.8 3.5t3.7 1.2q2-0.2 3.4-1.8t1.1-3.8z m5.3-12.1q-0.4-0.6-1.2-1t-1.3-0.5-1.6-0.3q-6.5-1-12.7 0.1-0.9 0.1-1.4 0.3t-1.3 0.4-1.1 1q0.7 0.6 1.7 1t1.7 0.5 1.9 0.3q5.1 0.6 10 0 1.4-0.2 2-0.3t1.6-0.5 1.7-1z m1.3 23.1q-0.2 0.6-0.4 1.7t-0.3 1.9-0.6 1.6-1.3 1.2q-1.9 1.1-4.2 1.6t-4.6 0.5-4.4-0.4q-1.1-0.2-1.9-0.4t-1.7-0.6-1.6-1-1.2-1.4q-0.5-2.1-1.2-6.5l0.1-0.3 0.4-0.2q5 3.3 11.3 3.3t11.3-3.3q0.5 0.1 0.6 0.5t-0.1 1-0.2 0.8z m4-21.4q-0.6 3.7-2.5 14.6-0.1 0.7-0.6 1.2t-0.9 0.9-1.3 0.7q-5.6 2.8-13.6 2-5.5-0.6-8.8-3.1-0.3-0.3-0.5-0.6t-0.4-0.8-0.2-0.8-0.1-0.8-0.2-0.8q-0.2-1.1-0.6-3.4t-0.6-3.6-0.5-3.3-0.5-3.5q0.1-0.6 0.4-1.1t0.7-0.8 1-0.7 1-0.5 1.1-0.4q2.8-1 7-1.4 8.4-0.9 15.1 1.1 3.4 1 4.8 2.7 0.3 0.5 0.3 1.1t-0.1 1.3z"/></g>
</Icon>
)
export default FaBitbucket
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {invokeGuardedCallbackAndCatchFirstError} from 'shared/ReactErrorUtils';
import invariant from 'shared/invariant';
export let getFiberCurrentPropsFromNode = null;
export let getInstanceFromNode = null;
export let getNodeFromInstance = null;
export function setComponentTree(
getFiberCurrentPropsFromNodeImpl,
getInstanceFromNodeImpl,
getNodeFromInstanceImpl,
) {
getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
getInstanceFromNode = getInstanceFromNodeImpl;
getNodeFromInstance = getNodeFromInstanceImpl;
if (__DEV__) {
if (!getNodeFromInstance || !getInstanceFromNode) {
console.error(
'EventPluginUtils.setComponentTree(...): Injected ' +
'module is missing getNodeFromInstance or getInstanceFromNode.',
);
}
}
}
let validateEventDispatches;
if (__DEV__) {
validateEventDispatches = function(event) {
const dispatchListeners = event._dispatchListeners;
const dispatchInstances = event._dispatchInstances;
const listenersIsArr = Array.isArray(dispatchListeners);
const listenersLen = listenersIsArr
? dispatchListeners.length
: dispatchListeners
? 1
: 0;
const instancesIsArr = Array.isArray(dispatchInstances);
const instancesLen = instancesIsArr
? dispatchInstances.length
: dispatchInstances
? 1
: 0;
if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) {
console.error('EventPluginUtils: Invalid `event`.');
}
};
}
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {function} listener Application-level callback
* @param {*} inst Internal component instance
*/
export function executeDispatch(event, listener, inst) {
const type = event.type || 'unknown-event';
event.currentTarget = getNodeFromInstance(inst);
invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
export function executeDispatchesInOrder(event) {
const dispatchListeners = event._dispatchListeners;
const dispatchInstances = event._dispatchInstances;
if (__DEV__) {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (let i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, dispatchListeners, dispatchInstances);
}
event._dispatchListeners = null;
event._dispatchInstances = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return {?string} id of the first dispatch execution who's listener returns
* true, or null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
const dispatchListeners = event._dispatchListeners;
const dispatchInstances = event._dispatchInstances;
if (__DEV__) {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (let i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchInstances[i])) {
return dispatchInstances[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchInstances)) {
return dispatchInstances;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
export function executeDispatchesInOrderStopAtTrue(event) {
const ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchInstances = null;
event._dispatchListeners = null;
return ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return {*} The return value of executing the single dispatch.
*/
export function executeDirectDispatch(event) {
if (__DEV__) {
validateEventDispatches(event);
}
const dispatchListener = event._dispatchListeners;
const dispatchInstance = event._dispatchInstances;
invariant(
!Array.isArray(dispatchListener),
'executeDirectDispatch(...): Invalid `event`.',
);
event.currentTarget = dispatchListener
? getNodeFromInstance(dispatchInstance)
: null;
const res = dispatchListener ? dispatchListener(event) : null;
event.currentTarget = null;
event._dispatchListeners = null;
event._dispatchInstances = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
*/
export function hasDispatches(event) {
return !!event._dispatchListeners;
}
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets, $ */
define(function (require, exports, module) {
"use strict";
// Brackets modules
var MultiRangeInlineEditor = brackets.getModule("editor/MultiRangeInlineEditor").MultiRangeInlineEditor,
EditorManager = brackets.getModule("editor/EditorManager"),
DocumentManager = brackets.getModule("document/DocumentManager"),
JSUtils = brackets.getModule("language/JSUtils"),
PerfUtils = brackets.getModule("utils/PerfUtils"),
ProjectManager = brackets.getModule("project/ProjectManager");
/**
* Return the token string that is at the specified position.
*
* @param hostEditor {!Editor} editor
* @param {!{line:Number, ch:Number}} pos
* @return {String} token string at the specified position
*/
function _getFunctionName(hostEditor, pos) {
var token = hostEditor._codeMirror.getTokenAt(pos, true);
// If the pos is at the beginning of a name, token will be the
// preceding whitespace or dot. In that case, try the next pos.
if (token.string.trim().length === 0 || token.string === ".") {
token = hostEditor._codeMirror.getTokenAt({line: pos.line, ch: pos.ch + 1}, true);
}
// Return valid function expressions only (function call or reference)
if (!((token.type === "variable") ||
(token.type === "variable-2") ||
(token.type === "property"))) {
return null;
}
return token.string;
}
/**
* @private
* For unit and performance tests. Allows lookup by function name instead of editor offset
* without constructing an inline editor.
*
* @param {!string} functionName
* @return {$.Promise} a promise that will be resolved with an array of function offset information
*/
function _findInProject(functionName) {
var result = new $.Deferred();
PerfUtils.markStart(PerfUtils.JAVASCRIPT_FIND_FUNCTION);
ProjectManager.getAllFiles()
.done(function (files) {
JSUtils.findMatchingFunctions(functionName, files)
.done(function (functions) {
PerfUtils.addMeasurement(PerfUtils.JAVASCRIPT_FIND_FUNCTION);
result.resolve(functions);
})
.fail(function () {
PerfUtils.finalizeMeasurement(PerfUtils.JAVASCRIPT_FIND_FUNCTION);
result.reject();
});
})
.fail(function () {
result.reject();
});
return result.promise();
}
/**
* @private
* For unit and performance tests. Allows lookup by function name instead of editor offset .
*
* @param {!Editor} hostEditor
* @param {!string} functionName
* @return {$.Promise} a promise that will be resolved with an InlineWidget
* or null if we're not going to provide anything.
*/
function _createInlineEditor(hostEditor, functionName) {
// Use Tern jump-to-definition helper, if it's available, to find InlineEditor target.
var helper = brackets._jsCodeHintsHelper;
if (helper === null) {
return null;
}
var result = new $.Deferred();
PerfUtils.markStart(PerfUtils.JAVASCRIPT_INLINE_CREATE);
var response = helper();
if (response.hasOwnProperty("promise")) {
response.promise.done(function (jumpResp) {
var resolvedPath = jumpResp.fullPath;
if (resolvedPath) {
// Tern doesn't always return entire function extent.
// Use QuickEdit search now that we know which file to look at.
var fileInfos = [];
fileInfos.push({name: jumpResp.resultFile, fullPath: resolvedPath});
JSUtils.findMatchingFunctions(functionName, fileInfos, true)
.done(function (functions) {
if (functions && functions.length > 0) {
var jsInlineEditor = new MultiRangeInlineEditor(functions);
jsInlineEditor.load(hostEditor);
PerfUtils.addMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE);
result.resolve(jsInlineEditor);
} else {
// No matching functions were found
PerfUtils.addMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE);
result.reject();
}
})
.fail(function () {
PerfUtils.addMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE);
result.reject();
});
} else { // no result from Tern. Fall back to _findInProject().
_findInProject(functionName).done(function (functions) {
if (functions && functions.length > 0) {
var jsInlineEditor = new MultiRangeInlineEditor(functions);
jsInlineEditor.load(hostEditor);
PerfUtils.addMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE);
result.resolve(jsInlineEditor);
} else {
// No matching functions were found
PerfUtils.addMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE);
result.reject();
}
}).fail(function () {
PerfUtils.finalizeMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE);
result.reject();
});
}
}).fail(function () {
PerfUtils.finalizeMeasurement(PerfUtils.JAVASCRIPT_INLINE_CREATE);
result.reject();
});
}
return result.promise();
}
/**
* This function is registered with EditorManager as an inline editor provider. It creates an inline editor
* when the cursor is on a JavaScript function name, finds all functions that match the name
* and shows (one/all of them) in an inline editor.
*
* @param {!Editor} editor
* @param {!{line:Number, ch:Number}} pos
* @return {$.Promise} a promise that will be resolved with an InlineWidget
* or null if we're not going to provide anything.
*/
function javaScriptFunctionProvider(hostEditor, pos) {
// Only provide a JavaScript editor when cursor is in JavaScript content
if (hostEditor.getModeForSelection() !== "javascript") {
return null;
}
// Only provide JavaScript editor if the selection is within a single line
var sel = hostEditor.getSelection();
if (sel.start.line !== sel.end.line) {
return null;
}
// Always use the selection start for determining the function name. The pos
// parameter is usually the selection end.
var functionName = _getFunctionName(hostEditor, sel.start);
if (!functionName) {
return null;
}
return _createInlineEditor(hostEditor, functionName);
}
// init
EditorManager.registerInlineEditProvider(javaScriptFunctionProvider);
PerfUtils.createPerfMeasurement("JAVASCRIPT_INLINE_CREATE", "JavaScript Inline Editor Creation");
PerfUtils.createPerfMeasurement("JAVASCRIPT_FIND_FUNCTION", "JavaScript Find Function");
// for unit tests only
exports.javaScriptFunctionProvider = javaScriptFunctionProvider;
exports._createInlineEditor = _createInlineEditor;
exports._findInProject = _findInProject;
});
|
module('pc.audio');
test('pc.audio.isSupported MP3', function () {
var url = '/test/file.mp3';
var a = new Audio();
equal(pc.AudioManager.isSupported(url), true);
equal(pc.AudioManager.isSupported(url, a), true);
});
test('pc.audio.isSupported ogg', function () {
var url = '/test/file.ogg';
var a = new Audio();
equal(pc.AudioManager.isSupported(url), true);
equal(pc.AudioManager.isSupported(url, a), true);
});
test('pc.audio.isSupported wav', function () {
var url = '/test/file.wav';
var a = new Audio();
equal(pc.AudioManager.isSupported(url), true);
equal(pc.AudioManager.isSupported(url, a), true);
});
test('pc.audio.isSupported other', function () {
var url = '/test/file.other';
var a = new Audio();
equal(pc.AudioManager.isSupported(url), false);
equal(pc.AudioManager.isSupported(url, a), false);
});
|
import Vue from 'vue';
import store from 'ee_else_ce/mr_notes/stores';
import initNotesApp from './init_notes';
import initDiffsApp from '../diffs';
import discussionCounter from '../notes/components/discussion_counter.vue';
import initDiscussionFilters from '../notes/discussion_filters';
import MergeRequest from '../merge_request';
import { resetServiceWorkersPublicPath } from '../lib/utils/webpack';
export default function initMrNotes() {
resetServiceWorkersPublicPath();
const mrShowNode = document.querySelector('.merge-request');
// eslint-disable-next-line no-new
new MergeRequest({
action: mrShowNode.dataset.mrAction,
});
initNotesApp();
// eslint-disable-next-line no-new
new Vue({
el: '#js-vue-discussion-counter',
name: 'DiscussionCounter',
components: {
discussionCounter,
},
store,
render(createElement) {
return createElement('discussion-counter');
},
});
initDiscussionFilters(store);
initDiffsApp(store);
}
|
var request = require('request-promise');
var Wsse = require('wsse');
var config = require('./config.json');
function checkInit(config) {
if (!config || !config.endpoint || !config.key || !config.secret) {
throw new Error('API not initialized. Make sure that the config file exists and has key, secret, and endpoint');
}
}
function generateAuthHeader(config) {
checkInit(config);
var token = new Wsse({
username: config.key,
password: config.secret
});
return {
'X-WSSE': 'UsernameToken ' + token.getWSSEHeader({nonceBase64: true})
};
};
function makeRequest(method, url, data) {
return request({
method: method,
baseUrl: config.endpoint,
url: url,
headers: generateAuthHeader(config)
});
}
// @todo: The function doesn't check for response status codes
function getFormData(caseFileId) {
return makeRequest('GET', `/casefiles/${caseFileId}`) // 1. Get the case File
.then(data => { // 2. Get documents
var caseFile = JSON.parse(data);
console.log(`Case file: ${caseFile.title}`);
var url = `casefiles/${caseFile.id}/documents`;
return makeRequest('GET', url);
})
.then(data => { // 3. Extract the document Ids
var documents = JSON.parse(data);
return documents.map(doc => doc.id);
})
.then(data => { // 4. Use the first document
// Get the form data for the first one
var documentId = data[0];
return makeRequest('GET', `/documents/${documentId}`);
})
.then(data => { // 5. Extract the meta Data from the document
var document = JSON.parse(data);
var metaData = document.metaData;
return metaData;
})
.then(metaData => { // 6. If we have json in the meta data, parse it
return JSON.parse(metaData);
});
}
let arg = process.argv;
let caseFileId = arg[arg.length-1].trim();
getFormData(caseFileId).then(data => {
console.log(data);
}).catch(data => {
console.log(`Response status: ${data.statusCode}`);
switch (data.statusCode) {
case 404:
console.log('Not found');
break;
case 403:
console.log('Access Denied');
break;
case 401:
console.log('Not authorized');
break;
case 400:
console.log('Bad request');
break;
default:
console.log('Unknown error');
break;
}
console.log(`Error: ${data.error}`);
});
|
"use strict";
/*
* Okta Events Endpoint
* http://developer.okta.com/docs/api/rest/events.html
*/
var NetworkAbstraction = require('./NetworkAbstraction.js');
module.exports = OktaAPIEvents;
/**
* Instantiate a new Okta API User helper with the given API token
* @param apiToken
* @param domain
* @param preview
* @constructor
*/
function OktaAPIEvents(apiToken, domain, preview)
{
if(apiToken == undefined || domain == undefined)
{
throw new Error("OktaAPI requires an API token and a domain");
}
this.domain = domain;
if(preview == undefined) this.preview = false;
else this.preview = preview;
this.request = new NetworkAbstraction(apiToken, domain, preview);
}
/*******************************************************************
***************** Events->Event Operations Start *******************
********************************************************************
*/
/**
* @method list Fetch a list of events from your Okta organization system log
* @param queryObj - used to search for events
* @param followLink - boolean, set to true to tell network abstraction to follow all pagination links and return result all at once.
* @param callback
*/
OktaAPIEvents.prototype.list = function(queryObj, followLink, callback) {
this.request.get("events", queryObj, followLink, callback);
}
/*******************************************************************
***************** Events->Event Operations End *********************
********************************************************************
*/
|
var makeDeque =
(function() { //begin IIFE
function makeDeque(values) { //begin factory
// These vars are private, local to scope of makeDeque,
// only accessible to functions defined in makeDeque
var array = values.slice(); //copy values
var absent = []; //list of missing elements
// Each function below is specific to one deque, with access to the private vars
function readmit(val) { //internal function only, do not attach to instances
var foundAt = absent.indexOf(val);
if (foundAt<0) return false; //foundAt is -1 if val not found
// else found; excise from absent array
absent.splice(foundAt,1);
return true;
}
// ---- Instance methods: -----
function top() {
if (array.length)
return array[array.length-1];
}
function bottom() {
if (array.length)
return array[0];
}
function pop() {
var val = array.pop();
if (val !== undefined)
absent.push(val);
return val;
}
function push(val) {
return readmit(val) && array.push(val);
}
function shift() {
var val = array.shift();
if (val !== undefined)
absent.push(val);
return val;
}
function unshift(val) {
return readmit(val) && array.unshift(val);
}
function sort(sortFn) {
//don't return:
array.sort(sortFn);
}
function map(convertFn) {
// This solution works but can be exploited
// (certain callbacks could change the array):
// return array.map(convertFn);
// Safer version: map a copy of array:
return array.slice().map(convertFn);
}
function cut() { //returns # elements moved from upper half to lower (0 if no change)
var fullLength = array.length;
var headLength = Math.ceil(fullLength / 2);
if (headLength == fullLength) // no tail, nothing to swap
return 0;
var tail = array.splice(headLength, fullLength); // removes tail from array
array = tail.concat(array); // swap tail and remaining head
return tail.length;
}
function shuffle() {
// Knuth-Fisher-Yates, modified from http://bost.ocks.org/mike/shuffle/
var end = array.length, temp, i;
// While there remain elements to shuffle…
while (end>1) {
// Pick a remaining element…
i = Math.floor(Math.random() * end--);
// And swap it with the current element.
temp = array[end];
array[end] = array[i];
array[i] = temp;
}
}
// Problem 4:
function render(container,renderItemFn) {
if (typeof container === 'string') {
container = document.getElementById(container);
}
if (!(container instanceof HTMLElement)) {
console.log('no such element');
return;
}
for (var i=0; i<array.length; ++i) {
var cell = document.createElement('div');
cell.className = 'dequeItem';
renderItemFn(array[i], cell);
container.appendChild(cell);
}
}
var deque = {// export each public method by linking an instance property to it:
sort : sort,
map : map,
cut : cut,
shuffle : shuffle,
top : top,
bottom : bottom,
push : push,
pop : pop,
shift : shift,
unshift : unshift,
render : render
};
return deque;
} //end factory makeDeque
return makeDeque;
})(); //end IIFE
if (typeof module !== "undefined") {
module.exports = makeDeque;
}
|
// This file is generated automatically by `scripts/build/fp.js`. Please, don't change it.
import fn from '../../isThursday/index.js'
import convertToFP from '../_lib/convertToFP/index.js'
var isThursday = convertToFP(fn, 1)
export default isThursday
|
var carousel = function(i, t) {
'undefined' == typeof t && (t = 0),
this.obj = $(i),
this.autoscrolldelay = t,
$(this.obj).find('.carousel-button-left').on('click', this.left.bind(this)),
$(this.obj).find('.carousel-button-right').on('click', this.right.bind(this)),
$(this.obj).on('mouseenter', this.mousein.bind(this)),
$(this.obj).on('mouseleave', this.mouseout.bind(this)), t && (this.interval = window.setInterval(this.right.bind(this), t)),
$(this.obj).find('.carousel-items').css('height', function(){
var max = 0;
$(this).children().each(function() {
max = Math.max( max, $(this).height() );
});
return max;
});
};
carousel.prototype = {
obj: null,
interval: null,
scrollSpeed: 200,
stop: !1,
mousein: function() {
window.clearTimeout(this.interval)
},
mouseout: function() {
this.autoscrolldelay && (this.interval = window.setInterval(this.right.bind(this), this.autoscrolldelay))
},
left: function() {
if (!this.stop) {
this.stop = !0;
var t = $(this.obj).find('.carousel-block').outerWidth();
$(this.obj).find('.carousel-items .carousel-block').eq(-1).prependTo($(this.obj).find('.carousel-items')), $(this.obj).find('.carousel-items').css({
left: '-' + t + 'px'
}), $(this.obj).find('.carousel-items').animate({
left: '0px'
}, this.scrollSpeed, function() {
this.stop = !1
}.bind(this))
}
},
right: function() {
if (!this.stop) {
this.stop = !0;
var t = $(this.obj).find('.carousel-block').outerWidth();
$(this.obj).find('.carousel-items').animate({
left: '-' + t + 'px'
}, this.scrollSpeed, function() {
$(this.obj).find('.carousel-items .carousel-block').eq(0).appendTo($(this.obj).find('.carousel-items')),
$(this.obj).find('.carousel-items').css({
left: '0px'
}),
this.stop = !1
}.bind(this))
}
}
}; |
const sharp = require('sharp');
const http = require('http');
const IMAGE_URL = 'http://blobby.wsimg.com/go/0296993c-cade-4ae8-8a65-b3172f22a3a0/6e14af04-904c-4654-936e-2bd7e6e08dd8.jpg';
function getImage() {
return new Promise((resolve, reject) => {
http.get(IMAGE_URL, res => {
if (res.statusCode !== 200) return void reject(new Error(`Invalid response: ${res.statusCode}`));
const chunks = [];
res.on('data', chunk => chunks.push(chunk));
res.on('end', () => {
resolve(Buffer.concat(chunks));
});
}).on('error', reject);
});
}
(async () => {
const imageData = await getImage();
const image = sharp(imageData);
// the blow options won't matter, including output format.. anything will result in:
// Error: VipsJpeg: Invalid SOS parameters for sequential JPEG
// VipsJpeg: out of order read at line 0
const saveData = await image
.withMetadata()
.resize(640, 480)
.toFormat('jpeg')
.toBuffer();
})();
|
jui.define("chart.brush.pie", [ "util.base", "util.math", "util.color" ], function(_, math, ColorUtil) {
/**
* @class chart.brush.pie
*
* implements pie brush
*
* @extends chart.brush.core
*/
var PieBrush = function() {
var self = this, textY = 3;
var g;
var cache_active = {};
this.setActiveEvent = function(pie, centerX, centerY, centerAngle) {
var dist = this.chart.theme("pieActiveDistance"),
tx = Math.cos(math.radian(centerAngle)) * dist,
ty = Math.sin(math.radian(centerAngle)) * dist;
pie.translate(centerX + tx, centerY + ty);
}
this.getFormatText = function(target, value, max) {
var key = target;
if(typeof(this.brush.format) == "function") {
return this.format(key, value, max);
} else {
if (!value) {
return key;
}
return key + ": " + this.format(value);
}
}
this.drawPie = function(centerX, centerY, outerRadius, startAngle, endAngle, color) {
var pie = this.chart.svg.group();
if (endAngle == 360) { // if pie is full size, draw a circle as pie brush
var circle = this.chart.svg.circle({
cx : centerX,
cy : centerY,
r : outerRadius,
fill : color,
stroke : this.chart.theme("pieBorderColor") || color,
"stroke-width" : this.chart.theme("pieBorderWidth")
});
pie.append(circle);
return pie;
}
var path = this.chart.svg.path({
fill : color,
stroke : this.chart.theme("pieBorderColor") || color,
"stroke-width" : this.chart.theme("pieBorderWidth")
});
// 바깥 지름 부터 그림
var obj = math.rotate(0, -outerRadius, math.radian(startAngle)),
startX = obj.x,
startY = obj.y;
// 시작 하는 위치로 옮김
path.MoveTo(startX, startY);
// outer arc 에 대한 지점 설정
obj = math.rotate(startX, startY, math.radian(endAngle));
pie.translate(centerX, centerY);
// arc 그림
path.Arc(outerRadius, outerRadius, 0, (endAngle > 180) ? 1 : 0, 1, obj.x, obj.y)
.LineTo(0, 0)
.ClosePath();
pie.append(path);
return pie;
}
this.drawPie3d = function(centerX, centerY, outerRadius, startAngle, endAngle, color) {
var pie = this.chart.svg.group(),
path = this.chart.svg.path({
fill : color,
stroke : this.chart.theme("pieBorderColor") || color,
"stroke-width" : this.chart.theme("pieBorderWidth")
});
// 바깥 지름 부터 그림
var obj = math.rotate(0, -outerRadius, math.radian(startAngle)),
startX = obj.x,
startY = obj.y;
// 시작 하는 위치로 옮김
path.MoveTo(startX, startY);
// outer arc 에 대한 지점 설정
obj = math.rotate(startX, startY, math.radian(endAngle));
pie.translate(centerX, centerY);
// arc 그림
path.Arc(outerRadius, outerRadius, 0, (endAngle > 180) ? 1 : 0, 1, obj.x, obj.y)
var y = obj.y + 10,
x = obj.x + 5,
targetX = startX + 5,
targetY = startY + 10;
path.LineTo(x, y);
path.Arc(outerRadius, outerRadius, 0, (endAngle > 180) ? 1 : 0, 0, targetX, targetY)
path.ClosePath();
pie.append(path);
return pie;
}
this.drawText = function(centerX, centerY, centerAngle, outerRadius, text) {
var c = this.chart,
dist = c.theme("pieOuterLineSize"),
r = outerRadius * c.theme("pieOuterLineRate"),
cx = centerX + (Math.cos(math.radian(centerAngle)) * outerRadius),
cy = centerY + (Math.sin(math.radian(centerAngle)) * outerRadius),
tx = centerX + (Math.cos(math.radian(centerAngle)) * r),
ty = centerY + (Math.sin(math.radian(centerAngle)) * r),
isLeft = (centerAngle + 90 > 180) ? true : false,
ex = (isLeft) ? tx - dist : tx + dist;
return c.svg.group({}, function() {
var path = c.svg.path({
fill: "transparent",
stroke: c.theme("pieOuterLineColor"),
"stroke-width": 0.7
});
path.MoveTo(cx, cy)
.LineTo(tx, ty)
.LineTo(ex, ty);
c.text({
"font-size": c.theme("pieOuterFontSize"),
"text-anchor": (isLeft) ? "end" : "start",
y: textY
}, text).translate(ex + (isLeft ? -3 : 3), ty);
});
}
this.drawUnit = function (index, data, g) {
var obj = this.axis.c(index);
var width = obj.width,
height = obj.height,
x = obj.x,
y = obj.y,
min = width;
if (height < min) {
min = height;
}
// center
var centerX = width / 2 + x,
centerY = height / 2 + y,
outerRadius = min / 2;
var target = this.brush.target,
active = this.brush.active,
all = 360,
startAngle = 0,
max = 0;
for (var i = 0; i < target.length; i++) {
max += data[target[i]];
}
for (var i = 0; i < target.length; i++) {
var value = data[target[i]],
endAngle = all * (value / max);
if (this.brush['3d']) {
var pie3d = this.drawPie3d(centerX, centerY, outerRadius, startAngle, endAngle, ColorUtil.darken(this.color(i), 0.5));
g.append(pie3d);
}
startAngle += endAngle;
}
startAngle = 0;
for (var i = 0; i < target.length; i++) {
var value = data[target[i]],
endAngle = all * (value / max),
centerAngle = startAngle + (endAngle / 2) - 90,
pie = this.drawPie(centerX, centerY, outerRadius, startAngle, endAngle, this.color(i));
// 설정된 키 활성화
if (active == target[i] || $.inArray(target[i], active) != -1) {
this.setActiveEvent(pie, centerX, centerY, centerAngle);
cache_active[centerAngle] = true;
}
// 활성화 이벤트 설정
if (this.brush.activeEvent != null) {
(function(p, cx, cy, ca) {
p.on(self.brush.activeEvent, function(e) {
if(!cache_active[ca]) {
self.setActiveEvent(p, cx, cy, ca);
cache_active[ca] = true;
} else {
p.translate(cx, cy);
cache_active[ca] = false;
}
});
p.attr({ cursor: "pointer" });
})(pie, centerX, centerY, centerAngle);
}
if (this.brush.showText) {
var text = this.getFormatText(target[i], value, max),
elem = this.drawText(centerX, centerY, centerAngle, outerRadius, text);
this.addEvent(elem, index, i);
g.append(elem);
}
self.addEvent(pie, index, i);
g.append(pie);
startAngle += endAngle;
}
}
this.drawBefore = function() {
g = this.chart.svg.group();
}
this.draw = function() {
this.eachData(function(i, data) {
this.drawUnit(i, data, g);
});
return g;
}
}
PieBrush.setup = function() {
return {
/** @cfg {Boolean} [clip=false] If the brush is drawn outside of the chart, cut the area. */
clip: false,
/** @cfg {Boolean} [showText=false] Set the text appear. */
showText: false,
/** @cfg {Function} [format=null] Returns a value from the format callback function of a defined option. */
format: null,
/** @cfg {Boolean} [3d=false] check 3d support */
"3d": false,
/** @cfg {String|Array} [active=null] Activates the pie of an applicable property's name. */
active: null,
/** @cfg {String} [activeEvent=null] Activates the pie in question when a configured event occurs (click, mouseover, etc). */
activeEvent: null
}
}
return PieBrush;
}, "chart.brush.core");
|
/**
* 读取所有md文件数据
*/
const fs = require('fs'); // 文件模块
const path = require('path'); // 路径模块
const chalk = require('chalk') // 命令行打印美化
const log = console.log
function readFileList (dir, filesList = []) {
const files = fs.readdirSync(dir);
files.forEach((item, index) => {
let filePath = path.join(dir, item);
const stat = fs.statSync(filePath);
if (stat.isDirectory() && item !== '.vuepress' && item !== '@pages') {
readFileList(path.join(dir, item), filesList); //递归读取文件
} else {
if (path.basename(dir) !== 'docs') { // 过滤docs目录级下的文件
const fileNameArr = path.basename(filePath).split('.')
let name = null, type = null;
if (fileNameArr.length === 2) { // 没有序号的文件
name = fileNameArr[0]
type = fileNameArr[1]
} else if (fileNameArr.length === 3) { // 有序号的文件
name = fileNameArr[1]
type = fileNameArr[2]
} else { // 超过两个‘.’的
log(chalk.yellow(`warning: 该文件 "${filePath}" 没有按照约定命名,将忽略生成相应数据。`))
return
}
if (type === 'md') { // 过滤非md文件
filesList.push({
name,
filePath
});
}
}
}
});
return filesList;
}
module.exports = readFileList;
|
define([
'bluebird',
'./adapters/objectWidget',
'./adapters/kbWidget',
'../merge'
], function (
Promise,
objectWidgetAdapter,
kbwidgetAdapter,
merge
) {
'use strict';
class WidgetManager {
constructor(config) {
// TODO: get rid of this?
// if (!config.runtime) {
// throw new Error('WidgetManager requires a runtime argument; pass as "runtime"')
// }
// this.runtime = config.runtime;
if (!config.baseWidgetConfig) {
throw new Error('WidgetManager requires a baseWidgetConfig argument; pass as "baseWidgetConfig"');
}
this.baseWidgetConfig = config.baseWidgetConfig;
this.widgets = {};
}
addWidget(widgetDef) {
if (widgetDef.id) {
widgetDef.name = widgetDef.id;
}
if (this.widgets[widgetDef.name]) {
throw new Error('Widget ' + widgetDef.name + ' is already registered');
}
/* TODO: validate the widget ...*/
this.widgets[widgetDef.name] = widgetDef;
}
getWidget(widgetId) {
return this.widgets[widgetId];
}
makeFactoryWidget(widget, config) {
return new Promise((resolve, reject) => {
var required = [widget.module];
if (widget.css) {
required.push('css!' + widget.module + '.css');
}
require(required,
(factory) => {
if (typeof factory === 'undefined') {
// TODO: convert to real Error object
reject({
message: 'Factory widget maker is undefined for ' + widget.module,
data: { widget: widget }
});
return;
}
if (factory.make === undefined) {
reject('Factory widget does not have a "make" method: ' + widget.name + ', ' + widget.module);
return;
}
try {
resolve(factory.make(config));
} catch (ex) {
reject(ex);
}
},
(error) => {
reject(error);
});
});
}
makeES6Widget(widget, config) {
return new Promise((resolve, reject) => {
var required = [widget.module];
if (widget.css) {
required.push('css!' + widget.module + '.css');
}
require(required,
(module) => {
let Widget;
if (module.Widget) {
Widget = module.Widget;
} else {
Widget = module;
}
if (typeof Widget === 'undefined') {
reject({
message: 'Widget class is undefined for ' + widget.module,
data: { widget: widget }
});
return;
}
try {
resolve(new Widget(config));
} catch (ex) {
reject(ex);
}
},
(error) => {
reject(error);
});
});
}
makeKbWidget(widget, config) {
return Promise.try(() => {
const configCopy = new merge.ShallowMerger({}).mergeIn(config).value();
configCopy.widget = {
module: widget.module,
jquery_object: (widget.config && widget.config.jqueryName) || config.jqueryName,
panel: config.panel,
title: widget.title
};
return new kbwidgetAdapter.KBWidgetAdapter(configCopy);
});
}
makeObjectWidget(widget, config) {
return Promise.try(() => {
const configCopy = new merge.ShallowMerger({}).mergeIn(config).value();
configCopy.widgetDef = widget;
configCopy.initConfig = config;
const x = new objectWidgetAdapter.ObjectWidgetAdapter(configCopy);
return x;
});
}
validateWidget(widget, name) {
var message;
if (typeof widget !== 'object') {
message = 'Invalid widget after making: ' + name;
}
if (message) {
console.error(message);
console.error(widget);
throw new Error(message);
}
}
makeWidget(widgetName, config) {
const widgetDef = this.widgets[widgetName];
if (!widgetDef) {
throw new Error('Widget ' + widgetName + ' not found');
}
let widgetPromise;
const configCopy = new merge.DeepMerger({}).mergeIn(config).value();
const widgetConfig = new merge.DeepMerger(configCopy).mergeIn(this.baseWidgetConfig).value();
config = config || {};
// config.runtime = this.runtime;
// TODO: this is not wonderful...
// config =
// How we create a widget depends on what type it is.
switch (widgetDef.type) {
case 'factory':
widgetPromise = this.makeFactoryWidget(widgetDef, widgetConfig);
break;
case 'es6':
widgetPromise = this.makeES6Widget(widgetDef, widgetConfig);
break;
case 'object':
widgetPromise = this.makeObjectWidget(widgetDef, widgetConfig);
break;
case 'kbwidget':
widgetPromise = this.makeKbWidget(widgetDef, widgetConfig);
break;
default:
throw new Error('Unsupported widget type ' + widgetDef.type);
}
return widgetPromise
.then((widget) => {
this.validateWidget(widget, widgetName);
return widget;
});
}
}
return {WidgetManager};
}); |
import {
Form,
Select,
InputNumber,
DatePicker,
Switch,
Slider,
Button
} from 'antd'
const FormItem = Form.Item
const Option = Select.Option
export default () => (
<div style={{ marginTop: 100 }}>
<Form layout='horizontal'>
<FormItem
label='Input Number'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<InputNumber
size='large'
min={1}
max={10}
style={{ width: 100 }}
defaultValue={3}
name='inputNumber'
/>
<a href='#'>Link</a>
</FormItem>
<FormItem label='Switch' labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}>
<Switch defaultChecked name='switch' />
</FormItem>
<FormItem label='Slider' labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}>
<Slider defaultValue={70} />
</FormItem>
<FormItem label='Select' labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}>
<Select
size='large'
defaultValue='lucy'
style={{ width: 192 }}
name='select'
>
<Option value='jack'>jack</Option>
<Option value='lucy'>lucy</Option>
<Option value='disabled' disabled>
disabled
</Option>
<Option value='yiminghe'>yiminghe</Option>
</Select>
</FormItem>
<FormItem
label='DatePicker'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<DatePicker name='startDate' />
</FormItem>
<FormItem style={{ marginTop: 48 }} wrapperCol={{ span: 8, offset: 8 }}>
<Button size='large' type='primary' htmlType='submit'>
OK
</Button>
<Button size='large' style={{ marginLeft: 8 }}>
Cancel
</Button>
</FormItem>
</Form>
</div>
)
|
var ejs = require("ejs"),
extend = require("extend"),
forEach = require("for_each"),
path = require("file_path"),
fileUtils = require("file_utils");
function compile(template, out, config, options, callback) {
var opts;
options = options || {};
opts = {
locals: options.data || (options.data = {}),
settings: options.settings
};
forEach(options.functions, function(fn) {
extend(options.data, fn());
});
opts.locals.env = config.env;
ejs.render(template, opts, function(err, str) {
if (err) {
callback(err);
return;
}
fileUtils.writeFile(out, str, function(err) {
callback(err);
});
});
}
module.exports = function(config) {
return function(done) {
compile(config.paths.ejs_src, config.paths.ejs_out, config, {
data: {},
functions: [
function() {
return {
useLiveReload: config.env !== "production",
liveReloadPort: config.liveReloadPort
};
}
]
}, done);
};
};
|
var webpack = require('webpack')
var config = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var BrowserSyncPlugin = require('browser-sync-webpack-plugin')
config.output.filename = '[name].js'
config.output.chunkFilename = '[id].js'
var SOURCE_MAP = true
config.devtool = SOURCE_MAP ? 'eval-source-map' : false
// add hot-reload related code to entry chunk
config.entry.app = [
'eventsource-polyfill',
'webpack-hot-middleware/client?quiet=true&reload=true',
config.entry.app
]
// generate loader string to be used with extract text plugin
function generateExtractLoaders (loaders) {
return loaders.map(function (loader) {
return loader + '-loader' + (SOURCE_MAP ? '?sourceMap' : '')
}).join('!')
}
config.vue.loaders = {
js: 'babel!eslint',
// http://vuejs.github.io/vue-loader/configurations/extract-css.html
css: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css'])),
less: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css', 'less'])),
sass: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css', 'sass'])),
stylus: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css', 'stylus']))
}
config.output.publicPath = '/'
config.plugins = (config.plugins || []).concat([
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('[name].css'),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html'
}),
new BrowserSyncPlugin(
// BrowserSync options
{
host: '127.0.0.1',
port: 8080,
proxy: 'http://127.0.0.1:8000/',
logConnections: true,
notify: false,
open: false
},
{
reload: true
}
)
])
module.exports = config
|
for (var i = 0; i < acentos.length; i++) {
if (acentos[i] && acentos[i + 1] && acentos[i + 2]) {
selSeat = i; //tenho medo desta variável solta
//Codigo..
if (confirm("Reserva da cadeira " + (i + 1) + " ~ " + (i + 3) + " está disponível, aceitar?.")) {
break;
} else {
//Codigo..
}
}
}
//https://pt.stackoverflow.com/q/219732/101
|
describe('view (option)', () => {
it('should be null be default', () => {
const image = window.createImage();
const viewer = new Viewer(image);
expect(viewer.options.view).to.be.null;
});
it('should execute the `view` hook function', (done) => {
const image = window.createImage();
const viewer = new Viewer(image, {
view(event) {
expect(event.type).to.equal('view');
},
viewed() {
viewer.hide(true);
done();
},
});
viewer.show();
});
it('should have expected properties in `event.detail`', (done) => {
const image = window.createImage();
const viewer = new Viewer(image, {
view(event) {
expect(event.detail).to.be.an('object').that.has.all.keys('image', 'index', 'originalImage');
expect(event.detail.image.src).to.equal(image.src);
expect(event.detail.index).to.equal(0);
expect(event.detail.originalImage).to.equal(image);
},
viewed() {
viewer.hide(true);
done();
},
});
viewer.show();
});
it('should not execute the `viewed` hook function when default prevented', (done) => {
const image = window.createImage();
const viewer = new Viewer(image, {
inline: true,
view(event) {
event.preventDefault();
setTimeout(() => {
viewer.hide(true);
done();
}, 350);
},
viewed() {
expect.fail(1, 0);
},
});
});
it('should execute the `view` hook function in inline mode', (done) => {
const image = window.createImage();
new Viewer(image, {
inline: true,
view(event) {
expect(event.type).to.equal('view');
done();
},
});
});
});
|
/***
MochiKit.Base 1.3.1
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
if (typeof(dojo) != 'undefined') {
dojo.provide("MochiKit.Base");
}
if (typeof(MochiKit) == 'undefined') {
MochiKit = {};
}
if (typeof(MochiKit.Base) == 'undefined') {
MochiKit.Base = {};
}
MochiKit.Base.VERSION = "1.3.1";
MochiKit.Base.NAME = "MochiKit.Base";
MochiKit.Base.update = function (self, obj/*, ... */) {
if (self === null) {
self = {};
}
for (var i = 1; i < arguments.length; i++) {
var o = arguments[i];
if (typeof(o) != 'undefined' && o !== null) {
for (var k in o) {
self[k] = o[k];
}
}
}
return self;
};
MochiKit.Base.update(MochiKit.Base, {
__repr__: function () {
return "[" + this.NAME + " " + this.VERSION + "]";
},
toString: function () {
return this.__repr__();
},
counter: function (n/* = 1 */) {
if (arguments.length === 0) {
n = 1;
}
return function () {
return n++;
};
},
clone: function (obj) {
var me = arguments.callee;
if (arguments.length == 1) {
me.prototype = obj;
return new me();
}
},
flattenArguments: function (lst/* ...*/) {
var res = [];
var m = MochiKit.Base;
var args = m.extend(null, arguments);
while (args.length) {
var o = args.shift();
if (o && typeof(o) == "object" && typeof(o.length) == "number") {
for (var i = o.length - 1; i >= 0; i--) {
args.unshift(o[i]);
}
} else {
res.push(o);
}
}
return res;
},
extend: function (self, obj, /* optional */skip) {
// Extend an array with an array-like object starting
// from the skip index
if (!skip) {
skip = 0;
}
if (obj) {
// allow iterable fall-through, but skip the full isArrayLike
// check for speed, this is called often.
var l = obj.length;
if (typeof(l) != 'number' /* !isArrayLike(obj) */) {
if (typeof(MochiKit.Iter) != "undefined") {
obj = MochiKit.Iter.list(obj);
l = obj.length;
} else {
throw new TypeError("Argument not an array-like and MochiKit.Iter not present");
}
}
if (!self) {
self = [];
}
for (var i = skip; i < l; i++) {
self.push(obj[i]);
}
}
// This mutates, but it's convenient to return because
// it's often used like a constructor when turning some
// ghetto array-like to a real array
return self;
},
updatetree: function (self, obj/*, ...*/) {
if (self === null) {
self = {};
}
for (var i = 1; i < arguments.length; i++) {
var o = arguments[i];
if (typeof(o) != 'undefined' && o !== null) {
for (var k in o) {
var v = o[k];
if (typeof(self[k]) == 'object' && typeof(v) == 'object') {
arguments.callee(self[k], v);
} else {
self[k] = v;
}
}
}
}
return self;
},
setdefault: function (self, obj/*, ...*/) {
if (self === null) {
self = {};
}
for (var i = 1; i < arguments.length; i++) {
var o = arguments[i];
for (var k in o) {
if (!(k in self)) {
self[k] = o[k];
}
}
}
return self;
},
keys: function (obj) {
var rval = [];
for (var prop in obj) {
rval.push(prop);
}
return rval;
},
items: function (obj) {
var rval = [];
var e;
for (var prop in obj) {
var v;
try {
v = obj[prop];
} catch (e) {
continue;
}
rval.push([prop, v]);
}
return rval;
},
_newNamedError: function (module, name, func) {
func.prototype = new MochiKit.Base.NamedError(module.NAME + "." + name);
module[name] = func;
},
operator: {
// unary logic operators
truth: function (a) { return !!a; },
lognot: function (a) { return !a; },
identity: function (a) { return a; },
// bitwise unary operators
not: function (a) { return ~a; },
neg: function (a) { return -a; },
// binary operators
add: function (a, b) { return a + b; },
sub: function (a, b) { return a - b; },
div: function (a, b) { return a / b; },
mod: function (a, b) { return a % b; },
mul: function (a, b) { return a * b; },
// bitwise binary operators
and: function (a, b) { return a & b; },
or: function (a, b) { return a | b; },
xor: function (a, b) { return a ^ b; },
lshift: function (a, b) { return a << b; },
rshift: function (a, b) { return a >> b; },
zrshift: function (a, b) { return a >>> b; },
// near-worthless built-in comparators
eq: function (a, b) { return a == b; },
ne: function (a, b) { return a != b; },
gt: function (a, b) { return a > b; },
ge: function (a, b) { return a >= b; },
lt: function (a, b) { return a < b; },
le: function (a, b) { return a <= b; },
// compare comparators
ceq: function (a, b) { return MochiKit.Base.compare(a, b) === 0; },
cne: function (a, b) { return MochiKit.Base.compare(a, b) !== 0; },
cgt: function (a, b) { return MochiKit.Base.compare(a, b) == 1; },
cge: function (a, b) { return MochiKit.Base.compare(a, b) != -1; },
clt: function (a, b) { return MochiKit.Base.compare(a, b) == -1; },
cle: function (a, b) { return MochiKit.Base.compare(a, b) != 1; },
// binary logical operators
logand: function (a, b) { return a && b; },
logor: function (a, b) { return a || b; },
contains: function (a, b) { return b in a; }
},
forwardCall: function (func) {
return function () {
return this[func].apply(this, arguments);
};
},
itemgetter: function (func) {
return function (arg) {
return arg[func];
};
},
typeMatcher: function (/* typ */) {
var types = {};
for (var i = 0; i < arguments.length; i++) {
var typ = arguments[i];
types[typ] = typ;
}
return function () {
for (var i = 0; i < arguments.length; i++) {
if (!(typeof(arguments[i]) in types)) {
return false;
}
}
return true;
};
},
isNull: function (/* ... */) {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] !== null) {
return false;
}
}
return true;
},
isUndefinedOrNull: function (/* ... */) {
for (var i = 0; i < arguments.length; i++) {
var o = arguments[i];
if (!(typeof(o) == 'undefined' || o === null)) {
return false;
}
}
return true;
},
isEmpty: function (obj) {
return !MochiKit.Base.isNotEmpty.apply(this, arguments);
},
isNotEmpty: function (obj) {
for (var i = 0; i < arguments.length; i++) {
var o = arguments[i];
if (!(o && o.length)) {
return false;
}
}
return true;
},
isArrayLike: function () {
for (var i = 0; i < arguments.length; i++) {
var o = arguments[i];
var typ = typeof(o);
if (
(typ != 'object' && !(typ == 'function' && typeof(o.item) == 'function')) ||
o === null ||
typeof(o.length) != 'number'
) {
return false;
}
}
return true;
},
isDateLike: function () {
for (var i = 0; i < arguments.length; i++) {
var o = arguments[i];
if (typeof(o) != "object" || o === null
|| typeof(o.getTime) != 'function') {
return false;
}
}
return true;
},
xmap: function (fn/*, obj... */) {
if (fn === null) {
return MochiKit.Base.extend(null, arguments, 1);
}
var rval = [];
for (var i = 1; i < arguments.length; i++) {
rval.push(fn(arguments[i]));
}
return rval;
},
map: function (fn, lst/*, lst... */) {
var m = MochiKit.Base;
var itr = MochiKit.Iter;
var isArrayLike = m.isArrayLike;
if (arguments.length <= 2) {
// allow an iterable to be passed
if (!isArrayLike(lst)) {
if (itr) {
// fast path for map(null, iterable)
lst = itr.list(lst);
if (fn === null) {
return lst;
}
} else {
throw new TypeError("Argument not an array-like and MochiKit.Iter not present");
}
}
// fast path for map(null, lst)
if (fn === null) {
return m.extend(null, lst);
}
// disabled fast path for map(fn, lst)
/*
if (false && typeof(Array.prototype.map) == 'function') {
// Mozilla fast-path
return Array.prototype.map.call(lst, fn);
}
*/
var rval = [];
for (var i = 0; i < lst.length; i++) {
rval.push(fn(lst[i]));
}
return rval;
} else {
// default for map(null, ...) is zip(...)
if (fn === null) {
fn = Array;
}
var length = null;
for (i = 1; i < arguments.length; i++) {
// allow iterables to be passed
if (!isArrayLike(arguments[i])) {
if (itr) {
return itr.list(itr.imap.apply(null, arguments));
} else {
throw new TypeError("Argument not an array-like and MochiKit.Iter not present");
}
}
// find the minimum length
var l = arguments[i].length;
if (length === null || length > l) {
length = l;
}
}
rval = [];
for (i = 0; i < length; i++) {
var args = [];
for (var j = 1; j < arguments.length; j++) {
args.push(arguments[j][i]);
}
rval.push(fn.apply(this, args));
}
return rval;
}
},
xfilter: function (fn/*, obj... */) {
var rval = [];
if (fn === null) {
fn = MochiKit.Base.operator.truth;
}
for (var i = 1; i < arguments.length; i++) {
var o = arguments[i];
if (fn(o)) {
rval.push(o);
}
}
return rval;
},
filter: function (fn, lst, self) {
var rval = [];
// allow an iterable to be passed
var m = MochiKit.Base;
if (!m.isArrayLike(lst)) {
if (MochiKit.Iter) {
lst = MochiKit.Iter.list(lst);
} else {
throw new TypeError("Argument not an array-like and MochiKit.Iter not present");
}
}
if (fn === null) {
fn = m.operator.truth;
}
if (typeof(Array.prototype.filter) == 'function') {
// Mozilla fast-path
return Array.prototype.filter.call(lst, fn, self);
} else if (typeof(self) == 'undefined' || self === null) {
for (var i = 0; i < lst.length; i++) {
var o = lst[i];
if (fn(o)) {
rval.push(o);
}
}
} else {
for (i = 0; i < lst.length; i++) {
o = lst[i];
if (fn.call(self, o)) {
rval.push(o);
}
}
}
return rval;
},
_wrapDumbFunction: function (func) {
return function () {
// fast path!
switch (arguments.length) {
case 0: return func();
case 1: return func(arguments[0]);
case 2: return func(arguments[0], arguments[1]);
case 3: return func(arguments[0], arguments[1], arguments[2]);
}
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push("arguments[" + i + "]");
}
return eval("(func(" + args.join(",") + "))");
};
},
method: function (self, func) {
var m = MochiKit.Base;
return m.bind.apply(this, m.extend([func, self], arguments, 2));
},
bind: function (func, self/* args... */) {
if (typeof(func) == "string") {
func = self[func];
}
var im_func = func.im_func;
var im_preargs = func.im_preargs;
var im_self = func.im_self;
var m = MochiKit.Base;
if (typeof(func) == "function" && typeof(func.apply) == "undefined") {
// this is for cases where JavaScript sucks ass and gives you a
// really dumb built-in function like alert() that doesn't have
// an apply
func = m._wrapDumbFunction(func);
}
if (typeof(im_func) != 'function') {
im_func = func;
}
if (typeof(self) != 'undefined') {
im_self = self;
}
if (typeof(im_preargs) == 'undefined') {
im_preargs = [];
} else {
im_preargs = im_preargs.slice();
}
m.extend(im_preargs, arguments, 2);
var newfunc = function () {
var args = arguments;
var me = arguments.callee;
if (me.im_preargs.length > 0) {
args = m.concat(me.im_preargs, args);
}
var self = me.im_self;
if (!self) {
self = this;
}
return me.im_func.apply(self, args);
};
newfunc.im_self = im_self;
newfunc.im_func = im_func;
newfunc.im_preargs = im_preargs;
return newfunc;
},
bindMethods: function (self) {
var bind = MochiKit.Base.bind;
for (var k in self) {
var func = self[k];
if (typeof(func) == 'function') {
self[k] = bind(func, self);
}
}
},
registerComparator: function (name, check, comparator, /* optional */ override) {
MochiKit.Base.comparatorRegistry.register(name, check, comparator, override);
},
_primitives: {'boolean': true, 'string': true, 'number': true},
compare: function (a, b) {
if (a == b) {
return 0;
}
var aIsNull = (typeof(a) == 'undefined' || a === null);
var bIsNull = (typeof(b) == 'undefined' || b === null);
if (aIsNull && bIsNull) {
return 0;
} else if (aIsNull) {
return -1;
} else if (bIsNull) {
return 1;
}
var m = MochiKit.Base;
// bool, number, string have meaningful comparisons
var prim = m._primitives;
if (!(typeof(a) in prim && typeof(b) in prim)) {
try {
return m.comparatorRegistry.match(a, b);
} catch (e) {
if (e != m.NotFound) {
throw e;
}
}
}
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
// These types can't be compared
var repr = m.repr;
throw new TypeError(repr(a) + " and " + repr(b) + " can not be compared");
},
compareDateLike: function (a, b) {
return MochiKit.Base.compare(a.getTime(), b.getTime());
},
compareArrayLike: function (a, b) {
var compare = MochiKit.Base.compare;
var count = a.length;
var rval = 0;
if (count > b.length) {
rval = 1;
count = b.length;
} else if (count < b.length) {
rval = -1;
}
for (var i = 0; i < count; i++) {
var cmp = compare(a[i], b[i]);
if (cmp) {
return cmp;
}
}
return rval;
},
registerRepr: function (name, check, wrap, /* optional */override) {
MochiKit.Base.reprRegistry.register(name, check, wrap, override);
},
repr: function (o) {
if (typeof(o) == "undefined") {
return "undefined";
} else if (o === null) {
return "null";
}
try {
if (typeof(o.__repr__) == 'function') {
return o.__repr__();
} else if (typeof(o.repr) == 'function' && o.repr != arguments.callee) {
return o.repr();
}
return MochiKit.Base.reprRegistry.match(o);
} catch (e) {
if (typeof(o.NAME) == 'string' && (
o.toString == Function.prototype.toString ||
o.toString == Object.prototype.toString
)) {
return o.NAME;
}
}
try {
var ostring = (o + "");
} catch (e) {
return "[" + typeof(o) + "]";
}
if (typeof(o) == "function") {
o = ostring.replace(/^\s+/, "");
var idx = o.indexOf("{");
if (idx != -1) {
o = o.substr(0, idx) + "{...}";
}
}
return ostring;
},
reprArrayLike: function (o) {
var m = MochiKit.Base;
return "[" + m.map(m.repr, o).join(", ") + "]";
},
reprString: function (o) {
return ('"' + o.replace(/(["\\])/g, '\\$1') + '"'
).replace(/[\f]/g, "\\f"
).replace(/[\b]/g, "\\b"
).replace(/[\n]/g, "\\n"
).replace(/[\t]/g, "\\t"
).replace(/[\r]/g, "\\r");
},
reprNumber: function (o) {
return o + "";
},
registerJSON: function (name, check, wrap, /* optional */override) {
MochiKit.Base.jsonRegistry.register(name, check, wrap, override);
},
evalJSON: function () {
return eval("(" + arguments[0] + ")");
},
serializeJSON: function (o) {
var objtype = typeof(o);
if (objtype == "undefined") {
return "undefined";
} else if (objtype == "number" || objtype == "boolean") {
return o + "";
} else if (o === null) {
return "null";
}
var m = MochiKit.Base;
var reprString = m.reprString;
if (objtype == "string") {
return reprString(o);
}
// recurse
var me = arguments.callee;
// short-circuit for objects that support "json" serialization
// if they return "self" then just pass-through...
var newObj;
if (typeof(o.__json__) == "function") {
newObj = o.__json__();
if (o !== newObj) {
return me(newObj);
}
}
if (typeof(o.json) == "function") {
newObj = o.json();
if (o !== newObj) {
return me(newObj);
}
}
// array
if (objtype != "function" && typeof(o.length) == "number") {
var res = [];
for (var i = 0; i < o.length; i++) {
var val = me(o[i]);
if (typeof(val) != "string") {
val = "undefined";
}
res.push(val);
}
return "[" + res.join(", ") + "]";
}
// look in the registry
try {
newObj = m.jsonRegistry.match(o);
return me(newObj);
} catch (e) {
if (e != m.NotFound) {
// something really bad happened
throw e;
}
}
// it's a function with no adapter, bad
if (objtype == "function") {
return null;
}
// generic object code path
res = [];
for (var k in o) {
var useKey;
if (typeof(k) == "number") {
useKey = '"' + k + '"';
} else if (typeof(k) == "string") {
useKey = reprString(k);
} else {
// skip non-string or number keys
continue;
}
val = me(o[k]);
if (typeof(val) != "string") {
// skip non-serializable values
continue;
}
res.push(useKey + ":" + val);
}
return "{" + res.join(", ") + "}";
},
objEqual: function (a, b) {
return (MochiKit.Base.compare(a, b) === 0);
},
arrayEqual: function (self, arr) {
if (self.length != arr.length) {
return false;
}
return (MochiKit.Base.compare(self, arr) === 0);
},
concat: function (/* lst... */) {
var rval = [];
var extend = MochiKit.Base.extend;
for (var i = 0; i < arguments.length; i++) {
extend(rval, arguments[i]);
}
return rval;
},
keyComparator: function (key/* ... */) {
// fast-path for single key comparisons
var m = MochiKit.Base;
var compare = m.compare;
if (arguments.length == 1) {
return function (a, b) {
return compare(a[key], b[key]);
};
}
var compareKeys = m.extend(null, arguments);
return function (a, b) {
var rval = 0;
// keep comparing until something is inequal or we run out of
// keys to compare
for (var i = 0; (rval === 0) && (i < compareKeys.length); i++) {
var key = compareKeys[i];
rval = compare(a[key], b[key]);
}
return rval;
};
},
reverseKeyComparator: function (key) {
var comparator = MochiKit.Base.keyComparator.apply(this, arguments);
return function (a, b) {
return comparator(b, a);
};
},
partial: function (func) {
var m = MochiKit.Base;
return m.bind.apply(this, m.extend([func, undefined], arguments, 1));
},
listMinMax: function (which, lst) {
if (lst.length === 0) {
return null;
}
var cur = lst[0];
var compare = MochiKit.Base.compare;
for (var i = 1; i < lst.length; i++) {
var o = lst[i];
if (compare(o, cur) == which) {
cur = o;
}
}
return cur;
},
objMax: function (/* obj... */) {
return MochiKit.Base.listMinMax(1, arguments);
},
objMin: function (/* obj... */) {
return MochiKit.Base.listMinMax(-1, arguments);
},
findIdentical: function (lst, value, start/* = 0 */, /* optional */end) {
if (typeof(end) == "undefined" || end === null) {
end = lst.length;
}
for (var i = (start || 0); i < end; i++) {
if (lst[i] === value) {
return i;
}
}
return -1;
},
findValue: function (lst, value, start/* = 0 */, /* optional */end) {
if (typeof(end) == "undefined" || end === null) {
end = lst.length;
}
var cmp = MochiKit.Base.compare;
for (var i = (start || 0); i < end; i++) {
if (cmp(lst[i], value) === 0) {
return i;
}
}
return -1;
},
nodeWalk: function (node, visitor) {
var nodes = [node];
var extend = MochiKit.Base.extend;
while (nodes.length) {
var res = visitor(nodes.shift());
if (res) {
extend(nodes, res);
}
}
},
nameFunctions: function (namespace) {
var base = namespace.NAME;
if (typeof(base) == 'undefined') {
base = '';
} else {
base = base + '.';
}
for (var name in namespace) {
var o = namespace[name];
if (typeof(o) == 'function' && typeof(o.NAME) == 'undefined') {
try {
o.NAME = base + name;
} catch (e) {
// pass
}
}
}
},
queryString: function (names, values) {
// check to see if names is a string or a dom element, and if
// MochiKit.dom is available. If so, drop it like it's a form
// Ugliest conditional in MochiKit? Probably!
if (typeof(MochiKit.dom) != "undefined" && arguments.length == 1
&& (typeof(names) == "string" || (
typeof(names.nodeType) != "undefined" && names.nodeType > 0
))
) {
var kv = MochiKit.dom.formContents(names);
names = kv[0];
values = kv[1];
} else if (arguments.length == 1) {
var o = names;
names = [];
values = [];
for (var k in o) {
var v = o[k];
if (typeof(v) != "function") {
names.push(k);
values.push(v);
}
}
}
var rval = [];
var len = Math.min(names.length, values.length);
var urlEncode = MochiKit.Base.urlEncode;
for (var i = 0; i < len; i++) {
v = values[i];
if (typeof(v) != 'undefined' && v !== null) {
rval.push(urlEncode(names[i]) + "=" + urlEncode(v));
}
}
return rval.join("&");
},
parseQueryString: function (encodedString, useArrays) {
var pairs = encodedString.replace(/\+/g, "%20").split("&");
var o = {};
var decode;
if (typeof(decodeURIComponent) != "undefined") {
decode = decodeURIComponent;
} else {
decode = unescape;
}
if (useArrays) {
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("=");
var name = decode(pair[0]);
var arr = o[name];
if (!(arr instanceof Array)) {
arr = [];
o[name] = arr;
}
arr.push(decode(pair[1]));
}
} else {
for (i = 0; i < pairs.length; i++) {
pair = pairs[i].split("=");
o[decode(pair[0])] = decode(pair[1]);
}
}
return o;
}
});
MochiKit.Base.AdapterRegistry = function () {
this.pairs = [];
};
MochiKit.Base.AdapterRegistry.prototype = {
register: function (name, check, wrap, /* optional */ override) {
if (override) {
this.pairs.unshift([name, check, wrap]);
} else {
this.pairs.push([name, check, wrap]);
}
},
match: function (/* ... */) {
for (var i = 0; i < this.pairs.length; i++) {
var pair = this.pairs[i];
if (pair[1].apply(this, arguments)) {
return pair[2].apply(this, arguments);
}
}
throw MochiKit.Base.NotFound;
},
unregister: function (name) {
for (var i = 0; i < this.pairs.length; i++) {
var pair = this.pairs[i];
if (pair[0] == name) {
this.pairs.splice(i, 1);
return true;
}
}
return false;
}
};
MochiKit.Base.EXPORT = [
"counter",
"clone",
"extend",
"update",
"updatetree",
"setdefault",
"keys",
"items",
"NamedError",
"operator",
"forwardCall",
"itemgetter",
"typeMatcher",
"isCallable",
"isUndefined",
"isUndefinedOrNull",
"isNull",
"isEmpty",
"isNotEmpty",
"isArrayLike",
"isDateLike",
"xmap",
"map",
"xfilter",
"filter",
"bind",
"bindMethods",
"NotFound",
"AdapterRegistry",
"registerComparator",
"compare",
"registerRepr",
"repr",
"objEqual",
"arrayEqual",
"concat",
"keyComparator",
"reverseKeyComparator",
"partial",
"merge",
"listMinMax",
"listMax",
"listMin",
"objMax",
"objMin",
"nodeWalk",
"zip",
"urlEncode",
"queryString",
"serializeJSON",
"registerJSON",
"evalJSON",
"parseQueryString",
"findValue",
"findIdentical",
"flattenArguments",
"method"
];
MochiKit.Base.EXPORT_OK = [
"nameFunctions",
"comparatorRegistry",
"reprRegistry",
"jsonRegistry",
"compareDateLike",
"compareArrayLike",
"reprArrayLike",
"reprString",
"reprNumber"
];
MochiKit.Base._exportSymbols = function (globals, module) {
if (typeof(MochiKit.__export__) == "undefined") {
MochiKit.__export__ = (MochiKit.__compat__ ||
(typeof(JSAN) == 'undefined' && typeof(dojo) == 'undefined')
);
}
if (!MochiKit.__export__) {
return;
}
var all = module.EXPORT_TAGS[":all"];
for (var i = 0; i < all.length; i++) {
globals[all[i]] = module[all[i]];
}
};
MochiKit.Base.__new__ = function () {
// A singleton raised when no suitable adapter is found
var m = this;
// Backwards compat
m.forward = m.forwardCall;
m.find = m.findValue;
if (typeof(encodeURIComponent) != "undefined") {
m.urlEncode = function (unencoded) {
return encodeURIComponent(unencoded).replace(/\'/g, '%27');
};
} else {
m.urlEncode = function (unencoded) {
return escape(unencoded
).replace(/\+/g, '%2B'
).replace(/\"/g,'%22'
).rval.replace(/\'/g, '%27');
};
}
m.NamedError = function (name) {
this.message = name;
this.name = name;
};
m.NamedError.prototype = new Error();
m.update(m.NamedError.prototype, {
repr: function () {
if (this.message && this.message != this.name) {
return this.name + "(" + m.repr(this.message) + ")";
} else {
return this.name + "()";
}
},
toString: m.forwardCall("repr")
});
m.NotFound = new m.NamedError("MochiKit.Base.NotFound");
m.listMax = m.partial(m.listMinMax, 1);
m.listMin = m.partial(m.listMinMax, -1);
m.isCallable = m.typeMatcher('function');
m.isUndefined = m.typeMatcher('undefined');
m.merge = m.partial(m.update, null);
m.zip = m.partial(m.map, null);
m.comparatorRegistry = new m.AdapterRegistry();
m.registerComparator("dateLike", m.isDateLike, m.compareDateLike);
m.registerComparator("arrayLike", m.isArrayLike, m.compareArrayLike);
m.reprRegistry = new m.AdapterRegistry();
m.registerRepr("arrayLike", m.isArrayLike, m.reprArrayLike);
m.registerRepr("string", m.typeMatcher("string"), m.reprString);
m.registerRepr("numbers", m.typeMatcher("number", "boolean"), m.reprNumber);
m.jsonRegistry = new m.AdapterRegistry();
var all = m.concat(m.EXPORT, m.EXPORT_OK);
m.EXPORT_TAGS = {
":common": m.concat(m.EXPORT_OK),
":all": all
};
m.nameFunctions(this);
};
MochiKit.Base.__new__();
//
// XXX: Internet Explorer blows
//
if (!MochiKit.__compat__) {
compare = MochiKit.Base.compare;
}
MochiKit.Base._exportSymbols(this, MochiKit.Base);
|
(function() {
var rule = data.rules[parseInt(request.param.num, 10)] || null;
if (rule === null) return response.error(404);
switch (request.method) {
case 'GET':
response.head(200);
response.end(JSON.stringify(rule, null, ' '));
return;
case 'PUT':
if (request.headers['content-type'].match(/^application\/json/)) {
var newRule = request.query;
if (newRule.isEnabled === false) {
newRule.isDisabled = true;
}
delete newRule.isEnabled;
data.rules.splice(data.rules.indexOf(rule), 1, newRule);
fs.writeFileSync(define.RULES_FILE, JSON.stringify(data.rules, null, ' '));
response.head(200);
response.end(JSON.stringify(newRule));
} else {
var args = [];
for (var i in request.query) {
if (i === 'method') continue;
args.push('-' + i + ' ' + request.query[i]);
}
if (args.length === 0) {
return response.error(400);
}
child_process.exec('node app-cli.js -mode rule -n ' + request.param.num + ' ' + args.join(' '), function(err, stdout, stderr) {
if (err) return response.error(500);
response.head(200);
response.end('{}');
});
}
return;
case 'DELETE':
child_process.exec('node app-cli.js -mode rule --remove -n ' + request.param.num, function(err, stdout, stderr) {
if (err) return response.error(500);
response.head(200);
response.end('{}');
});
return;
}
})(); |
import annotateAsPure from "@babel/helper-annotate-as-pure";
import { types as t } from "@babel/core";
export default function(api, options) {
const { loose } = options;
let helperName = "taggedTemplateLiteral";
if (loose) helperName += "Loose";
/**
* This function groups the objects into multiple calls to `.concat()` in
* order to preserve execution order of the primitive conversion, e.g.
*
* "".concat(obj.foo, "foo", obj2.foo, "foo2")
*
* would evaluate both member expressions _first_ then, `concat` will
* convert each one to a primitive, whereas
*
* "".concat(obj.foo, "foo").concat(obj2.foo, "foo2")
*
* would evaluate the member, then convert it to a primitive, then evaluate
* the second member and convert that one, which reflects the spec behavior
* of template literals.
*/
function buildConcatCallExressions(items) {
let avail = true;
return items.reduce(function(left, right) {
let canBeInserted = t.isLiteral(right);
if (!canBeInserted && avail) {
canBeInserted = true;
avail = false;
}
if (canBeInserted && t.isCallExpression(left)) {
left.arguments.push(right);
return left;
}
return t.callExpression(
t.memberExpression(left, t.identifier("concat")),
[right],
);
});
}
return {
pre() {
this.templates = new Map();
},
visitor: {
TaggedTemplateExpression(path) {
const { node } = path;
const { quasi } = node;
const strings = [];
const raws = [];
for (const elem of (quasi.quasis: Array)) {
const { raw, cooked } = elem.value;
const value =
cooked == null
? path.scope.buildUndefinedNode()
: t.stringLiteral(cooked);
strings.push(value);
raws.push(t.stringLiteral(raw));
}
// Generate a unique name based on the string literals so we dedupe
// identical strings used in the program.
const rawParts = raws.map(s => s.value).join(",");
const name = `${helperName}_${raws.length}_${rawParts}`;
let templateObject = this.templates.get(name);
if (templateObject) {
templateObject = t.clone(templateObject);
} else {
const programPath = path.find(p => p.isProgram());
templateObject = programPath.scope.generateUidIdentifier(
"templateObject",
);
this.templates.set(name, templateObject);
const helperId = this.addHelper(helperName);
const init = t.callExpression(helperId, [
t.arrayExpression(strings),
t.arrayExpression(raws),
]);
annotateAsPure(init);
init._compact = true;
programPath.scope.push({
id: templateObject,
init,
// This ensures that we don't fail if not using function expression helpers
_blockHoist: 1.9,
});
}
path.replaceWith(
t.callExpression(node.tag, [templateObject, ...quasi.expressions]),
);
},
TemplateLiteral(path) {
const nodes = [];
const expressions = path.get("expressions");
let index = 0;
for (const elem of (path.node.quasis: Array)) {
if (elem.value.cooked) {
nodes.push(t.stringLiteral(elem.value.cooked));
}
if (index < expressions.length) {
const expr = expressions[index++];
const node = expr.node;
if (!t.isStringLiteral(node, { value: "" })) {
nodes.push(node);
}
}
}
// since `+` is left-to-right associative
// ensure the first node is a string if first/second isn't
const considerSecondNode = !loose || !t.isStringLiteral(nodes[1]);
if (!t.isStringLiteral(nodes[0]) && considerSecondNode) {
nodes.unshift(t.stringLiteral(""));
}
let root = nodes[0];
if (loose) {
for (let i = 1; i < nodes.length; i++) {
root = t.binaryExpression("+", root, nodes[i]);
}
} else if (nodes.length > 1) {
root = buildConcatCallExressions(nodes);
}
path.replaceWith(root);
},
},
};
}
|
import Lab from 'lab'
import Code from 'code'
import { server } from '../src/index.js'
var lab = exports.lab = Lab.script()
lab.experiment('Images Api Tests', () => {
lab.test('GET /images (invalid id)', (done) => {
var options = {
method: 'GET',
url: '/api/images/invalidId'
}
server.inject(options, (response) => {
Code.expect(response.statusCode).to.equal(400)
server.stop(done)
})
})
lab.test('GET /images (valid id but image does not exists)', (done) => {
var options = {
method: 'GET',
url: '/api/images/66a9490416de9bb820b499f4'
}
server.inject(options, (response) => {
Code.expect(response.statusCode).to.equal(404)
server.stop(done)
})
})
})
|
// document.write('Hello World!');
require('./style.css');
document.write(require("./content.js"));
var item = "<div>"+ name + "<div>";
var items = []
items.map(function(value){
return "<li>"+ name + "<li>";
})
|
/* */
'use strict';
var LIBRARY = require("./$.library"),
$def = require("./$.def"),
$redef = require("./$.redef"),
hide = require("./$.hide"),
has = require("./$.has"),
SYMBOL_ITERATOR = require("./$.wks")('iterator'),
Iterators = require("./$.iterators"),
$iterCreate = require("./$.iter-create"),
setToStringTag = require("./$.set-to-string-tag"),
getProto = require("./$").getProto,
BUGGY = !([].keys && 'next' in [].keys()),
FF_ITERATOR = '@@iterator',
KEYS = 'keys',
VALUES = 'values';
var returnThis = function() {
return this;
};
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE) {
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind) {
if (!BUGGY && kind in proto)
return proto[kind];
switch (kind) {
case KEYS:
return function keys() {
return new Constructor(this, kind);
};
case VALUES:
return function values() {
return new Constructor(this, kind);
};
}
return function entries() {
return new Constructor(this, kind);
};
};
var TAG = NAME + ' Iterator',
proto = Base.prototype,
_native = proto[SYMBOL_ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT],
_default = _native || getMethod(DEFAULT),
methods,
key;
if (_native) {
var IteratorPrototype = getProto(_default.call(new Base));
setToStringTag(IteratorPrototype, TAG, true);
if (!LIBRARY && has(proto, FF_ITERATOR))
hide(IteratorPrototype, SYMBOL_ITERATOR, returnThis);
}
if ((!LIBRARY || FORCE) && (BUGGY || !(SYMBOL_ITERATOR in proto))) {
hide(proto, SYMBOL_ITERATOR, _default);
}
Iterators[NAME] = _default;
Iterators[TAG] = returnThis;
if (DEFAULT) {
methods = {
values: DEFAULT == VALUES ? _default : getMethod(VALUES),
keys: IS_SET ? _default : getMethod(KEYS),
entries: DEFAULT != VALUES ? _default : getMethod('entries')
};
if (FORCE)
for (key in methods) {
if (!(key in proto))
$redef(proto, key, methods[key]);
}
else
$def($def.P + $def.F * BUGGY, NAME, methods);
}
return methods;
};
|
import { tokens } from '../tokenTypes'
const { SPACE, IDENT, STRING } = tokens
export default tokenStream => {
let fontFamily
if (tokenStream.matches(STRING)) {
fontFamily = tokenStream.lastValue
} else {
fontFamily = tokenStream.expect(IDENT)
while (tokenStream.hasTokens()) {
tokenStream.expect(SPACE)
const nextIdent = tokenStream.expect(IDENT)
fontFamily += ` ${nextIdent}`
}
}
tokenStream.expectEmpty()
return fontFamily
}
|
//>>built
define(["dojo/_base/declare","dojox/data/CssRuleStore"],function(h,k){return h("dojox.data.CssClassStore",k,{_labelAttribute:"class",_idAttribute:"class",_cName:"dojox.data.CssClassStore",getFeatures:function(){return{"dojo.data.api.Read":!0,"dojo.data.api.Identity":!0}},getAttributes:function(a){this._assertIsItem(a);return["class","classSans"]},getValue:function(a,c,b){return(a=this.getValues(a,c))&&0<a.length?a[0]:b},getValues:function(a,c){this._assertIsItem(a);this._assertIsAttribute(c);var b=
[];"class"===c?b=[a.className]:"classSans"===c&&(b=[a.className.replace(/\./g,"")]);return b},_handleRule:function(a,c,b){c={};a=a.selectorText.split(" ");for(b=0;b<a.length;b++){var d=a[b],e=d.indexOf(".");if(d&&0<d.length&&-1!==e){var f=d.indexOf(",")||d.indexOf("["),d=d.substring(e,-1!==f&&f>e?f:d.length);c[d]=!0}}for(var g in c)this._allItems[g]||(c={},c.className=g,c[this._storeRef]=this,this._allItems[g]=c)},_handleReturn:function(){var a=[],c={},b;for(b in this._allItems)c[b]=this._allItems[b];
for(;this._pending.length;)b=this._pending.pop(),b.request._items=c,a.push(b);for(;a.length;)b=a.pop(),b.fetch?this._handleFetchReturn(b.request):this._handleFetchByIdentityReturn(b.request)},_handleFetchByIdentityReturn:function(a){var c=a._items[a.identity];this.isItem(c)||(c=null);a.onItem&&a.onItem.call(a.scope||dojo.global,c)},getIdentity:function(a){this._assertIsItem(a);return this.getValue(a,this._idAttribute)},getIdentityAttributes:function(a){this._assertIsItem(a);return[this._idAttribute]},
fetchItemByIdentity:function(a){a=a||{};a.store||(a.store=this);this._pending&&0<this._pending.length?this._pending.push({request:a}):(this._pending=[{request:a}],this._fetch(a));return a}})}); |
import expect, { spyOn } from 'expect'
import React, { Component } from 'react'
import { render, unmountComponentAtNode } from 'react-dom'
import createHistory from '../createMemoryHistory'
import { routerShape } from '../PropTypes'
import execSteps from './execSteps'
import Router from '../Router'
describe('When a router enters a branch', function () {
let
node,
newsLeaveHookSpy, removeNewsLeaveHook, userLeaveHookSpy,
DashboardRoute, NewsFeedRoute, InboxRoute, RedirectToInboxRoute, MessageRoute, UserRoute, AssignmentRoute,
routes
beforeEach(function () {
node = document.createElement('div')
newsLeaveHookSpy = expect.createSpy()
userLeaveHookSpy = expect.createSpy()
class Dashboard extends Component {
render() {
return (
<div className="Dashboard">
<h1>The Dashboard</h1>
{this.props.children}
</div>
)
}
}
class NewsFeed extends Component {
componentWillMount() {
removeNewsLeaveHook = this.context.router.setRouteLeaveHook(
this.props.route,
() => newsLeaveHookSpy() // Break reference equality.
)
}
render() {
return <div>News</div>
}
}
NewsFeed.contextTypes = {
router: routerShape.isRequired
}
class Inbox extends Component {
render() {
return <div>Inbox</div>
}
}
class UserAssignment extends Component {
render() {
return <div>assignment {this.props.params.assignmentId}</div>
}
}
class User extends Component {
componentWillMount() {
this.context.router.setRouteLeaveHook(
this.props.route,
userLeaveHookSpy
)
}
render() {
return <div>User {this.props.params.userId} {this.props.children}</div>
}
}
User.contextTypes = {
router: routerShape.isRequired
}
NewsFeedRoute = {
path: 'news',
component: NewsFeed,
onEnter(nextState, replace) {
expect(this).toBe(NewsFeedRoute)
expect(nextState.routes).toContain(NewsFeedRoute)
expect(replace).toBeA('function')
},
onChange(prevState, nextState, replace) {
expect(this).toBe(NewsFeedRoute)
expect(prevState).toNotEqual(nextState)
expect(prevState.routes).toContain(NewsFeedRoute)
expect(nextState.routes).toContain(NewsFeedRoute)
expect(replace).toBeA('function')
},
onLeave() {
expect(this).toBe(NewsFeedRoute)
}
}
InboxRoute = {
path: 'inbox',
component: Inbox,
onEnter(nextState, replace) {
expect(this).toBe(InboxRoute)
expect(nextState.routes).toContain(InboxRoute)
expect(replace).toBeA('function')
},
onLeave() {
expect(this).toBe(InboxRoute)
}
}
RedirectToInboxRoute = {
path: 'redirect-to-inbox',
onEnter(nextState, replace) {
expect(this).toBe(RedirectToInboxRoute)
expect(nextState.routes).toContain(RedirectToInboxRoute)
expect(replace).toBeA('function')
replace('/inbox')
},
onLeave() {
expect(this).toBe(RedirectToInboxRoute)
}
}
MessageRoute = {
path: 'messages/:messageID',
onEnter(nextState, replace) {
expect(this).toBe(MessageRoute)
expect(nextState.routes).toContain(MessageRoute)
expect(replace).toBeA('function')
},
onChange(prevState, nextState, replace) {
expect(this).toBe(MessageRoute)
expect(prevState.routes).toContain(MessageRoute)
expect(nextState.routes).toContain(MessageRoute)
expect(replace).toBeA('function')
},
onLeave() {
expect(this).toBe(MessageRoute)
}
}
AssignmentRoute = {
path: 'assignments/:assignmentId',
component: UserAssignment,
onEnter() { expect(this).toBe(AssignmentRoute) },
onLeave() { expect(this).toBe(AssignmentRoute) }
}
UserRoute = {
path: 'users/:userId',
component: User,
childRoutes: [ AssignmentRoute ],
onEnter() { expect(this).toBe(UserRoute) },
onLeave() { expect(this).toBe(UserRoute) }
}
DashboardRoute = {
path: '/',
component: Dashboard,
onEnter(nextState, replace) {
expect(this).toBe(DashboardRoute)
expect(nextState.routes).toContain(DashboardRoute)
expect(replace).toBeA('function')
},
onChange(prevState, nextState, replace) {
expect(this).toBe(DashboardRoute)
expect(prevState).toNotEqual(nextState)
expect(prevState.routes).toContain(DashboardRoute)
expect(nextState.routes).toContain(DashboardRoute)
expect(replace).toBeA('function')
},
onLeave() {
expect(this).toBe(DashboardRoute)
},
childRoutes: [ NewsFeedRoute, InboxRoute, RedirectToInboxRoute, MessageRoute, UserRoute ]
}
routes = [
DashboardRoute
]
})
afterEach(function () {
unmountComponentAtNode(node)
})
it('calls the onEnter hooks of all routes in that branch', function (done) {
const dashboardRouteEnterSpy = spyOn(DashboardRoute, 'onEnter').andCallThrough()
const newsFeedRouteEnterSpy = spyOn(NewsFeedRoute, 'onEnter').andCallThrough()
render(<Router history={createHistory('/news')} routes={routes}/>, node, function () {
expect(dashboardRouteEnterSpy).toHaveBeenCalled()
expect(newsFeedRouteEnterSpy).toHaveBeenCalled()
done()
})
})
it('calls the route leave hooks when leaving the route', function (done) {
const history = createHistory('/news')
render(<Router history={history} routes={routes}/>, node, function () {
expect(newsLeaveHookSpy.calls.length).toEqual(0)
history.push('/inbox')
expect(newsLeaveHookSpy.calls.length).toEqual(1)
history.push('/news')
expect(newsLeaveHookSpy.calls.length).toEqual(1)
history.push('/inbox')
expect(newsLeaveHookSpy.calls.length).toEqual(2)
done()
})
})
it('does not call removed route leave hooks', function (done) {
const history = createHistory('/news')
render(<Router history={history} routes={routes}/>, node, function () {
removeNewsLeaveHook()
history.push('/inbox')
expect(newsLeaveHookSpy).toNotHaveBeenCalled()
done()
})
})
it('does not remove route leave hooks when changing params', function (done) {
const history = createHistory('/users/foo')
// Stub this function to exercise the code path.
history.listenBeforeUnload = () => (() => {})
render(<Router history={history} routes={routes}/>, node, function () {
expect(userLeaveHookSpy.calls.length).toEqual(0)
history.push('/users/bar')
expect(userLeaveHookSpy.calls.length).toEqual(1)
history.push('/users/baz')
expect(userLeaveHookSpy.calls.length).toEqual(2)
done()
})
})
describe('and one of the transition hooks navigates to another route', function () {
it('immediately transitions to the new route', function (done) {
const redirectRouteEnterSpy = spyOn(RedirectToInboxRoute, 'onEnter').andCallThrough()
const redirectRouteLeaveSpy = spyOn(RedirectToInboxRoute, 'onLeave').andCallThrough()
const inboxEnterSpy = spyOn(InboxRoute, 'onEnter').andCallThrough()
render(<Router history={createHistory('/redirect-to-inbox')} routes={routes}/>, node, function () {
expect(this.state.location.pathname).toEqual('/inbox')
expect(redirectRouteEnterSpy).toHaveBeenCalled()
expect(redirectRouteLeaveSpy.calls.length).toEqual(0)
expect(inboxEnterSpy).toHaveBeenCalled()
done()
})
})
})
describe('and then navigates to another branch', function () {
it('calls the onLeave hooks of all routes in the previous branch that are not in the next branch', function (done) {
const dashboardRouteLeaveSpy = spyOn(DashboardRoute, 'onLeave').andCallThrough()
const inboxRouteEnterSpy = spyOn(InboxRoute, 'onEnter').andCallThrough()
const inboxRouteLeaveSpy = spyOn(InboxRoute, 'onLeave').andCallThrough()
const history = createHistory('/inbox')
const steps = [
function () {
expect(inboxRouteEnterSpy).toHaveBeenCalled('InboxRoute.onEnter was not called')
history.push('/news')
},
function () {
expect(inboxRouteLeaveSpy).toHaveBeenCalled('InboxRoute.onLeave was not called')
expect(dashboardRouteLeaveSpy.calls.length).toEqual(0, 'DashboardRoute.onLeave was called')
}
]
const execNextStep = execSteps(steps, done)
render(
<Router history={history}
routes={routes}
onUpdate={execNextStep}
/>, node, execNextStep)
})
})
describe('and then navigates to the same branch, but with different params', function () {
it('calls the onLeave and onEnter hooks of all routes whose params have changed', function (done) {
const dashboardRouteLeaveSpy = spyOn(DashboardRoute, 'onLeave').andCallThrough()
const dashboardRouteChangeSpy = spyOn(DashboardRoute, 'onChange').andCallThrough()
const dashboardRouteEnterSpy = spyOn(DashboardRoute, 'onEnter').andCallThrough()
const messageRouteLeaveSpy = spyOn(MessageRoute, 'onLeave').andCallThrough()
const messageRouteChangeSpy = spyOn(MessageRoute, 'onChange').andCallThrough()
const messageRouteEnterSpy = spyOn(MessageRoute, 'onEnter').andCallThrough()
const history = createHistory('/messages/123')
const steps = [
function () {
expect(dashboardRouteEnterSpy).toHaveBeenCalled('DashboardRoute.onEnter was not called')
expect(messageRouteEnterSpy).toHaveBeenCalled('InboxRoute.onEnter was not called')
history.push('/messages/456')
},
function () {
expect(messageRouteLeaveSpy).toHaveBeenCalled('MessageRoute.onLeave was not called')
expect(messageRouteEnterSpy).toHaveBeenCalled('MessageRoute.onEnter was not called')
expect(messageRouteChangeSpy.calls.length).toEqual(0, 'DashboardRoute.onChange was called')
expect(dashboardRouteChangeSpy).toHaveBeenCalled('DashboardRoute.onChange was not called')
expect(dashboardRouteLeaveSpy.calls.length).toEqual(0, 'DashboardRoute.onLeave was called')
}
]
const execNextStep = execSteps(steps, done)
render(
<Router history={history}
routes={routes}
onUpdate={execNextStep}
/>, node, execNextStep)
})
})
describe('and then navigates to the same branch, but with different parent params', function () {
it('calls the onLeave and onEnter hooks of the parent and children', function (done) {
const parentLeaveSpy = spyOn(UserRoute, 'onLeave').andCallThrough()
const parentEnterSpy = spyOn(UserRoute, 'onEnter').andCallThrough()
const childLeaveSpy = spyOn(AssignmentRoute, 'onLeave').andCallThrough()
const childEnterSpy = spyOn(AssignmentRoute, 'onEnter').andCallThrough()
const history = createHistory('/users/123/assignments/456')
const steps = [
function () {
expect(parentEnterSpy).toHaveBeenCalled()
expect(childEnterSpy).toHaveBeenCalled()
history.push('/users/789/assignments/456')
},
function () {
expect(parentLeaveSpy).toHaveBeenCalled()
expect(childLeaveSpy).toHaveBeenCalled()
expect(parentEnterSpy).toHaveBeenCalled()
expect(childEnterSpy).toHaveBeenCalled()
}
]
const execNextStep = execSteps(steps, done)
render(
<Router history={history}
routes={routes}
onUpdate={execNextStep}
/>, node, execNextStep)
})
})
describe('and then the query changes', function () {
it('calls the onEnter hooks of all routes in that branch', function (done) {
const newsFeedRouteEnterSpy = spyOn(NewsFeedRoute, 'onEnter').andCallThrough()
const newsFeedRouteChangeSpy = spyOn(NewsFeedRoute, 'onChange').andCallThrough()
const history = createHistory('/inbox')
render(<Router history={history} routes={routes}/>, node, function () {
history.push({ pathname: '/news', query: { q: 1 } })
expect(newsFeedRouteChangeSpy.calls.length).toEqual(0, 'NewsFeedRoute.onChange was called')
expect(newsFeedRouteEnterSpy.calls.length).toEqual(1)
history.push({ pathname: '/news', query: { q: 2 } })
expect(newsFeedRouteChangeSpy).toHaveBeenCalled('NewsFeedRoute.onChange was not called')
expect(newsFeedRouteEnterSpy.calls.length).toEqual(1)
done()
})
})
})
})
|
var _ = require("underscore");
exports.paragraph = paragraph;
exports.run = run;
exports._elements = elements;
exports.getDescendantsOfType = getDescendantsOfType;
exports.getDescendants = getDescendants;
function paragraph(transform) {
return elementsOfType("paragraph", transform);
}
function run(transform) {
return elementsOfType("run", transform);
}
function elementsOfType(elementType, transform) {
return elements(function(element) {
if (element.type === elementType) {
return transform(element);
} else {
return element;
}
});
}
function elements(transform) {
return function transformElement(element) {
if (element.children) {
var children = _.map(element.children, transformElement);
element = _.extend(element, {children: children});
}
return transform(element);
};
}
function getDescendantsOfType(element, type) {
return getDescendants(element).filter(function(descendant) {
return descendant.type === type;
});
}
function getDescendants(element) {
var descendants = [];
visitDescendants(element, function(descendant) {
descendants.push(descendant);
});
return descendants;
}
function visitDescendants(element, visit) {
if (element.children) {
element.children.forEach(function(child) {
visitDescendants(child, visit);
visit(child);
});
}
}
|
angular.module("lilypad.services")
.factory('SearchFactory', function($http, appConfig) {
var factory = {};
factory.searchLocations = function(phrase) {
var url = appConfig.baseUrl + '/search/locations';
var req = {
'method' :'GET',
'url' : url,
'headers': { 'phrase' : phrase }
};
return $http(req);
};
factory.searchUsers = function(phrase) {
var url = appConfig.baseUrl + '/search/users';
var req = {
'method' :'GET',
'url' : url,
'headers': { 'phrase' : phrase }
};
return $http(req);
};
return factory;
})
|
module.exports.startApp = function(
console,
startServer,
startWorkers
) {
return function() {
console.log('starting app');
startWorkers();
startServer();
};
};
|
var SceneElementAdapter = require("./scene-element.js");
var CameraConfiguration = require("../scene/configuration.js");
var Resource = require("../../../resource");
var DEFAULT_CAMERA_MODEL = "urn:xml3d:view:perspective";
/**
* Adapter for <view>
* @param {RenderAdapterFactory} factory
* @param {Element} node
* @extends SceneElementAdapter
* @constructor
*/
var ViewRenderAdapter = function (factory, node) {
SceneElementAdapter.call(this, factory, node, false, false);
this.dataAdapter = Resource.getAdapter(node, "data");
this.createRenderNode();
};
XML3D.createClass(ViewRenderAdapter, SceneElementAdapter, {
createRenderNode: function () {
var parent = this.getParentRenderAdapter();
var parentNode = parent.getRenderNode ? parent.getRenderNode() : this.factory.renderer.scene.createRootNode();
this.renderNode = this.factory.renderer.scene.createRenderView({
camera: this.createCameraConfiguration(), parent: parentNode
});
this.updateLocalMatrix();
},
createCameraConfiguration: function () {
var model = this.node.hasAttribute("model") ? this.node.getAttribute("model") : DEFAULT_CAMERA_MODEL;
return new CameraConfiguration(model, this.dataAdapter.getXflowNode(), {name: this.node.id});
},
/* Interface method */
getViewMatrix: function () {
var m = new XML3D.Mat4();
this.renderNode.getWorldToViewMatrix(m.data);
return m;
},
/**
* returns view2world matrix
* @return {mat4}
*/
getWorldMatrix: function () {
var m = new XML3D.Mat4();
this.renderNode.getViewToWorldMatrix(m.data);
return m;
},
getProjectionMatrix: function () {
var m = new XML3D.Mat4();
this.renderNode.getProjectionMatrix(m.data);
return m;
},
getRootAdapter: function() {
var parent = this.getParentRenderAdapter();
var nextParent;
while ((nextParent = parent.getParentRenderAdapter()) !== null) {
parent = nextParent;
}
return parent;
},
dispose: function() {
this.getRootAdapter().activeViewChanged();
SceneElementAdapter.prototype.dispose.call(this);
},
attributeChangedCallback: function (name, oldValue, newValue) {
SceneElementAdapter.prototype.attributeChangedCallback.call(this, name, oldValue, newValue);
switch (name) {
case "model":
this.renderNode.remove();
this.createRenderNode();
break;
}
}
});
// Export
module.exports = ViewRenderAdapter;
|
// @flow
export default function( duration: number ): Promise<any> {
return new Promise( function( resolve ) {
setTimeout( function() {
resolve()
}, duration )
})
}
|
define([], function() {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
rsComboSymbolsRange = '\\u20d0-\\u20f0',
rsDingbatRange = '\\u2700-\\u27bf',
rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
rsPunctuationRange = '\\u2000-\\u206f',
rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
rsVarRange = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsApos = "['\u2019]",
rsBreak = '[' + rsBreakRange + ']',
rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;
/** Used to match complex or compound words. */
var reUnicodeWord = RegExp([
rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
rsUpper + '+' + rsOptUpperContr,
rsDigits,
rsEmoji
].join('|'), 'g');
/**
* Splits a Unicode `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function unicodeWords(string) {
return string.match(reUnicodeWord) || [];
}
return unicodeWords;
});
|
define({
//begin v1.x content
smiley: "Txertatu emotikonoa",
emoticonSmile: "irribarre handia",
emoticonLaughing: "barrea",
emoticonWink: "begi-keinua",
emoticonGrin: "irribarrea",
emoticonCool: "bikain",
emoticonAngry: "haserre",
emoticonHalf: "erdia",
emoticonEyebrow: "bekaina",
emoticonFrown: "bekozkotu",
emoticonShy: "lotsatia",
emoticonGoofy: "tuntuna",
emoticonOops: "ene!",
emoticonTongue: "mihia",
emoticonIdea: "ideia",
emoticonYes: "bai",
emoticonNo: "ez",
emoticonAngel: "aingerua",
emoticonCrying: "negarrez",
emoticonHappy: "pozik"
//end v1.x content
});
|
(function(window, angular, undefined) {'use strict';
angular.module('gs.flash-message', ['ngSanitize'])
.directive('gsFlashMessage', ['$sce', function ($sce) {
function _messageWrapper (messages) {
messages = messages || {};
_.forEach(Object.keys(messages), function (key) {
messages[key] = (_.isArray(messages[key])
? messages[key]
: (_.isString(messages[key])
? [$sce.trustAsHtml(messages[key])]
: []));
});
return messages;
}
function _relevantFlashMessages (params, key) {
return params.flash && params.flash[key];
}
return {
restrict: 'A',
scope: true,
template:
'<div class="alert" ng-if="flashMessagesPopulated()">' +
'<div ng-if="messageList.length" ng-repeat="(key, messageList) in messages" class="alert--message alert--message__{{ key }}"">' +
'<span class="alert--message--content" ng-repeat="message in messageList track by $index" ng-bind-html="message"></span>' +
'<a href ng-click="close()">' +
'<i class="alert--message--remove-icon"></i>' +
'</a>' +
'</div>' +
'</div>',
link: function (scope, el, attrs) {
var key = (attrs.gsFlashMessage || attrs.dataGsFlashMessage);
if (!key.length) {
return;
}
angular.extend(scope, {messages: _messageWrapper({})});
scope.$on('$stateChangeSuccess', function (ev, toS, toP, fromS, fromP) {
var messages = _relevantFlashMessages(fromP, key);
if (messages) {
scope.messages = _messageWrapper(messages);
} else {
scope.close();
}
return scope.messages;
});
scope.$on('flash:' + key, function (ev, messages) {
scope.messages = _messageWrapper(messages);
return scope.messages;
});
scope.close = function () {
scope.messages = _messageWrapper({});
return scope.messages;
};
scope.flashMessagesPopulated = function () {
return _.any(scope.messages, 'length');
};
}
};
}]);
})(window, window.angular);
|
const HistoryData_Schema = {
name: "HistoryData",
fields: [
{ name: "dataValues", isArray: true, fieldType:"DataValue" }
]
};
exports.HistoryData_Schema = HistoryData_Schema; |
import "./office/styles.less";
import "../static/favicon.ico";
import App from "./office/app";
import hydrate from "./shared/utils/hydrate";
import configureStore from "./office/store";
process.env.MODULE = "office";
const store = configureStore(window.__INITIAL_STATE__);
hydrate(App, store);
if (module.hot) {
module.hot.accept("./office/app", () => {
hydrate(App, store);
});
}
|
(function (root, factory) {
// Node.
if(typeof module === 'object' && typeof module.exports === 'object') {
exports = module.exports = factory();
}
// AMD.
if(typeof define === 'function' && define.amd) {
define(["terraformer/terraformer"],factory);
}
// Browser Global.
if(typeof root.navigator === "object") {
if (typeof root.Terraformer === "undefined"){
root.Terraformer = {};
}
root.Terraformer.ArcGIS = factory();
}
}(this, function() {
var exports = { };
var Terraformer;
// Local Reference To Browser Global
if(typeof this.navigator === "object") {
Terraformer = this.Terraformer;
}
// Setup Node Dependencies
if(typeof module === 'object' && typeof module.exports === 'object') {
Terraformer = require('terraformer');
}
// Setup AMD Dependencies
if(arguments[0] && typeof define === 'function' && define.amd) {
Terraformer = arguments[0];
}
// This function flattens holes in multipolygons to one array of polygons
function flattenHoles(array){
var output = [], polygon;
for (var i = 0; i < array.length; i++) {
polygon = array[i];
if(polygon.length > 1){
for (var ii = 0; ii < polygon.length; ii++) {
output.push(polygon[ii]);
}
} else {
output.push(polygon[0]);
}
}
return output;
}
function findGeometryType(input){
if(input.x && input.y){
return "Point";
}
if(input.points){
return "MultiPoint";
}
if(input.paths) {
return (input.paths.length === 1) ? "LineString" : "MultiLineString";
}
if(input.rings) {
return (input.rings.length === 1) ? "Polygon" : "MultiPolygon";
}
if(input.attributes && input.geometry) {
return "Feature";
}
throw "Terraformer: invalid ArcGIS input. Are you sure your data is properly formatted?";
}
// this takes an arcgis geometry and converts it to geojson
function parse(arcgis){
var type = findGeometryType(arcgis);
var inputSpatialReference = (arcgis.geometry) ? arcgis.geometry.spatialReference : arcgis.spatialReference;
var geojson = {
type: type
};
if(type === "Feature") {
geojson.properties = arcgis.attributes;
}
switch(type){
case "Point":
geojson.coordinates = [arcgis.x, arcgis.y];
break;
case "MultiPoint":
geojson.coordinates = arcgis.points;
break;
case "LineString":
geojson.coordinates = arcgis.paths[0];
break;
case "MultiLineString":
geojson.coordinates = arcgis.paths;
break;
case "Polygon":
geojson.coordinates = arcgis.rings;
break;
case "MultiPolygon":
geojson.coordinates = [arcgis.rings];
break;
case "Feature":
geojson.geometry = parse(arcgis.geometry);
break;
}
//convert spatial ref if needed
if(inputSpatialReference && inputSpatialReference.wkid === 102100){
geojson = Terraformer.toGeographic(geojson);
}
return new Terraformer.Primitive(geojson);
}
// this takes a point line or polygon geojson object and converts it to the appropriate
function convert(geojson, sr){
var spatialReference = (sr) ? sr : { wkid: 4326 };
var result = {}, i;
switch(geojson.type){
case "Point":
result.x = geojson.coordinates[0];
result.y = geojson.coordinates[1];
result.spatialReference = spatialReference;
break;
case "MultiPoint":
result.points = geojson.coordinates;
result.spatialReference = spatialReference;
break;
case "LineString":
result.paths = [geojson.coordinates];
result.spatialReference = spatialReference;
break;
case "MultiLineString":
result.paths = geojson.coordinates;
result.spatialReference = spatialReference;
break;
case "Polygon":
result.rings = geojson.coordinates;
result.spatialReference = spatialReference;
break;
case "MultiPolygon":
result.rings = flattenHoles(geojson.coordinates);
result.spatialReference = spatialReference;
break;
case "Feature":
result.geometry = convert(geojson.geometry);
result.attributes = geojson.properties;
break;
case "FeatureCollection":
result = [];
for (i = 0; i < geojson.features.length; i++){
result.push(convert(geojson.features[i]));
}
break;
case "GeometryCollection":
result = [];
for (i = 0; i < geojson.geometries.length; i++){
result.push(convert(geojson.geometries[i]));
}
break;
}
return result;
}
exports.parse = parse;
exports.convert = convert;
return exports;
})); |
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @constructor
* @extends {WebInspector.Object}
*/
WebInspector.DebuggerModel = function()
{
InspectorBackend.registerDebuggerDispatcher(new WebInspector.DebuggerDispatcher(this));
this._debuggerPausedDetails = null;
/**
* @type {Object.<string, WebInspector.Script>}
*/
this._scripts = {};
this._scriptsBySourceURL = {};
this._canSetScriptSource = false;
this._breakpointsActive = true;
WebInspector.settings.pauseOnExceptionStateString = WebInspector.settings.createSetting("pauseOnExceptionStateString", WebInspector.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions);
WebInspector.settings.pauseOnExceptionStateString.addChangeListener(this._pauseOnExceptionStateChanged, this);
this.enableDebugger();
}
// Keep these in sync with WebCore::ScriptDebugServer
WebInspector.DebuggerModel.PauseOnExceptionsState = {
DontPauseOnExceptions : "none",
PauseOnAllExceptions : "all",
PauseOnUncaughtExceptions: "uncaught"
};
/**
* @constructor
* @implements {WebInspector.RawLocation}
* @param {string} scriptId
* @param {number} lineNumber
* @param {number} columnNumber
*/
WebInspector.DebuggerModel.Location = function(scriptId, lineNumber, columnNumber)
{
this.scriptId = scriptId;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
}
WebInspector.DebuggerModel.Events = {
DebuggerWasEnabled: "DebuggerWasEnabled",
DebuggerWasDisabled: "DebuggerWasDisabled",
DebuggerPaused: "DebuggerPaused",
DebuggerResumed: "DebuggerResumed",
ParsedScriptSource: "ParsedScriptSource",
FailedToParseScriptSource: "FailedToParseScriptSource",
BreakpointResolved: "BreakpointResolved",
GlobalObjectCleared: "GlobalObjectCleared",
CallFrameSelected: "CallFrameSelected",
ExecutionLineChanged: "ExecutionLineChanged",
ConsoleCommandEvaluatedInSelectedCallFrame: "ConsoleCommandEvaluatedInSelectedCallFrame",
BreakpointsActiveStateChanged: "BreakpointsActiveStateChanged"
}
WebInspector.DebuggerModel.BreakReason = {
DOM: "DOM",
EventListener: "EventListener",
XHR: "XHR",
Exception: "exception",
Assert: "assert",
CSPViolation: "CSPViolation"
}
WebInspector.DebuggerModel.prototype = {
/**
* @return {boolean}
*/
debuggerEnabled: function()
{
return !!this._debuggerEnabled;
},
enableDebugger: function()
{
if (this._debuggerEnabled)
return;
function callback(error, result)
{
this._canSetScriptSource = result;
}
DebuggerAgent.canSetScriptSource(callback.bind(this));
DebuggerAgent.enable(this._debuggerWasEnabled.bind(this));
},
disableDebugger: function()
{
if (!this._debuggerEnabled)
return;
DebuggerAgent.disable(this._debuggerWasDisabled.bind(this));
},
/**
* @return {boolean}
*/
canSetScriptSource: function()
{
return this._canSetScriptSource;
},
_debuggerWasEnabled: function()
{
this._debuggerEnabled = true;
this._pauseOnExceptionStateChanged();
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasEnabled);
},
_pauseOnExceptionStateChanged: function()
{
DebuggerAgent.setPauseOnExceptions(WebInspector.settings.pauseOnExceptionStateString.get());
},
_debuggerWasDisabled: function()
{
this._debuggerEnabled = false;
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasDisabled);
},
/**
* @param {WebInspector.DebuggerModel.Location} rawLocation
*/
continueToLocation: function(rawLocation)
{
DebuggerAgent.continueToLocation(rawLocation);
},
/**
* @param {WebInspector.DebuggerModel.Location} rawLocation
* @param {string} condition
* @param {function(?DebuggerAgent.BreakpointId, Array.<WebInspector.DebuggerModel.Location>):void=} callback
*/
setBreakpointByScriptLocation: function(rawLocation, condition, callback)
{
var script = this.scriptForId(rawLocation.scriptId);
if (script.sourceURL)
this.setBreakpointByURL(script.sourceURL, rawLocation.lineNumber, rawLocation.columnNumber, condition, callback);
else
this.setBreakpointBySourceId(rawLocation, condition, callback);
},
/**
* @param {string} url
* @param {number} lineNumber
* @param {number=} columnNumber
* @param {string=} condition
* @param {function(?DebuggerAgent.BreakpointId, Array.<WebInspector.DebuggerModel.Location>)=} callback
*/
setBreakpointByURL: function(url, lineNumber, columnNumber, condition, callback)
{
// Adjust column if needed.
var minColumnNumber = 0;
var scripts = this._scriptsBySourceURL[url] || [];
for (var i = 0, l = scripts.length; i < l; ++i) {
var script = scripts[i];
if (lineNumber === script.lineOffset)
minColumnNumber = minColumnNumber ? Math.min(minColumnNumber, script.columnOffset) : script.columnOffset;
}
columnNumber = Math.max(columnNumber, minColumnNumber);
/**
* @this {WebInspector.DebuggerModel}
* @param {?Protocol.Error} error
* @param {DebuggerAgent.BreakpointId} breakpointId
* @param {Array.<DebuggerAgent.Location>} locations
*/
function didSetBreakpoint(error, breakpointId, locations)
{
if (callback) {
var rawLocations = /** @type {Array.<WebInspector.DebuggerModel.Location>} */ (locations);
callback(error ? null : breakpointId, rawLocations);
}
}
DebuggerAgent.setBreakpointByUrl(lineNumber, url, undefined, columnNumber, condition, didSetBreakpoint.bind(this));
WebInspector.userMetrics.ScriptsBreakpointSet.record();
},
/**
* @param {WebInspector.DebuggerModel.Location} rawLocation
* @param {string} condition
* @param {function(?DebuggerAgent.BreakpointId, Array.<WebInspector.DebuggerModel.Location>)=} callback
*/
setBreakpointBySourceId: function(rawLocation, condition, callback)
{
/**
* @this {WebInspector.DebuggerModel}
* @param {?Protocol.Error} error
* @param {DebuggerAgent.BreakpointId} breakpointId
* @param {DebuggerAgent.Location} actualLocation
*/
function didSetBreakpoint(error, breakpointId, actualLocation)
{
if (callback) {
var rawLocation = /** @type {WebInspector.DebuggerModel.Location} */ (actualLocation);
callback(error ? null : breakpointId, [rawLocation]);
}
}
DebuggerAgent.setBreakpoint(rawLocation, condition, didSetBreakpoint.bind(this));
WebInspector.userMetrics.ScriptsBreakpointSet.record();
},
/**
* @param {DebuggerAgent.BreakpointId} breakpointId
* @param {function(?Protocol.Error)=} callback
*/
removeBreakpoint: function(breakpointId, callback)
{
DebuggerAgent.removeBreakpoint(breakpointId, callback);
},
/**
* @param {DebuggerAgent.BreakpointId} breakpointId
* @param {DebuggerAgent.Location} location
*/
_breakpointResolved: function(breakpointId, location)
{
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.BreakpointResolved, {breakpointId: breakpointId, location: location});
},
_globalObjectCleared: function()
{
this._setDebuggerPausedDetails(null);
this._reset();
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.GlobalObjectCleared);
},
_reset: function()
{
this._scripts = {};
this._scriptsBySourceURL = {};
},
/**
* @return {Object.<string, WebInspector.Script>}
*/
get scripts()
{
return this._scripts;
},
/**
* @param {DebuggerAgent.ScriptId} scriptId
* @return {WebInspector.Script}
*/
scriptForId: function(scriptId)
{
return this._scripts[scriptId] || null;
},
/**
* @param {DebuggerAgent.ScriptId} scriptId
* @param {string} newSource
* @param {function(?Protocol.Error)} callback
*/
setScriptSource: function(scriptId, newSource, callback)
{
this._scripts[scriptId].editSource(newSource, this._didEditScriptSource.bind(this, scriptId, newSource, callback));
},
/**
* @param {DebuggerAgent.ScriptId} scriptId
* @param {string} newSource
* @param {function(?Protocol.Error)} callback
* @param {?Protocol.Error} error
* @param {Array.<DebuggerAgent.CallFrame>=} callFrames
*/
_didEditScriptSource: function(scriptId, newSource, callback, error, callFrames)
{
callback(error);
if (!error && callFrames && callFrames.length)
this._pausedScript(callFrames, this._debuggerPausedDetails.reason, this._debuggerPausedDetails.auxData);
},
/**
* @return {Array.<DebuggerAgent.CallFrame>}
*/
get callFrames()
{
return this._debuggerPausedDetails ? this._debuggerPausedDetails.callFrames : null;
},
/**
* @return {?WebInspector.DebuggerPausedDetails}
*/
debuggerPausedDetails: function()
{
return this._debuggerPausedDetails;
},
/**
* @param {?WebInspector.DebuggerPausedDetails} debuggerPausedDetails
*/
_setDebuggerPausedDetails: function(debuggerPausedDetails)
{
if (this._debuggerPausedDetails)
this._debuggerPausedDetails.dispose();
this._debuggerPausedDetails = debuggerPausedDetails;
if (this._debuggerPausedDetails)
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPausedDetails);
if (debuggerPausedDetails) {
this.setSelectedCallFrame(debuggerPausedDetails.callFrames[0]);
DebuggerAgent.setOverlayMessage(WebInspector.UIString("Paused in debugger"));
} else {
this.setSelectedCallFrame(null);
DebuggerAgent.setOverlayMessage();
}
},
/**
* @param {Array.<DebuggerAgent.CallFrame>} callFrames
* @param {string} reason
* @param {*} auxData
*/
_pausedScript: function(callFrames, reason, auxData)
{
this._setDebuggerPausedDetails(new WebInspector.DebuggerPausedDetails(this, callFrames, reason, auxData));
},
_resumedScript: function()
{
this._setDebuggerPausedDetails(null);
if (this._executionLineLiveLocation)
this._executionLineLiveLocation.dispose();
this._executionLineLiveLocation = null;
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerResumed);
},
/**
* @param {DebuggerAgent.ScriptId} scriptId
* @param {string} sourceURL
* @param {number} startLine
* @param {number} startColumn
* @param {number} endLine
* @param {number} endColumn
* @param {boolean} isContentScript
* @param {string=} sourceMapURL
* @param {boolean=} hasSourceURL
*/
_parsedScriptSource: function(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL)
{
var script = new WebInspector.Script(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL);
if (!script.isAnonymousScript() && !script.isInlineScript()) {
var existingScripts = this._scriptsBySourceURL[script.sourceURL] || [];
for (var i = 0; i < existingScripts.length; ++i) {
if (existingScripts[i].isInlineScript()) {
script.setIsDynamicScript(true);
break;
}
}
}
this._registerScript(script);
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ParsedScriptSource, script);
},
/**
* @param {WebInspector.Script} script
*/
_registerScript: function(script)
{
this._scripts[script.scriptId] = script;
if (script.sourceURL) {
var scripts = this._scriptsBySourceURL[script.sourceURL];
if (!scripts) {
scripts = [];
this._scriptsBySourceURL[script.sourceURL] = scripts;
}
scripts.push(script);
}
},
/**
* @param {WebInspector.Script} script
* @param {number} lineNumber
* @param {number} columnNumber
* @return {WebInspector.DebuggerModel.Location}
*/
createRawLocation: function(script, lineNumber, columnNumber)
{
if (script.sourceURL)
return this.createRawLocationByURL(script.sourceURL, lineNumber, columnNumber)
return new WebInspector.DebuggerModel.Location(script.scriptId, lineNumber, columnNumber);
},
/**
* @param {string} sourceURL
* @param {number} lineNumber
* @param {number} columnNumber
* @return {WebInspector.DebuggerModel.Location}
*/
createRawLocationByURL: function(sourceURL, lineNumber, columnNumber)
{
var closestScript = null;
var scripts = this._scriptsBySourceURL[sourceURL] || [];
for (var i = 0, l = scripts.length; i < l; ++i) {
var script = scripts[i];
if (!closestScript)
closestScript = script;
if (script.lineOffset > lineNumber || (script.lineOffset === lineNumber && script.columnOffset > columnNumber))
continue;
if (script.endLine < lineNumber || (script.endLine === lineNumber && script.endColumn <= columnNumber))
continue;
closestScript = script;
break;
}
return closestScript ? new WebInspector.DebuggerModel.Location(closestScript.scriptId, lineNumber, columnNumber) : null;
},
/**
* @return {boolean}
*/
isPaused: function()
{
return !!this.debuggerPausedDetails();
},
/**
* @param {?WebInspector.DebuggerModel.CallFrame} callFrame
*/
setSelectedCallFrame: function(callFrame)
{
if (this._executionLineLiveLocation)
this._executionLineLiveLocation.dispose();
delete this._executionLineLiveLocation;
this._selectedCallFrame = callFrame;
if (!this._selectedCallFrame)
return;
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.CallFrameSelected, callFrame);
function updateExecutionLine(uiLocation)
{
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ExecutionLineChanged, uiLocation);
}
this._executionLineLiveLocation = callFrame.script.createLiveLocation(callFrame.location, updateExecutionLine.bind(this));
},
/**
* @return {?WebInspector.DebuggerModel.CallFrame}
*/
selectedCallFrame: function()
{
return this._selectedCallFrame;
},
/**
* @param {string} code
* @param {string} objectGroup
* @param {boolean} includeCommandLineAPI
* @param {boolean} doNotPauseOnExceptionsAndMuteConsole
* @param {boolean} returnByValue
* @param {boolean} generatePreview
* @param {function(?WebInspector.RemoteObject, boolean, RuntimeAgent.RemoteObject=)} callback
*/
evaluateOnSelectedCallFrame: function(code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback)
{
/**
* @param {?RuntimeAgent.RemoteObject} result
* @param {boolean=} wasThrown
*/
function didEvaluate(result, wasThrown)
{
if (returnByValue)
callback(null, !!wasThrown, wasThrown ? null : result);
else
callback(WebInspector.RemoteObject.fromPayload(result), !!wasThrown);
if (objectGroup === "console")
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ConsoleCommandEvaluatedInSelectedCallFrame);
}
this.selectedCallFrame().evaluate(code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, didEvaluate.bind(this));
},
/**
* @param {function(Object)} callback
*/
getSelectedCallFrameVariables: function(callback)
{
var result = { this: true };
var selectedCallFrame = this._selectedCallFrame;
if (!selectedCallFrame)
callback(result);
var pendingRequests = 0;
function propertiesCollected(properties)
{
for (var i = 0; properties && i < properties.length; ++i)
result[properties[i].name] = true;
if (--pendingRequests == 0)
callback(result);
}
for (var i = 0; i < selectedCallFrame.scopeChain.length; ++i) {
var scope = selectedCallFrame.scopeChain[i];
var object = WebInspector.RemoteObject.fromPayload(scope.object);
pendingRequests++;
object.getAllProperties(propertiesCollected);
}
},
/**
* @param {boolean} active
*/
setBreakpointsActive: function(active)
{
if (this._breakpointsActive === active)
return;
this._breakpointsActive = active;
DebuggerAgent.setBreakpointsActive(active);
this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.BreakpointsActiveStateChanged, active);
},
/**
* @return {boolean}
*/
breakpointsActive: function()
{
return this._breakpointsActive;
},
/**
* @param {WebInspector.DebuggerModel.Location} rawLocation
* @param {function(WebInspector.UILocation):(boolean|undefined)} updateDelegate
* @return {WebInspector.Script.Location}
*/
createLiveLocation: function(rawLocation, updateDelegate)
{
var script = this._scripts[rawLocation.scriptId];
return script.createLiveLocation(rawLocation, updateDelegate);
},
/**
* @param {WebInspector.DebuggerModel.Location} rawLocation
* @return {?WebInspector.UILocation}
*/
rawLocationToUILocation: function(rawLocation)
{
var script = this._scripts[rawLocation.scriptId];
if (!script)
return null;
return script.rawLocationToUILocation(rawLocation.lineNumber, rawLocation.columnNumber);
},
/**
* Handles notification from JavaScript VM about updated stack (liveedit or frame restart action).
* @this {WebInspector.DebuggerModel}
* @param {Array.<DebuggerAgent.CallFrame>=} newCallFrames
* @param {Object=} details
*/
callStackModified: function(newCallFrames, details)
{
// FIXME: declare this property in protocol and in JavaScript.
if (details && details["stack_update_needs_step_in"])
DebuggerAgent.stepInto();
else {
if (newCallFrames && newCallFrames.length)
this._pausedScript(newCallFrames, this._debuggerPausedDetails.reason, this._debuggerPausedDetails.auxData);
}
},
__proto__: WebInspector.Object.prototype
}
WebInspector.DebuggerEventTypes = {
JavaScriptPause: 0,
JavaScriptBreakpoint: 1,
NativeBreakpoint: 2
};
/**
* @constructor
* @implements {DebuggerAgent.Dispatcher}
* @param {WebInspector.DebuggerModel} debuggerModel
*/
WebInspector.DebuggerDispatcher = function(debuggerModel)
{
this._debuggerModel = debuggerModel;
}
WebInspector.DebuggerDispatcher.prototype = {
/**
* @param {Array.<DebuggerAgent.CallFrame>} callFrames
* @param {string} reason
* @param {Object=} auxData
*/
paused: function(callFrames, reason, auxData)
{
this._debuggerModel._pausedScript(callFrames, reason, auxData);
},
resumed: function()
{
this._debuggerModel._resumedScript();
},
globalObjectCleared: function()
{
this._debuggerModel._globalObjectCleared();
},
/**
* @param {DebuggerAgent.ScriptId} scriptId
* @param {string} sourceURL
* @param {number} startLine
* @param {number} startColumn
* @param {number} endLine
* @param {number} endColumn
* @param {boolean=} isContentScript
* @param {string=} sourceMapURL
* @param {boolean=} hasSourceURL
*/
scriptParsed: function(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL)
{
this._debuggerModel._parsedScriptSource(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, !!isContentScript, sourceMapURL, hasSourceURL);
},
/**
* @param {string} sourceURL
* @param {string} source
* @param {number} startingLine
* @param {number} errorLine
* @param {string} errorMessage
*/
scriptFailedToParse: function(sourceURL, source, startingLine, errorLine, errorMessage)
{
},
/**
* @param {DebuggerAgent.BreakpointId} breakpointId
* @param {DebuggerAgent.Location} location
*/
breakpointResolved: function(breakpointId, location)
{
this._debuggerModel._breakpointResolved(breakpointId, location);
}
}
/**
* @constructor
* @param {WebInspector.Script} script
* @param {DebuggerAgent.CallFrame} payload
*/
WebInspector.DebuggerModel.CallFrame = function(script, payload)
{
this._script = script;
this._payload = payload;
this._locations = [];
}
WebInspector.DebuggerModel.CallFrame.prototype = {
/**
* @return {WebInspector.Script}
*/
get script()
{
return this._script;
},
/**
* @return {string}
*/
get type()
{
return this._payload.type;
},
/**
* @return {string}
*/
get id()
{
return this._payload.callFrameId;
},
/**
* @return {Array.<DebuggerAgent.Scope>}
*/
get scopeChain()
{
return this._payload.scopeChain;
},
/**
* @return {RuntimeAgent.RemoteObject}
*/
get this()
{
return this._payload.this;
},
/**
* @return {string}
*/
get functionName()
{
return this._payload.functionName;
},
/**
* @return {WebInspector.DebuggerModel.Location}
*/
get location()
{
var rawLocation = /** @type {WebInspector.DebuggerModel.Location} */ (this._payload.location);
return rawLocation;
},
/**
* @param {string} code
* @param {string} objectGroup
* @param {boolean} includeCommandLineAPI
* @param {boolean} doNotPauseOnExceptionsAndMuteConsole
* @param {boolean} returnByValue
* @param {boolean} generatePreview
* @param {function(?RuntimeAgent.RemoteObject, boolean=)=} callback
*/
evaluate: function(code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback)
{
/**
* @this {WebInspector.DebuggerModel.CallFrame}
* @param {?Protocol.Error} error
* @param {RuntimeAgent.RemoteObject} result
* @param {boolean=} wasThrown
*/
function didEvaluateOnCallFrame(error, result, wasThrown)
{
if (error) {
console.error(error);
callback(null, false);
return;
}
callback(result, wasThrown);
}
DebuggerAgent.evaluateOnCallFrame(this._payload.callFrameId, code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, didEvaluateOnCallFrame.bind(this));
},
/**
* @param {function(?Protocol.Error=)=} callback
*/
restart: function(callback)
{
/**
* @this {WebInspector.DebuggerModel.CallFrame}
* @param {?Protocol.Error} error
* @param {Array.<DebuggerAgent.CallFrame>=} callFrames
* @param {Object=} details
*/
function protocolCallback(error, callFrames, details)
{
if (!error)
WebInspector.debuggerModel.callStackModified(callFrames, details);
if (callback)
callback(error);
}
DebuggerAgent.restartFrame(this._payload.callFrameId, protocolCallback);
},
/**
* @param {function(WebInspector.UILocation):(boolean|undefined)} updateDelegate
*/
createLiveLocation: function(updateDelegate)
{
var location = this._script.createLiveLocation(this.location, updateDelegate);
this._locations.push(location);
return location;
},
dispose: function(updateDelegate)
{
for (var i = 0; i < this._locations.length; ++i)
this._locations[i].dispose();
this._locations = [];
}
}
/**
* @constructor
* @param {WebInspector.DebuggerModel} model
* @param {Array.<DebuggerAgent.CallFrame>} callFrames
* @param {string} reason
* @param {*} auxData
*/
WebInspector.DebuggerPausedDetails = function(model, callFrames, reason, auxData)
{
this.callFrames = [];
for (var i = 0; i < callFrames.length; ++i) {
var callFrame = callFrames[i];
var script = model.scriptForId(callFrame.location.scriptId);
if (script)
this.callFrames.push(new WebInspector.DebuggerModel.CallFrame(script, callFrame));
}
this.reason = reason;
this.auxData = auxData;
}
WebInspector.DebuggerPausedDetails.prototype = {
dispose: function()
{
for (var i = 0; i < this.callFrames.length; ++i) {
var callFrame = this.callFrames[i];
callFrame.dispose();
}
}
}
/**
* @type {?WebInspector.DebuggerModel}
*/
WebInspector.debuggerModel = null;
|
import {expect} from 'chai';
import {
graphql,
GraphQLSchema,
GraphQLObjectType
} from 'graphql';
import GraphQLGeneric from './generic';
class Unknown {
constructor(field) {
this.field = field;
}
}
describe('GraphQL generic type', () => {
it('should coerse generic object to string', () => {
const unknown = new Unknown('foo');
expect(GraphQLGeneric.serialize(unknown)).to.equal('{\'field\':\'foo\'}');
});
it('should stringifiy generic types', async () => {
const unknown = new Unknown('bar');
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
foo: {
type: GraphQLGeneric,
resolve: () => unknown
}
}
})
});
return expect(
await graphql(schema, `{ foo }`)
).to.deep.equal({
data: {
foo: GraphQLGeneric.serialize(unknown)
}
});
});
it('should handle null', async () => {
const unknown = null;
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
foo: {
type: GraphQLGeneric,
resolve: () => unknown
}
}
})
});
return expect(
await graphql(schema, `{ foo }`)
).to.deep.equal({
data: {
foo: null
}
});
});
it('should handle generic types as input', async () => {
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
foo: {
type: GraphQLGeneric,
args: {
bar: {
type: GraphQLGeneric
}
},
resolve: (_, {bar}) => {
return new Unknown(bar.field + '-qux');
}
}
}
})
});
const unknown = GraphQLGeneric.serialize(new Unknown('baz'));
return expect(
await graphql(schema, `{ foo(bar: "${unknown}") }`)
).to.deep.equal({
data: {
foo: unknown.replace('baz', 'baz-qux')
}
});
});
});
|
if(module.exports){var optionsPage=module.exports;safari.extension.settings.addEventListener("change",function(a){"open-options"==a.key&&optionsPage.open()},!1)};
|
const path = require('path');
const settings = require('../manifest');
const printConfig = require('../../utils/printConfig');
const paths = settings.paths;
const webpack = require('webpack');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackManifest = require('webpack-manifest-plugin');
const ExtractTextPlugin =require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const publicPath = '/';
const NODE_ENV = process.env.NODE_ENV;
printConfig(settings, null);
module.exports = {
bail: true,
devtool: 'source-map',
entry: {
polyfills: require.resolve('../polyfills'),
app: paths.main,
vendor: [
"react",
"react-dom",
"react-redux",
"react-router",
"redux",
"redux-thunk",
"axios"
]
},
output: {
path: paths.build,
pathinfo: true,
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
publicPath: publicPath
},
resolve: {
extensions: ['.js', '']
},
resolveLoader: {
root: paths.nodeModules,
moduleTemplates: ['*-loader']
},
module: {
loaders: [
{
exclude: [
/\.html$/,
/\.js$/,
/\.css$/,
/\.json$/,
/\.svg$/
],
loader: 'url',
query: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]'
}
},
{
test: /\.js$/,
include: paths.app,
loader: 'babel'
},
{
test: /\.css$/,
include: paths.app,
loader: ExtractTextPlugin.extract('style', 'css?importLoaders=1!postcss')
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.svg$/,
loader: 'file',
query: {
name: 'static/media/[name].[hash:8].[ext]'
}
}
]
},
postcss: function() {
return [
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9'
]
})
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(NODE_ENV || settings.env)
},
__DEV__: (NODE_ENV && NODE_ENV === 'development') || settings.is.__DEV__,
__PROD__: (NODE_ENV && NODE_ENV === 'production') || settings.is.__PROD__
}),
new HtmlWebpackPlugin({
inject: true,
template: paths.templateHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
new ExtractTextPlugin('static/css/[name].[contenthash:8].css'),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false
},
mangle: {
screw_ie8: true
},
output: {
comments: false,
screw_ie8: true
}
}),
new CaseSensitivePathsPlugin(),
new webpack.optimize.CommonsChunkPlugin({
names: [ 'polyfills', 'vendor' ],
minChunks: Infinity
}),
new WebpackManifest({
fileName: 'asset-manifest.json'
})
],
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
|
// -- SDK File : KonySyncLib.js
// --Generated On Fri Feb 19 18:08:53 IST 2016*******************
// **************** Start jsonWriter.js*******************
//#ifdef iphone
//#define KONYSYNC_IOS
//#endif
//#ifdef bb
//#define KONYSYNC_BB
//#endif
//#ifdef bb10
//#define KONYSYNC_BB10
//#endif
//#ifdef winmobile
//#define KONYSYNC_WINDOWS
//#endif
//#ifdef winmobile6x
//#define KONYSYNC_WINDOWS
//#endif
//#ifdef winphone8
//#define KONYSYNC_WINDOWS
//#endif
//#ifdef android
//#define KONYSYNC_ANDROID
//#endif
//#ifdef j2me
//#define KONYSYNC_J2ME
//#endif
//#ifdef ipad
//#define KONYSYNC_IOS
//#endif
//#ifdef tabrcandroid
//#define KONYSYNC_ANDROID
//#endif
//#ifdef playbook
//#define KONYSYNC_WINDOWS
//#endif
//#ifdef spaipad
//#define KONYSYNC_IOS
//#endif
//#ifdef spatabandroid
//#define KONYSYNC_ANDROID
//#endif
//#ifdef spaplaybook
//#define KONYSYNC_WINDOWS
//#endif
//#ifdef windows8
//#define KONYSYNC_WINDOWS
//#endif
//#ifdef spatabwindows
//#define KONYSYNC_WINDOWS
//#endif
//#ifdef desktop_kiosk
//#define KONYSYNC_WINDOWS
//#endif
//#ifdef desktopweb
//#define KONYSYNC_WINDOWS
//#endif
//#ifdef iphone
//#define KONYSYNC_MOBILE
//#endif
//#ifdef bb
//#define KONYSYNC_MOBILE
//#endif
//#ifdef bb10
//#define KONYSYNC_MOBILE
//#endif
//#ifdef winmobile
//#define KONYSYNC_MOBILE
//#endif
//#ifdef winmobile6x
//#define KONYSYNC_MOBILE
//#endif
//#ifdef winphone8
//#define KONYSYNC_MOBILE
//#endif
//#ifdef android
//#define KONYSYNC_MOBILE
//#endif
//#ifdef j2me
//#define KONYSYNC_MOBILE
//#endif
//#ifdef symbian
//#define KONYSYNC_MOBILE
//#endif
//#ifdef ipad
//#define KONYSYNC_TAB
//#endif
//#ifdef tabrcandroid
//#define KONYSYNC_TAB
//#endif
//#ifdef playbook
//#define KONYSYNC_TAB
//#endif
//#ifdef spaipad
//#define KONYSYNC_TAB
//#endif
//#ifdef spatabandroid
//#define KONYSYNC_TAB
//#endif
//#ifdef spaplaybook
//#define KONYSYNC_TAB
//#endif
//#ifdef windows8
//#define KONYSYNC_TAB
//#endif
//#ifdef spatabwindows
//#define KONYSYNC_TAB
//#endif
//#ifdef desktop_kiosk
//#define KONYSYNC_DESKTOP
//#endif
//#ifdef desktopweb
//#define KONYSYNC_DESKTOP
//#endif
//#ifdef KONYSYNC_IOS
//#define KONYSYNC_ENCRYPTION_AVAILABLE
//#endif
//#ifdef KONYSYNC_ANDROID
//#define KONYSYNC_ENCRYPTION_AVAILABLE
//#endif
//#ifdef KONYSYNC_WINDOWS
//#define KONYSYNC_ENCRYPTION_AVAILABLE
//#endif
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
/*
kony.sync.jsonGetType = function(node) {
sync.log.trace("Entering kony.sync.jsonGetType ");
if (kony.type(node) === "table") {
for (var key in node) {
if ((key === 1)) {
return 1;
} else if (key === "1") {
return 1;
} else {
return 2;
}
}
return 1;
}
return 0;
};
kony.sync.createJson = function(key, data) {
sync.log.trace("Entering kony.sync.createJson ");
kony.sync.jsonBegin();
kony.sync.jsonWriteKeyValue(key, data);
kony.sync.jsonEnd();
return js;
};
kony.sync.jsonWriteKeyValue = function(key, data) {
sync.log.trace("Entering kony.sync.jsonWriteKeyValue ");
kony.sync.jsonBeginElement(key);
kony.sync.jsonWriteValue(data);
};
kony.sync.jsonWriteValue = function(data) {
sync.log.trace("Entering kony.sync.jsonWriteValue ");
datatype = kony.sync.jsonGetType(data);
var len = null;
if (datatype === 0) {
kony.sync.jsonString(data);
} else if (datatype === 1) {
kony.sync.jsonBeginArray();
len = kony.sync.jsonwriter_ipairs_length(data);
var count1 = 0;
if(!kony.sync.isNullOrUndefined(data)){
for (var i = 0; i < data.length; i++) {
var v = data[i];
count1 = count1 + 1;
kony.sync.jsonWriteValue(v);
if ((count1 !== len)) {
js = js + ",";
}
}
}
kony.sync.jsonEndArray();
} else {
kony.sync.jsonBeginHash();
len = kony.sync.jsonwriter_pairs_length(data);
var count2 = 0;
for (var key in data) {
var value = data[key];
count2 = count2 + 1;
kony.sync.jsonWriteKeyValue(key, value);
if ((count2 !== len)) {
js = js + ",";
}
}
kony.sync.jsonEndHash();
}
};
kony.sync.jsonBegin = function() {
sync.log.trace("Entering kony.sync.jsonBegin ");
js = "{";
};
kony.sync.jsonEnd = function() {
sync.log.trace("Entering kony.sync.jsonEnd ");
js = js + " }";
};
kony.sync.jsonBeginElement = function(elementName) {
sync.log.trace("Entering kony.sync.jsonBeginElement ");
js = js + "\"" + elementName + "\"" + " : ";
};
kony.sync.jsonBeginArray = function() {
sync.log.trace("Entering kony.sync.jsonBeginArray ");
js = js + " \[";
};
kony.sync.jsonEndArray = function() {
sync.log.trace("Entering kony.sync.jsonEndArray ");
js = js + " \]";
};
kony.sync.jsonBeginHash = function() {
sync.log.trace("Entering kony.sync.jsonBeginHash ");
js = js + " \{";
};
kony.sync.jsonEndHash = function() {
sync.log.trace("Entering kony.sync.jsonEndHash ");
js = js + " \}";
};
kony.sync.jsonAddValue = function(key, value) {
sync.log.trace("Entering kony.sync.jsonAddValue ");
js = js + " \"" + key + "\" : " + "\"" + value + "\"";
};
kony.sync.jsonString = function(value) {
sync.log.trace("Entering kony.sync.jsonString ");
if ((value === "null")) {
js = js + "null";
} else {
js = js + "\"" + value + "\"";
}
};
kony.sync.jsonwriter_pairs_length = function(tab) {
sync.log.trace("Entering kony.sync.jsonwriter_pairs_length ");
var count = 0;
if (!kony.sync.isNullOrUndefined(tab)) {
for (var key in tab) {
count = count + 1;
}
}
return count;
};
kony.sync.jsonwriter_ipairs_length = function(tab) {
sync.log.trace("Entering kony.sync.jsonwriter_ipairs_length ");
var count = 0;
if(!kony.sync.isNullOrUndefined(tab)){
for (var key = 0; key < tab.length; key++) {
count = count + 1;
}
}
return count;
};
*/
// **************** End jsonWriter.js*******************
// **************** Start KonySyncAPI.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync)=== "undefined"){
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined") {
kony.sync.blobManager = {};
}
// Device Auto Registration and Validation Starts here --
sync.startSession = function(config) {
if(kony.sync.validateSyncConfigParams("startSession", config) === false){
return;
}
if(kony.sync.preProcessSyncConfig("startSession", config, config[kony.sync.onSyncError]) === false){
return;
}
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncStart], kony.sync.currentSyncReturnParams);
var registerSuccess = true;
var alreadyRegistered = false;
var isError = false;
//assign the currentSyncBinaryStats to lastSyncBinaryStats.
kony.sync.reinitializeBinaryStats();
function single_transaction_callback(tx) {
sync.log.trace("Entering single_transaction_callback");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.syncConfigurationColumnDeviceIDName]);
kony.sync.qb_from(query, kony.sync.syncConfigurationTableName);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params,kony.sync.currentSyncConfigParams[kony.sync.onSyncError]);
if(resultSet === false){
registerSuccess = false;
isError = true;
return;
}
if(resultSet.rows.length === 0){
isError = true;
return;
}
var record = kony.db.sqlResultsetRowItem(tx, resultSet, 0);
sync.log.debug("Device Record: ", record);
sync.log.debug("Device ID: ", record.DeviceID);
if (record.DeviceID !== kony.sync.getDeviceID()) {
kony.sync.konyRegisterDevice(registerDeviceCallback);
sync.log.info("Registering Device...");
}
else {
alreadyRegistered = true;
sync.log.info("Device already registered");
}
}
function registerDeviceCallback(serverResponse) {
sync.log.trace("Entering registerDeviceCallback");
if (!kony.sync.isNullOrUndefined(serverResponse.opstatus) && serverResponse.opstatus !== 0) {
if (!kony.sync.isNullOrUndefined(serverResponse.d)) {
sync.log.error("Register Device Response : ", serverResponse);
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], kony.sync.getServerError(
serverResponse.d));
kony.sync.isSessionInProgress = false;
} else {
sync.log.error("Register Device Response : ", serverResponse);
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], kony.sync.getServerError(serverResponse) );
kony.sync.isSessionInProgress = false;
}
registerSuccess = false;
return;
}
else if(kony.sync.isNullOrUndefined(serverResponse.d)){
registerSuccess = false;
kony.sync.isSessionInProgress = false;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], kony.sync.getServerError(serverResponse) );
return;
}
if ((serverResponse.d.error === "true")) {
sync.log.error("Register Device Response : ", serverResponse);
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], kony.sync.getServerError(
serverResponse.d));
kony.sync.isSessionInProgress = false;
registerSuccess = false;
return;
}
sync.log.debug("Register Device Response : ", serverResponse);
var connection2 = kony.sync.getConnectionOnly(kony.sync.syncConfigurationDBName,kony.sync.syncConfigurationDBName, kony.sync.currentSyncConfigParams[kony.sync.onSyncError], "Load device id");
if(connection2 !== null){
kony.sync.startTransaction(connection2, single_device_register_callback, single_transaction_success_callback, single_transaction_error_callback, "Load device id");
}
function single_device_register_callback(tx) {
sync.log.trace("Entering single_device_register_callback");
kony.sync.instanceId = serverResponse.d.__registerdevice.instanceID;
var insertTab = {};
insertTab[kony.sync.syncConfigurationColumnInstanceIDName] = kony.sync.instanceId;
insertTab[kony.sync.syncConfigurationColumnDeviceIDName] = kony.sync.getDeviceID();
var wcs = {};
kony.table.insert(wcs, {key: kony.sync.syncConfigurationColumnDeviceIDName, value: ""});
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, kony.sync.syncConfigurationTableName);
kony.sync.qb_set(query, insertTab);
kony.sync.qb_where(query, wcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
return;
}
alreadyRegistered = true;
sync.log.info("Register Device success");
}
}
function single_transaction_error_callback(){
sync.log.trace("Entering single_transaction_error_callback");
sync.log.error("Register Device failed");
//kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], kony.sync.getSyncRegisterationFailed());
kony.sync.isSessionInProgress = false;
kony.sync.callTransactionError(isError, kony.sync.currentSyncConfigParams[kony.sync.onSyncError]);
}
function single_transaction_success_callback() {
sync.log.trace("Entering single_transaction_success_callback");
if(registerSuccess && alreadyRegistered && !isError) {
//Check if schema upgrade is pending
if(kony.sync.schemaUpgradeNeeded){
kony.sync.upgradeSchema(kony.sync.syncStartSession);
}
else{
kony.sync.isDownloadPendingForSchemaUpgrade(isDownloadPendingForSchemaUpgradeCallback);
}
}else if(isError){
sync.log.fatal("SynConfigTable is empty. There seems to be problem in sync.init");
kony.sync.getErrorTable(kony.sync.errorCodeMetatableError, kony.sync.getErrorMessage(kony.sync.errorCodeMetatableError), null);
}
}
function isDownloadPendingForSchemaUpgradeCallback(isError, errorObject, pending){
if(isError){
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], errorObject);
}else{
if(pending){
kony.sync.omitUpload = true; //only download
kony.sync.schemaUpgradeDownloadPending = true;
}
kony.sync.syncStartSession();
}
}
var connection = kony.sync.getConnectionOnly(kony.sync.syncConfigurationDBName,kony.sync.syncConfigurationDBName, kony.sync.currentSyncConfigParams[kony.sync.onSyncError], "Device Registration");
if(connection !==null){
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback, single_transaction_error_callback, "Device Registration");
}
};
kony.sync.syncStartSession = function(){
sync.log.trace("Entering kony.sync.syncStartSession ");
sync.log.info("Calling syncStartSession...");
kony.sync.isErrorInAnyScope = false;
kony.sync.syncErrorMessage = {};
kony.sync.validateScopeSession();
};
kony.sync.validateScopeSession = function(abortSync, syncErrorObject) {
sync.log.trace("Entering kony.sync.validateScopeSession ");
//If sync is aborted not because of scope issues
if(abortSync === true){
sync.log.trace("kony.sync.validateScopeSession->abortSync");
kony.sync.isSessionInProgress = false;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], syncErrorObject);
return;
}
kony.sync.resetscopesessionglobals(callback);
function callback(isSyncComplete){
var isError = false;
if (isSyncComplete === true) {
sync.log.trace("is Sync Complete true...");
if(typeof(binary) !== "undefined" && typeof(binary.util) !== "undefined") {
sync.log.trace("notifying the on demand binary thread. after sync start");
binary.util.notifyToPrepareJobs();
}
//var currentSyncConfig = JSON.stringify(kony.sync.currentSyncConfigParams);
//store the current sync config so that it can be used later.
//kony.store.setItem(kony.sync.currentSyncConfigKey, currentSyncConfig);
//sync.log.trace("resetScopeSessionGlobals callback - "+currentSyncConfig);
if(kony.sync.forceUpload === true){
kony.sync.forceUpload = false;
kony.sync.omitDownload = false;
kony.sync.validateScopeSession(true, kony.sync.schemaUpgradeErrorObject);
return;
}
if(kony.sync.forceUploadUpgrade === true){
kony.sync.forceUploadUpgrade = false;
kony.sync.omitDownload = false;
kony.sync.schemaUpgradeErrorObject();
return;
}
if(!kony.sync.isErrorInAnyScope){
if(!kony.sync.performOnlySchemaUpgrade){
//Continue upgrade after upload
/* if(kony.sync.schemaUpgradeNeeded){
kony.sync.upgradeSchema(kony.sync.syncStartSession);
return;
}*/
//start normal sync process after downloading changes for schema upgrade
if(kony.sync.schemaUpgradeDownloadPending){
kony.sync.schemaUpgradeDownloadPending = false;
kony.sync.omitUpload = false;
kony.sync.omitDownload = false;
kony.sync.resetsyncsessionglobals();
kony.sync.syncStartSession();
return;
}
}
kony.sync.omitUpload = false;
kony.sync.omitDownload = false;
kony.sync.isSessionInProgress = false;
kony.sync.performOnlySchemaUpgrade = false;
sync.log.trace("kony.sync.validateScopeSession->calling onSyncSuccess function");
kony.sync.schemaUpgradeDownloadPending = false;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncSuccess], kony.sync.currentSyncReturnParams);
}
else{
sync.log.error("kony.sync.validateScopeSession->calling onSyncError function");
kony.sync.isSessionInProgress = false;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError],kony.sync.getErrorTable(kony.sync.errorCodeSyncError,kony.sync.getErrorMessage(kony.sync.errorCodeSyncError),kony.sync.syncErrorMessage));
}
return;// Sync Completes here.
}
function validateTransaction(tx) {
sync.log.trace("Entering kony.sync.validateScopeSession->validateTransaction");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key: kony.sync.metaTableScopeColumn,
value: kony.sync.currentScope[kony.sync.scopeName]
}, {
key: kony.sync.metaTableFilterValue,
value: "no filter"
}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet === false){
isError = true;
return;
}
if (resultSet.rows.length !== 1) {
isError = true;
return;
}
if(kony.sync.schemaUpgradeDownloadPending){
//check if download is pending after schema upgrade for this scope
var rowItem = kony.db.sqlResultsetRowItem(tx, resultSet, 0);
if(rowItem[kony.sync.metaTableSchemaUpgradeSyncTimeColumn]==="0,0"){
kony.sync.omitDownload = false; //download for this scope
}else{
kony.sync.omitDownload = true; //this scope has already been downloaded
}
}
kony.sync.currentSyncReturnParams.currentScope = kony.sync.currentScope[kony.sync.scopeName];
}
function startScopeSession() {
if(isError === true){
errorScopeSession();
return;
}
sync.log.trace("Entering kony.sync.validateScopeSession->startScopeSession");
kony.sync.deleteMapKey(kony.sync.currentSyncReturnParams, kony.sync.serverDetails);
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onScopeStart], kony.sync.currentSyncReturnParams);
kony.sync.startUpload();
}
function errorScopeSession() {
sync.log.trace("Entering kony.sync.validateScopeSession->errorScopeSession");
var isbreak = kony.sync.callTransactionError(isError, kony.sync.currentSyncConfigParams[kony.sync.onScopeError]);
if (isbreak === true) {
kony.sync.callTransactionError(isError, kony.sync.currentSyncConfigParams[kony.sync.onSyncError]);
kony.sync.isSessionInProgress = false;
return;
}
kony.sync.validateScopeSession();
}
var connection = kony.sync.getConnectionOnly(kony.sync.currentScope[kony.sync.scopeDataSource], kony.sync.currentScope[kony.sync.scopeDataSource], errorScopeSession, "validate scope session");
if(connection !== null){
kony.sync.startTransaction(connection, validateTransaction, startScopeSession, errorScopeSession, "validate scope session");
}
}
};
kony.sync.startUpload = function() {
sync.log.trace("Entering kony.sync.startUpload ");
if(kony.sync.omitUpload){
kony.sync.uploadCompleted();
return;
}
if (kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks])) {
kony.sync.syncUploadChanges(kony.sync.currentScope[kony.sync.scopeName], kony.sync.currentScope[kony.sync.scopeDataSource], kony.sync.uploadCompleted);
} else {
var scopename = kony.sync.currentScope[kony.sync.scopeName];
if (kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][scopename] !== null && kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][scopename] !== undefined && kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][scopename][kony.sync.sessionTaskDoUpload]) {
kony.sync.syncUploadChanges(kony.sync.currentScope[kony.sync.scopeName], kony.sync.currentScope[kony.sync.scopeDataSource], kony.sync.uploadCompleted);
} else {
sync.log.info("Skipping Upload for Scope : ", kony.sync.currentScope[kony.sync.scopeName]);
kony.sync.uploadCompleted();
}
}
};
kony.sync.uploadCompleted = function(error, msg) {
sync.log.trace("Entering kony.sync.uploadCompleted ");
if(kony.sync.isSyncStopped){
sync.log.debug("sync stopped in uploadCompleted");
kony.sync.stopSyncSession();
return;
}
if(error===true){
sync.log.error("Error Occurred during upload : ",msg);
//if schema change error occurred - app is not latest one
if(msg.errorCode === kony.sync.servercodes.appVersionNotLatest){
kony.sync.onSchemaUpgradeErrorFromServer(msg);
return;
}
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onScopeError], msg);
kony.sync.isErrorInAnyScope = true;
kony.sync.syncErrorMessage[kony.sync.currentScope[kony.sync.scopeName]] = msg;
kony.sync.validateScopeSession();
}else{
if(kony.sync.omitDownload){ //In case download is force disabled
kony.sync.validateScopeSession();
return;
}
if(kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks]) || kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][kony.sync.currentScope[kony.sync.scopeName]])) {
kony.sync.syncDownloadChanges(kony.sync.currentScope[kony.sync.scopeName], kony.sync.currentScope[kony.sync.scopeDataSource], kony.sync.downloadCompletedCallback);
} else {
if (kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][kony.sync.currentScope[kony.sync.scopeName]][kony.sync.sessionTaskDoDownload]) {
kony.sync.syncDownloadChanges(kony.sync.currentScope[kony.sync.scopeName], kony.sync.currentScope[kony.sync.scopeDataSource], kony.sync.downloadCompletedCallback);
} else {
sync.log.info("Skipping Download for Scope : ", kony.sync.currentScope[kony.sync.scopeName]);
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onScopeSuccess], kony.sync.currentSyncReturnParams);
//In case of OTA scope and dodownload is false, the records for corresponding ack's will be deleted
/*if (kony.sync.currentScope[kony.sync.syncStrategy] === kony.sync.syncStrategy_OTA){
kony.sync.deleteRecordsAfterUpload(deleteRecordsAfterUploadCallback);
}*/
if (kony.sync.isUploadErrorPolicyCOE(kony.sync.currentScope)) {
if(kony.sync.currentScope[kony.sync.syncStrategy] !== kony.sync.syncStrategy_OTA ) {
deleteRecordsAfterUploadCallback(0);
} else {
kony.sync.updateSyncOrderForScope(deleteRecordsAfterUploadCallback);
}
}
else{
kony.sync.validateScopeSession();
}
}
}
}
function deleteRecordsAfterUploadCallback(code){
sync.log.trace("Entering deleteRecordsAfterUploadCallback");
if(code!==0){
kony.sync.isErrorInAnyScope = true;
var errObject = null;
//statement error
if(code===kony.sync.errorCodeSQLStatement){
errObject = kony.sync.errorObject;
}
//transaction error
else{
errObject = kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null);
}
kony.sync.syncErrorMessage[kony.sync.currentScope[kony.sync.scopeName]] = errObject;
sync.log.error("Error occurred in Deleting Records After Upload : ", errObject);
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onScopeError], errObject);
}
kony.sync.validateScopeSession();
}
};
kony.sync.downloadCompletedCallback = function(error, msg) {
sync.log.trace("Entering kony.sync.downloadCompletedCallback ");
if(kony.sync.isSyncStopped){
sync.log.debug("sync stopped in downloadCompletedCallback");
kony.sync.stopSyncSession();
return;
}
if(error){
sync.log.error("Error occurred during download : ", msg);
//if schema change error occurred - app is not latest one
if(msg.errorCode === kony.sync.servercodes.appVersionNotLatest){
kony.sync.onSchemaUpgradeErrorFromServer(msg);
return;
}
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onScopeError], msg);
kony.sync.isErrorInAnyScope = true;
kony.sync.syncErrorMessage[kony.sync.currentScope[kony.sync.scopeName]] = msg;
}
else{
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onScopeSuccess], kony.sync.currentSyncReturnParams);
}
kony.sync.validateScopeSession();
};
kony.sync.validateSyncConfigParams = function(opName, config){
if(kony.sync.isNullOrUndefined(config)){
kony.sync.alert("Argument type mismatch found for operation:sync." + opName + ". Expected 'config object' Actual 'null or undefined'");
return false;
}
if(typeof(config) !== "object"){
kony.sync.alert("Argument type mismatch found for operation:sync." + opName + ". Expected 'config object' Actual '" + typeof(config) + "'");
return false;
}
kony.sync.resetSessionVars();
};
kony.sync.preProcessSyncConfig = function(opName, config, errorcallback, sessionRequired){
if(!kony.sync.isSyncInitialized(errorcallback)){
return false;
}
if(!kony.sync.scopenameExist(config,errorcallback)){
return false;
}
kony.sync.syncConfigurationDBName = konysyncClientSyncConfig.AppID;
config.appVersion = kony.sync.configVersion;//konysyncClientSyncConfig.Version;
kony.sync.currentSyncConfigParams = config;
kony.sync.uploadClientContext = {};
kony.sync.downloadClientContext = {};
if(sessionRequired!==false){
if (kony.sync.isSessionInProgress) {
sync.log.warn("Sync Session already in progress...");
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(kony.sync.errorCodeSessionInProgress,kony.sync.getErrorMessage(kony.sync.errorCodeSessionInProgress),null));
return false;
}
kony.sync.isSessionInProgress = true;
}
sync.log.debug("Starting sync." + opName + " with Current Config Params : ", config);
kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey] = kony.sync.tonumber(kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey]);
kony.sync.currentSyncConfigParams[kony.sync.maxParallelChunksKey] = kony.sync.tonumber(kony.sync.currentSyncConfigParams[kony.sync.maxParallelChunksKey]);
kony.sync.resetsyncsessionglobals(opName);
};
kony.sync.scopenameExist = function(config,errorcallback){
sync.log.trace("Entering kony.sync.scopenameExist");
if(!kony.sync.isNullOrUndefined(config[kony.sync.sessionTasks])){
for(var key in config[kony.sync.sessionTasks]){
if(kony.sync.isNullOrUndefined(kony.sync.scopeDict[key])){
sync.log.error("Wrong scopename given in SessionTasks");
kony.sync.alert("Wrong scopename given in SessionTasks");
kony.sync.verifyAndCallClosure(errorcallback, {});
return false;
}
}
}
if(!kony.sync.isNullOrUndefined(config[kony.sync.removeAfterUpload])){
for(var key in config[kony.sync.removeAfterUpload]){
if(kony.sync.isNullOrUndefined(kony.sync.scopeDict[key])){
sync.log.error("Wrong scopename given in RemoveAfterUpload");
kony.sync.alert("Wrong scopename given in RemoveAfterUpload");
kony.sync.verifyAndCallClosure(errorcallback, {});
return false;
}
}
}
return true;
};
sync.stopSession = function(callback){
sync.log.trace("Entering sync.stop");
kony.sync.isSessionInProgress = false;
kony.sync.isSyncStopped = true;
kony.sync.onSyncStop = callback;
};
kony.sync.stopSyncSession = function(){
kony.sync.isSyncStopped = false;
kony.sync.globalIsDownloadStarted = true;
kony.sync.verifyAndCallClosure(kony.sync.onSyncStop);
};
// **************** End KonySyncAPI.js*******************
// **************** Start KonySyncBlobConstants.js*******************
/**
* Created by KH9093 on 21-09-2015.
*/
if (typeof(kony.sync) === "undefined") {
kony.sync = {};
}
if (typeof(sync) === "undefined") {
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined") {
kony.sync.blobManager = {};
}
kony.sync.BlobType = {
BASE64 : 1,
FILE: 2
};
kony.sync.currentSyncStats = {};
kony.sync.lastSyncStats = {};
//defining states for blob manager.
kony.sync.blobManager.INSERT_PROCESSING = 1;
kony.sync.blobManager.INSERT_FAILED = 2;
kony.sync.blobManager.UPDATE_PROCESSING = 11;
kony.sync.blobManager.UPDATE_FAILED = 12;
kony.sync.blobManager.DELETE_PROCESSING = 21;
kony.sync.blobManager.DELETE_FAILED = 22;
kony.sync.blobManager.FILE_DOESNOT_EXIST = 31;
kony.sync.blobManager.DOWNLOAD_ACCEPTED= 61;
kony.sync.blobManager.DOWNLOAD_FAILED = 63;
kony.sync.blobManager.DOWNLOAD_IN_PROGRESS = 64;
kony.sync.blobManager.UPLOAD_ACCEPTED = 71;
kony.sync.blobManager.UPLOAD_FAILED = 73;
kony.sync.blobManager.UPLOAD_IN_PROGRESS = 74;
kony.sync.blobManager.NO_OPERATION = 50;
kony.sync.blobManager.ONDEMAND_FETCH_LIMIT = 10;
kony.sync.blobManager.ONDEMAND_FETCH_OFFSET = 0;
//defining state messages..
kony.sync.blobManager.states = {};
kony.sync.blobManager.states[kony.sync.blobManager.INSERT_PROCESSING] = "Insert Operation in Process";
kony.sync.blobManager.states[kony.sync.blobManager.INSERT_FAILED] = "Insert Operation Failed";
kony.sync.blobManager.states[kony.sync.blobManager.UPDATE_PROCESSING] = "Update Operation in Process";
kony.sync.blobManager.states[kony.sync.blobManager.UPDATE_FAILED] = "Update Operation Failed";
kony.sync.blobManager.states[kony.sync.blobManager.DELETE_PROCESSING] = "Delete Operation in Process";
kony.sync.blobManager.states[kony.sync.blobManager.DELETE_FAILED] = "Delete Operation Failed";
kony.sync.blobManager.states[kony.sync.blobManager.FILE_DOESNOT_EXIST] = "Blob File doesn't exist.";
kony.sync.blobManager.states[kony.sync.blobManager.DOWNLOAD_ACCEPTED] = "Download request added to the queue";
kony.sync.blobManager.states[kony.sync.blobManager.DOWNLOAD_FAILED] = "Download Operation Failed";
kony.sync.blobManager.states[kony.sync.blobManager.DOWNLOAD_IN_PROGRESS] = "Download Operation in Process";
kony.sync.blobManager.states[kony.sync.blobManager.NO_OPERATION] = "Blob record available";
kony.sync.blobManager.states[kony.sync.blobManager.UPLOAD_ACCEPTED] = "Upload Request added to the queue";
kony.sync.blobManager.states[kony.sync.blobManager.UPLOAD_IN_PROGRESS] = "Upload Operation In progress";
kony.sync.blobManager.states[kony.sync.blobManager.UPLOAD_FAILED] = "Upload Operation Failed";
// **************** End KonySyncBlobConstants.js*******************
// **************** Start KonySyncBlobStoreManager.js*******************
// **************** Start BlobStoreManager.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined") {
kony.sync.blobManager = {};
}
/*columns of the BlobStoreManager table are ---
id, localPath, type, state, status, size, lastUpdatedTimeStamp
*/
kony.sync.blobManager.tableName = "tableName";
kony.sync.blobManager.columnName = "columnName";
kony.sync.blobManager.localPath = "localPath";
kony.sync.blobManager.id = "id";
kony.sync.blobManager.type = "type";
kony.sync.blobManager.state = "state";
kony.sync.blobManager.status = "status";
kony.sync.blobManager.size = "size";
kony.sync.blobManager.lastUpdatedTimeStamp = "lastUpdatedTimeStamp";
kony.sync.blobManager.retry = 'retry';
var dbname = kony.sync.syncConfigurationDBName;
var tbname = "konysyncBLOBSTOREMANAGER";
var resultset = null;
/**
* Method used to update the blob store manager record for given blobid.
* @param tx - transaction id
* @param blobid - id of the blob store manager row.
* @param valuesTable - values that are updated in the record.
* @param errorCallback - error callback in case of failures.
* @returns {*}
*/
kony.sync.blobManager.updateBlobManager = function(tx, blobid, valuesTable, errorCallback){
var query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, valuesTable);
kony.sync.qb_where(query, [
{
key : kony.sync.blobManager.id,
value : blobid
}
]);
kony.sync.qb_update(query, kony.sync.blobStoreManagerTable);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
resultset = kony.sync.executeSql(tx, sql, params, errorCallback);
return resultset;
};
/**
* This method is used to insert a base64 in the konysyncBLOBSTOREMANAGER table.
* @param base64 the base64 value which has to be inserted in the blob store
*/
kony.sync.blobManager.saveBlob = function(tx, tableName, columnName, base64, errorCallback) {
if(!kony.sync.isNullOrUndefined(base64) && base64.trim().length > 0) {
var query = kony.sync.qb_createQuery();
var error;
kony.sync.qb_set(query, {
localPath: "",
size: base64.length,
status: 100,
state: kony.sync.blobManager.INSERT_PROCESSING,
type: kony.sync.blobTypeBase64,
tableName : tableName,
columnName : columnName
});
kony.sync.qb_insert(query, kony.sync.blobStoreManagerTable);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
resultset = kony.sync.executeSql(tx, sql, params, errorCallback);
if (resultset === null || resultset === false)
return null;
var blobId = resultset.insertId;
var blobFileName = binary.util.saveBase64File("" + blobId, base64);
sync.log.trace("blob filepath returned is " + blobFileName);
//if file creation is successful.. insert the file path to the blobstoremanager.
var valuesTable = {};
if (blobFileName) {
valuesTable[kony.sync.blobManager.localPath] = blobFileName;
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.NO_OPERATION;
valuesTable[kony.sync.blobManager.status] = 100;
kony.sync.blobManager.updateBlobManager(tx, blobId, valuesTable, errorCallback);
} else {
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.INSERT_FAILED;
valuesTable[kony.sync.blobManager.status] = 0;
kony.sync.blobManager.updateBlobManager(tx, blobId, valuesTable, errorCallback);
error = kony.sync.getErrorTable(
kony.sync.errorCodeBlobFileNotCreated,
kony.sync.getErrorMessage(kony.sync.errorCodeBlobFileNotCreated)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
return;
}
return blobId;
} else {
error = kony.sync.getErrorTable(
kony.sync.errorCodeEmptyOrNullBase64,
kony.sync.getErrorMessage(kony.sync.errorCodeEmptyOrNullBase64)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
};
/**
* This method is used to delete records from the konysyncBLOBSTOREMANAGER table.
* @param id array which contains the list of valid ids whose records has to be deleted
* @return true if deletion is successful else false
*/
kony.sync.blobManager.deleteBlob = function(tx, blobid, errorCallback) {
kony.print("deleteBlobFromTable..");
if (blobid === undefined || typeof(blobid) !== "number") {
var error = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidColumnParams,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidColumnParams)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
} else {
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobid, errorCallback);
//state, status, localPath
//delete the record only if it is in valid state.
var state = null;
if(!kony.sync.isNullOrUndefined(blobMeta)) {
state = blobMeta[kony.sync.blobManager.state];
}
var possibleStates = [kony.sync.blobManager.INSERT_FAILED, kony.sync.blobManager.DELETE_FAILED, kony.sync.blobManager.FILE_DOESNOT_EXIST,
kony.sync.blobManager.NO_OPERATION,kony.sync.blobManager.UPDATE_FAILED ,kony.sync.blobManager.DOWNLOAD_FAILED, kony.sync.blobManager.DOWNLOAD_IN_PROGRESS,
kony.sync.blobManager.DOWNLOAD_ACCEPTED];
if(!kony.sync.isNullOrUndefined(state) && possibleStates.indexOf(state) !== -1) {
var valuesTable = {};
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DELETE_PROCESSING;
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable, errorCallback);
var deleteFile = binary.util.deleteBlobFile(blobMeta[kony.sync.blobManager.localPath]);
//TODO - add check to deletefile status..
var query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, kony.sync.blobStoreManagerTable);
var wcs = [{
key: kony.sync.blobManager.id,
value: blobid,
comptype: 'OR'
}];
kony.sync.qb_where(query, wcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
resultset = kony.db.executeSql(tx, sql, params, errorCallback);
if(resultset === null || resultset === false ){
valuesTable = {};
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DELETE_FAILED;
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable, errorCallback)
}
return resultset;
} else {
var error = kony.sync.getErrorTable(
kony.sync.errorCodeBlobInvalidStateForDelete,
kony.sync.getErrorMessage(kony.sync.errorCodeBlobInvalidStateForDelete, kony.sync.blobManager.states[state])
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
};
/**
* This method is used to update the binary data referred by id.
* @param id unique id of the base64 value.
* @param base64 is the binary value to be updated.
*/
kony.sync.blobManager.updateBlob = function(tx, blobid, base64, errorCallback) {
var error;
if (blobid === undefined || typeof(blobid) !== "number") {
error = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidColumnParams,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidColumnParams)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
} else {
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobid, errorCallback);
//state, status, localPath
var state = null;
if(!kony.sync.isNullOrUndefined(blobMeta)) {
state = blobMeta[kony.sync.blobManager.state];
}
var possibleStates = [kony.sync.blobManager.INSERT_FAILED, kony.sync.blobManager.FILE_DOESNOT_EXIST, kony.sync.blobManager.DELETE_FAILED,
kony.sync.blobManager.NO_OPERATION, kony.sync.blobManager.UPDATE_FAILED ,kony.sync.blobManager.DOWNLOAD_FAILED,
kony.sync.blobManager.DOWNLOAD_ACCEPTED, kony.sync.blobManager.DOWNLOAD_IN_PROGRESS];
if(!kony.sync.isNullOrUndefined(state) && possibleStates.indexOf(state) !== -1) {
var valuesTable = {};
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.UPDATE_PROCESSING;
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable, errorCallback);
var isBlobSaved = binary.util.saveBase64File("" + blobid, base64);
if (isBlobSaved !== null) {
valuesTable = {};
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.NO_OPERATION;
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable, errorCallback);
} else {
valuesTable = {};
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.UPDATE_FAILED;
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable, errorCallback);
}
return blobid;
} else {
error = kony.sync.getErrorTable(
kony.sync.errorCodeBlobInvalidStateForUpdate,
kony.sync.getErrorMessage(kony.sync.errorCodeBlobInvalidStateForUpdate, kony.sync.blobManager.states[state])
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
};
/**
* This is a utility method used to insert inline policy blobvalues to konysyncBLOBSTOREMANAGER
* and return corresponding blob ids
* @param tx transaction id
* @param tbname tablename
* @param values table columns
* @return object containing columns and their blob indices
*/
kony.sync.blobstore_insert = function(tx, tbname, values, errorCallback) {
if(kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname]) ||
kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns])){
//TODO - call error callback with apt error.
return;
}
var blobstoreindices = {};
var j;
var sql;
var binaryColumnsList = Object.keys(values);
var binaryColumnRefs = [];
for(j = 0; j < binaryColumnsList.length; j++) {
binaryColumnRefs[j] = kony.sync.binaryMetaColumnPrefix + binaryColumnsList[j]
}
for(j in binaryColumnsList) {
if(!kony.sync.isNullOrUndefined(values[binaryColumnsList[j]])) {
var blobIndex = kony.sync.blobManager.saveBlob(tx, tbname, binaryColumnsList[j] , values[binaryColumnsList[j]], errorCallback);
if(!kony.sync.isNullOrUndefined(blobIndex)) {
blobstoreindices[binaryColumnRefs[j]] = blobIndex;
}
}
}
return blobstoreindices;
};
/**
* This is a utility method used to update blobvalues to konysyncBLOBSTOREMANAGER and return
* corresponding blobids
* @param tx - transaction id
* @param tbname - tablename
* @param values - table columns
* @param wc - whereclause
* @param isBatch - indicates whether utility function is used for batch or not
* @return object containing columns and their blob indices
*/
kony.sync.blobstore_update = function(tx, tbname, values, wc, isBatch, errorCallback) {
var isUpdateSuccessful =true;
if(kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname]) ||
kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns])){
//TODO - call error callback with apt error.
return;
}
var blobstoreindices = {};
var query_compile;
var sql;
var binaryColumnsList = Object.keys(values);
var binaryColumnRefs = [];
for(var i = 0; i < binaryColumnsList.length; i++) {
binaryColumnRefs[i] = kony.sync.binaryMetaColumnPrefix + binaryColumnsList[i]
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, binaryColumnRefs);
kony.sync.qb_from(query, tbname);
if(isBatch === true) {
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0] + " " + wc;
}
else {
kony.sync.qb_where(query, wc);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
}
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params, errorCallback);
if(resultset !== false && resultset !== null) {
if(resultset.rows.length > 0) {
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
for (var j = 0; j < binaryColumnRefs.length; j++) {
var blobIndex;
if (!kony.sync.isNullOrUndefined(rowItem[binaryColumnRefs[j]])) {
if(rowItem[binaryColumnRefs[j]] !== "NULL")
blobIndex = kony.sync.blobManager.updateBlob(tx, rowItem[binaryColumnRefs[j]], values[binaryColumnsList[j]], errorCallback);
else {
blobIndex = kony.sync.blobManager.saveBlob(tx, tbname, binaryColumnsList[j], values[binaryColumnsList[j]], errorCallback);
}
}
if (!kony.sync.isNullOrUndefined(blobIndex)) {
blobstoreindices[binaryColumnRefs[j]] = blobIndex;
}
}
}
return blobstoreindices;
}
};
/**
* This is a utility method used to delete blob from konysyncBLOBSTOREMANAGER
* @param tx transaction id
* @param tbname tablename
* @param isBatch indicates whether utility function is used for batch or not
* @return
*/
kony.sync.blobstore_delete = function(tx, tbname, wc, isBatch, errorCallback) {
if(kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname]) ||
kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns])){
return true;
}
var binaryColumns = kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns];
var isDeleteSuccessful = true;
var query_compile = null;
var sql = null;
var binaryColumnRefs = [];
for(var i = 0; i < binaryColumns.length; i++) {
binaryColumnRefs[i] = kony.sync.binaryMetaColumnPrefix + binaryColumns[i];
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, binaryColumnRefs);
kony.sync.qb_from(query, tbname);
if(isBatch === true) {
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0] + " " + wc;
} else {
kony.sync.qb_where(query, wc);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
}
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params, errorCallback);
if(resultset !== false && resultset !== null) {
if (resultset.rows.length > 0) {
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
for (var i = 0; i < binaryColumnRefs.length; i++) {
var blobIndex;
if (!kony.sync.isNullOrUndefined(rowItem[binaryColumnRefs[i]])) {
blobIndex = rowItem[binaryColumnRefs[i]];
if(blobIndex !== "NULL") {
var results = kony.sync.blobManager.deleteBlob(tx, blobIndex, errorCallback);
if(results === false || results === null){
isDeleteSuccessful = false;
}
}
}
}
}
return isDeleteSuccessful;
}
};
/**
* Success callback called after successful completion of download.
* @param response - contains the response from download manager. (blobid, value file/base64).
*/
//expected fields in response.
//blobid,requestState,statusCode, errorResponse
//filePath
kony.sync.blobManager.onDemandUniversalSuccessCallback = function(response) {
sync.log.trace(" Entered into kony.sync.blobManager.onDemandUniversalSuccessCallback "+JSON.stringify(response));
var isDownload = true;
if(response.hasOwnProperty("blobid")) {
var successResponse = {};
var blobId = parseInt(response.blobid);
//give the response to the user.
function invokeCallbacks(updateResult, filePath) {
if(isDownload) {
if (updateResult) {
var blobType = kony.sync.blobManager.getRegisteredBlobType(blobId);
//increment total number of download jobs completed..
kony.sync.incrementCompletedJobs(true);
if (!kony.sync.isNullOrUndefined(blobType)) {
successResponse.pkTable = kony.sync.blobManager.getRegisteredPkTable(blobId);
if (blobType === kony.sync.BlobType.FILE) {
var decodedFilePath = binary.util.decodeBase64File(filePath);
successResponse.filePath = decodedFilePath;
}
else {
var base64String = binary.util.getBase64FromFiles([filePath]);
successResponse.base64 = base64String[0];
}
var successCallback = kony.sync.blobManager.getRegisteredSuccessCallback(blobId);
//clean up binarynotifier map..
if (!kony.sync.isNullOrUndefined(successCallback)) {
kony.sync.verifyAndCallClosure(successCallback, successResponse);
}
} else {
//log download completed..
sync.log.info("Download completed for blob id " + blobId);
}
} else {
var errorCallback = kony.sync.blobManager.getRegisteredErrorCallback(blobId);
//increment total number of download jobs failed..
kony.sync.incrementFailedJobs(true);
if (!kony.sync.isNullOrUndefined(errorCallback)) {
//update status failed after download.
var error = kony.sync.getErrorTable(
kony.sync.errorCodeBinaryDownloadFailed,
kony.sync.getErrorMessage(kony.sync.errorCodeBinaryDownloadFailed)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
} else {
//increment upload completed jobs..
kony.sync.incrementCompletedJobs(false);
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams) &&
kony.sync.isValidFunctionType(kony.sync.currentSyncConfigParams["uploadBinarySuccessCallback"])) {
var uploadSuccessCallback = kony.sync.currentSyncConfigParams["uploadBinarySuccessCallback"];
kony.sync.verifyAndCallClosure(uploadSuccessCallback, response);
}
else {
sync.log.info("Upload completed..");
}
}
//invoke the notifier..
kony.sync.invokeBinaryNotifiers(isDownload);
}
//check the type of request.
if(parseInt(response[kony.sync.requestState]) === kony.sync.blobManager.UPLOAD_IN_PROGRESS) {
isDownload = false;
}
kony.sync.blobManager.updateStatusAfterOndemandJob(response, true,isDownload , invokeCallbacks);
}
};
/**
* Failure callback after error in download.
* @param response - contains the error object and the corresponding blob id.
*/
kony.sync.blobManager.onDemandUniversalErrorCallback = function(response) {
sync.log.error("universal error callback " + JSON.stringify(response));
var isDownload = true;
if(response.hasOwnProperty("blobid")) {
function invokeCallbacks(updateResult, filePath) {
if(isDownload) {
//increment total number of download jobs failed..
kony.sync.incrementFailedJobs(true);
sync.log.trace("invoking error callback for the download request..");
var errorCallback = kony.sync.blobManager.getRegisteredErrorCallback(response.blobid);
if (!kony.sync.isNullOrUndefined(errorCallback)) {
//create an error object with appropriate details..
var errorMessage = kony.sync.getErrorMessage(kony.sync.errorCodeBinaryDownloadFailed) +
" status "+response.statusCode + " " + response.errorMessage;
var errorObject = kony.sync.getErrorTable(kony.sync.errorCodeBinaryDownloadFailed, errorMessage);
kony.sync.verifyAndCallClosure(errorCallback, errorObject);
}
} else {
//increment total number of download jobs failed..
kony.sync.incrementFailedJobs(false);
sync.log.trace("invoking error callback for the upload request..");
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams) &&
kony.sync.isValidFunctionType(kony.sync.currentSyncConfigParams["uploadBinaryErrorCallback"])) {
var uploadErrorCallback = kony.sync.currentSyncConfigParams["uploadBinaryErrorCallback"];
//create an error object with appropriate details..
var errorMessage = kony.sync.getErrorMessage(kony.sync.errorCodeBinaryUploadFailed) +
" status "+response.statusCode + " " + response.errorMessage;
var errorObject = kony.sync.getErrorTable(kony.sync.errorCodeBinaryUploadFailed, errorMessage);
kony.sync.verifyAndCallClosure(uploadErrorCallback, errorObject);
} else {
//upload failed.
sync.log.error("sync binary upload failed for blob id "+response.blobid);
}
}
//invoke the notifier..
kony.sync.invokeBinaryNotifiers(isDownload);
}
//using the request state find out if the request is for upload/ download.
if(parseInt(response[kony.sync.requestState]) === kony.sync.blobManager.UPLOAD_IN_PROGRESS) {
isDownload = false;
}
kony.sync.blobManager.updateStatusAfterOndemandJob(response, false, isDownload ,invokeCallbacks);
}
};
/** Method used to register success and error callbacks for given blob download.
* @param blobid - blobid which is under download
* @param pks - primary key values which uniquely identify the blob in parent table
* @param successCallback - success callback to be called after successful download
* @param errorCallback - error callback to be called in case of failure.
*/
kony.sync.blobManager.registerCallbacks = function(blobid, pks, blobType, successCallback, errorCallback){
kony.sync.blobManager.binaryNotifierMap[blobid] = [pks, blobType, successCallback, errorCallback];
};
/**
* Method returns the registered Success callback for the given blobid download request.
* @param blobid - blobid which is under download.
* @returns {*}
*/
kony.sync.blobManager.getRegisteredSuccessCallback = function(blobid) {
if(kony.sync.blobManager.binaryNotifierMap.hasOwnProperty(blobid)) {
return kony.sync.blobManager.binaryNotifierMap[blobid][2];
} else {
return null;
}
};
/**
* Method returns the registered error callback for the given blobid download request.
* @param blobid - blobid which is under download.
* @returns {*}
*/
kony.sync.blobManager.getRegisteredErrorCallback = function(blobid) {
if(kony.sync.blobManager.binaryNotifierMap.hasOwnProperty(blobid)) {
return kony.sync.blobManager.binaryNotifierMap[blobid][3];
} else {
return null;
}
};
/**
* Method returns the registered pk values for the given blobid download request.
* @param blobid - blobid which is under download.
* @returns {*}
*/
kony.sync.blobManager.getRegisteredPkTable = function(blobid) {
if(kony.sync.blobManager.binaryNotifierMap.hasOwnProperty(blobid)) {
return kony.sync.blobManager.binaryNotifierMap[blobid][0];
} else {
return null;
}
};
kony.sync.blobManager.getRegisteredBlobType = function(blobid) {
if(kony.sync.blobManager.binaryNotifierMap.hasOwnProperty(blobid)) {
return kony.sync.blobManager.binaryNotifierMap[blobid][1];
} else {
return null;
}
};
/**
* Method used to update status of the blob record to completed after completion of donwload.
* @param blobid - id for which the status has to be updated.
* @param success - result of operation (true/ false).
* @param isDownload - operation type. true for download / false for upload.
*/
kony.sync.blobManager.updateStatusAfterOndemandJob = function(response, success, isDownload, updateResultCallback) {
var finalFilePath = "";
var valuesTable = {};
function single_transaction_callback(tx) {
var blobid = parseInt(response[kony.sync.blobId]);
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobid, function(err){
sync.log.trace("error in fetching blobMeta --> updateStatusAfterOndemandJob" );
});
if(isDownload) {
if (blobMeta[kony.sync.blobManager.state] === parseInt(response[kony.sync.requestState])) {
//delete the previousFile and rename the temp file.
if (success) {
sync.log.trace(" kony.sync.blobManager.updateStatusAfterOndemandJob: single_transaction_callback ", blobid);
var previousFileName = blobMeta[kony.sync.blobManager.localPath];
var filePath = response["filePath"];
var fileSuccess;
if (previousFileName === "") {
filePath = filePath.substring(0, filePath.indexOf("_temp"));
fileSuccess = binary.util.renameFile(response["filePath"], filePath);
finalFilePath = filePath;
} else {
fileSuccess = binary.util.renameFile(response["filePath"], previousFileName);
finalFilePath = previousFileName;
}
if (fileSuccess) {
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.NO_OPERATION;
valuesTable[kony.sync.blobManager.status] = 100;
valuesTable[kony.sync.blobManager.localPath] = finalFilePath;
} else {
//failed writing file to the memory. error?
/*var noOfRetries = blobMeta[kony.sync.blobManager.retry] - 1;
if(noOfRetries < 0) {
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DOWNLOAD_FAILED;
valuesTable[kony.sync.blobManager.status] = 0;
} else {
valuesTable[kony.sync.blobManager.retry] = noOfRetries;
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DOWNLOAD_ACCEPTED;
valuesTable[kony.sync.blobManager.status] = 0;
}*/
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DOWNLOAD_FAILED;
valuesTable[kony.sync.blobManager.status] = 0;
success = false;
}
} else {
if (response.hasOwnProperty("errorResponse") && !response["errorResponse"]
&& response["errorResponse"].trim() !== "") {
//check if for the errorResponse, we have to retry or not.
if (kony.sync.blobManager.isRetryError(response["statusCode"], response["errorResponse"])) {
var noOfRetries = blobMeta[kony.sync.blobManager.retry] - 1;
if(noOfRetries < 0) {
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DOWNLOAD_FAILED;
valuesTable[kony.sync.blobManager.status] = 0;
} else {
valuesTable[kony.sync.blobManager.retry] = noOfRetries;
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DOWNLOAD_ACCEPTED;
valuesTable[kony.sync.blobManager.status] = 0;
}
//valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DOWNLOAD_FAILED;
//valuesTable[kony.sync.blobManager.status] = 0;
}
else {
sync.log.trace("Not a retry error, so updating status as download failed for blobid:"+blobid);
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DOWNLOAD_FAILED;
valuesTable[kony.sync.blobManager.status] = 0;
}
} else {
//download failed. no error Response received.
sync.log.error("Download failed. Response from server is "+JSON.stringify(response));
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.DOWNLOAD_FAILED;
valuesTable[kony.sync.blobManager.status] = 0;
}
}
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable);
} else {
//user invoked operation after download request. No need to update anything.
success = false;
sync.log.trace("some other operation got invoked after download call. So, ignoring downloaded file");
if (response.hasOwnProperty["filePath"]) {
binary.util.deleteBlobFile(response["filePath"]);
}
}
} else {
//upload response parsing.
if(blobMeta[kony.sync.blobManager.state] === parseInt(response[kony.sync.requestState])) {
valuesTable = {};
if(success) {
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.NO_OPERATION;
} else {
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.UPLOAD_FAILED;
}
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable);
} else {
//user invoked another operation after upload request.
sync.log.trace("some other operation got invoked after upload call");
success = false;
}
}
}
function single_transaction_success_callback() {
sync.log.trace("updateStatusAfterOndemandJob -> transaction success");
updateResultCallback(success, finalFilePath);
}
function single_transaction_error_callback() {
sync.log.trace("updateStatusAfterOndemandJob -> transaction failure");
success = false;
updateResultCallback(success, finalFilePath);
}
var connection = kony.sync.getConnectionOnly(kony.sync.syncConfigurationDBName, kony.sync.syncConfigurationDBName);
if(connection !== null) {
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback,
single_transaction_error_callback);
}
};
/**
* Method is used to parse the statusCode and errorResponse that the sdk receives upon DownloadBinary
* and concludes if the download should be retried or not.
* @param statusCode - statusCode from http response
* @param errorResponse - errorResponse fetched from server
* @returns {boolean} - whether the error leads to retry or not.
*/
kony.sync.blobManager.isRetryError = function(statusCode, errorResponse) {
var isRetryError = false;
sync.log.trace("isRetryError:statusCode: " + statusCode + " errorResponse:", errorResponse);
statusCode = parseInt(statusCode);
try {
errorResponse = JSON.parse(errorResponse);
} catch(err){
sync.log.error("kony.sync.blobManager.isRetryError parsing error response "+errorResponse);
return isRetryError;
}
//depending on the status code and error response, find out if the download should be retried!
switch (statusCode) {
case 404:
isRetryError = false;
break;
case 401:
if (errorResponse.hasOwnProperty("mfcode")) {
if (errorResponse["mfcode"] === "Auth-9") {
sync.log.trace("Got Auth-9 response");
isRetryError = true;
} else if(errorResponse["mfcode"] === "Gateway-5") {
sync.log.trace("Got Gateway-5 response");
isRetryError = true;
}
} else {
isRetryError = false;
}
break;
case 200:
if(errorResponse.hasOwnProperty("d") && errorResponse["d"].hasOwnProperty("mfcode")) {
if(errorResponse["d"]["mfcode"] === "Gateway-5") {
isRetryError = true;
}
}
break;
default:
isRetryError = false;
}
return isRetryError;
};
kony.sync.blobManager.updateParentWithBlobReference = function(tx, tableName, values, wcs, errorCallback) {
sync.log.trace("kony.sync.blobManager.updateParentWithBlobReference - entered with table "+tableName+" and values ",values);
sync.log.trace("kony.sync.blobManager.updateParentWithBlobReference - updating parent table with blobref.");
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tableName);
kony.sync.qb_set(query, values);
kony.sync.qb_where(query, wcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params, errorCallback);
if(resultset === false) {
sync.log.error("Error in updating the parent table with blobId ");
}
//update the history table as well..
sync.log.trace("kony.sync.blobManager.updateParentWithBlobReference - updating history table with blobref.");
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tableName+kony.sync.historyTableName);
kony.sync.qb_set(query, values);
kony.sync.qb_where(query, wcs);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
resultset = kony.sync.executeSql(tx, sql, params, errorCallback);
if(resultset === false) {
sync.log.error("Error in updating the history table with blobId ");
}
return resultset;
};
kony.sync.blobManager.createBlobRecord = function(tx, tableName, columnName, errorCallback) {
var query = kony.sync.qb_createQuery();
var state = kony.sync.blobManager.DOWNLOAD_ACCEPTED;
kony.sync.qb_set(query, {
localPath: "",
status: 0,
state: state,
type: kony.sync.blobTypeBase64,
tableName : tableName,
columnName : columnName,
retry: kony.sync.maxRetries
});
kony.sync.qb_insert(query, kony.sync.blobStoreManagerTable);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
resultset = kony.sync.executeSql(tx, sql, params, errorCallback);
if (resultset === null || resultset === false) {
sync.log.error("error in creating a entry in blobstore manager");
return;
}
var blobId = resultset.insertId;
return blobId;
};
/**
* Method invokes download operation on the given record.
* @param tx - transaction id
* @param tableName - parent table name for the blob reocrd
* @param columnName - column name of the binary field.
* @param blobType - download response type . (FILE /BASE64).
* @param pks - pk table which uniquely identifies the record
* @param successCallback - success callback for download request.
* @param errorCallback - error callback for download request.
* @returns {null}
*/
kony.sync.blobManager.triggerDownload = function(tx, tableName, columnName, pks, errorCallback) {
sync.log.trace("kony.sync.blobManager.triggerDownload - Entered function with tablename and columnname "+tableName+"--"+columnName);
var blobId = kony.sync.blobManager.createBlobRecord(tx, tableName, columnName, errorCallback);
if(!blobId) {
return;
}
sync.log.trace("successfully created an entry in blobstore manager");
var setClause = {};
var blobMetaFieldKey = kony.sync.binaryMetaColumnPrefix+columnName;
setClause[blobMetaFieldKey] = blobId;
var wcs = [];
for (var key in pks) {
var wc = {};
wc.key = key;
wc.value = pks[key];
wcs.push(wc);
}
resultset = kony.sync.blobManager.updateParentWithBlobReference(tx, tableName, setClause, wcs, errorCallback);
if(resultset === false || resultset === null) {
return;
}
sync.log.trace("updated parent table with the blod id.");
binary.util.notifyToPrepareJobs();
return blobId;
};
/**
* Method retriggers the download (incase of force-download / failed download.)
* @param tx - transaction id
* @param blobid - id which uniquely identifies the blob
* @param blobType - download response type (FILE/ base64).
* @param pks - pk table which uniquely identifies the record.
* @param successCallback - success callback for download request.
* @param errorCallback - error callback for download request.
*/
kony.sync.blobManager.retryDownload = function(tx, blobid, blobType, pks, successCallback, errorCallback) {
//reset the state and status to 0% and DOWNLOAD_ACCEPTED
var state = kony.sync.blobManager.DOWNLOAD_ACCEPTED;
var valuesTable = {};
valuesTable[kony.sync.blobManager.state] = state;
valuesTable[kony.sync.blobManager.status] = 0;
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable, errorCallback);
//increment total number of download jobs..
kony.sync.incrementTotalJobs(true);
kony.sync.blobManager.registerCallbacks(blobid, pks, blobType, successCallback, errorCallback);
binary.util.notifyToPrepareJobs();
};
kony.sync.blobManager.getBlobInline = function(tx, blobid, blobType, tableName, columnName, config, pks,
successCallback, errorCallback) {
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobid, errorCallback);
if(!kony.sync.isNullOrUndefined(blobMeta) && blobMeta !== false) {
var possibleStates = [kony.sync.blobManager.NO_OPERATION, kony.sync.blobManager.UPLOAD_ACCEPTED,
kony.sync.blobManager.UPLOAD_IN_PROGRESS, kony.sync.blobManager.UPLOAD_FAILED];
var state = blobMeta[kony.sync.blobManager.state];
if(blobMeta[kony.sync.blobManager.status] === 100 &&
possibleStates.indexOf(state) !== -1) {
//base64 exists. return back the required details.
var successResponse = {};
successResponse.pkTable = pks;
if (blobType === kony.sync.BlobType.FILE) {
//return blobMeta[kony.sync.blobManager.localPath];
var decodedFilePath = binary.util.decodeBase64File(blobMeta[kony.sync.blobManager.localPath]);
successResponse.filePath = decodedFilePath;
successCallback(successResponse);
} else {
var base64String = binary.util.getBase64FromFiles([blobMeta[kony.sync.blobManager.localPath]]);
if (base64String[0].length > 0) {
successResponse.base64 = base64String[0];
successCallback(successResponse);
} else {
//update the state of the file stating the file doesn't exist.
var valuesTable = {};
valuesTable.state = kony.sync.blobManager.FILE_DOESNOT_EXIST;
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable, errorCallback);
//throw an error saying file doesn't exist.
var error = kony.sync.getErrorTable(
kony.sync.errorCodeBlobFileDoesnotExist,
kony.sync.getErrorMessage(kony.sync.errorCodeBlobFileDoesnotExist)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
} else {
var error = kony.sync.getErrorTable(
kony.sync.errorCodeBlobInvalidState,
kony.sync.getErrorMessage(kony.sync.errorCodeBlobInvalidState)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
};
/**
* Method called when download request is invoked.
* @param tx - transaction id
* @param blobid - id of the blob store manager record.
* @param blobType - response type (FILE / BASE64).
* @param tableName - name of the parent table.
* @param columnName - binary column to which the record refers to.
* @param config - configuration parameters for download ( forceDownload).
* @param pks - pk table that uniquely identies the record in parent table.
* @param successCallback - success callback for fetch
* @param errorCallback - error callback for fetch,
* @returns {*}
*/
kony.sync.blobManager.getBlobOnDemand = function(tx, blobid, blobType, tableName, columnName, config, pks,
successCallback, errorCallback) {
//no blob id. trigger download
if(blobid === kony.sync.blobRefNotDefined) {
sync.log.trace("triggering download --> getBlobOnDemand");
var generatedBlobId = kony.sync.blobManager.triggerDownload(tx, tableName, columnName, pks, errorCallback);
if(generatedBlobId) {
kony.sync.blobManager.registerCallbacks(generatedBlobId, pks, blobType, successCallback, errorCallback);
}
//increment total number of download jobs..
kony.sync.incrementTotalJobs(true);
} else {
//check if the file is available.
sync.log.trace("fetching from blobStoreManager --> getBlobOnDemand");
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobid, errorCallback);
if(!kony.sync.isNullOrUndefined(blobMeta) && blobMeta !== false) {
//possible states of the file to read the base64.
var possibleStates = [kony.sync.blobManager.NO_OPERATION, kony.sync.blobManager.UPLOAD_ACCEPTED,
kony.sync.blobManager.UPLOAD_IN_PROGRESS, kony.sync.blobManager.UPLOAD_FAILED];
var state = blobMeta[kony.sync.blobManager.state];
var forceDownload = false;
sync.log.trace("blob meta from blobStoreManager.." + JSON.stringify(blobMeta));
if(!kony.sync.isNullOrUndefined(config) && config.hasOwnProperty(kony.sync.forceDownload)) {
forceDownload = config.forceDownload;
}
sync.log.trace("forceDownload "+forceDownload+ " -> getBlobOnDemand");
//if state is No_operation and status is 100, file exists. read it and return.
if(blobMeta[kony.sync.blobManager.status] === kony.sync.maxFilePercent &&
possibleStates.indexOf(state) !== -1) {
//base64 exists. return back the required details.
if(!forceDownload) {
var successResponse = {};
successResponse.pkTable = pks;
//if requested response type is FILE, return the filePath.
if (blobType === kony.sync.BlobType.FILE) {
var decodedFilePath = binary.util.decodeBase64File(blobMeta[kony.sync.blobManager.localPath]);
successResponse.filePath = decodedFilePath;
sync.log.trace("response to the user with filepath "+JSON.stringify(successResponse));
successCallback(successResponse);
} else {
//else read the base64 string from the file.
var base64String = binary.util.getBase64FromFiles([blobMeta[kony.sync.blobManager.localPath]])
if (base64String[0].length > 0) {
successResponse.base64 = base64String[0];
sync.log.trace("response to the user with base64 string "+JSON.stringify(successResponse));
successCallback(successResponse);
} else {
var valuesTable = {};
valuesTable.state = kony.sync.blobManager.FILE_DOESNOT_EXIST;
kony.sync.blobManager.updateBlobManager(tx, blobid, valuesTable, errorCallback);
sync.log.error("requested file does not exist -> getBlobOnDemand");
//throw an error saying file doesn't exist.
var error = kony.sync.getErrorTable(
kony.sync.errorCodeBlobFileDoesnotExistOnDemand,
kony.sync.getErrorMessage(kony.sync.errorCodeBlobFileDoesnotExistOnDemand)
);
errorCallback(error);
}
}
} else {
//retrigger download..
sync.log.trace("forceDownload is true. ReTriggering download -> getBlobOnDemand");
kony.sync.blobManager.retryDownload(tx, blobid, blobType, pks, successCallback, errorCallback);
}
}
//if already download requested on that record, throw an error..
else if(blobMeta[kony.sync.blobManager.state] === kony.sync.blobManager.DOWNLOAD_ACCEPTED ||
blobMeta[kony.sync.blobManager.state] === kony.sync.blobManager.DOWNLOAD_IN_PROGRESS) {
//throw an error download already requested...
sync.log.error("Download request is already in queue -> getBlobOnDemand");
var error = kony.sync.getErrorTable(
kony.sync.errorCodeDownloadAlreadyInQueue,
kony.sync.getErrorMessage(kony.sync.errorCodeDownloadAlreadyInQueue)
);
errorCallback(error);
}
//if already ony operation is in progress on the blob entry, download is not allowed.
else if (blobMeta[kony.sync.blobManager.state] === kony.sync.blobManager.UPDATE_PROCESSING ||
blobMeta[kony.sync.blobManager.state] === kony.sync.blobManager.DELETE_PROCESSING) {
sync.log.error("User performing operation..-> getBlobOnDemand");
var error = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidStateForDownload,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidStateForDownload,
kony.sync.blobManager.states[blobMeta[kony.sync.blobManager.state]])
);
errorCallback(error);
}
else {
//retriger download
//blob entry exists but not the file.
sync.log.trace("retriggering download -> getBlobOnDemand");
kony.sync.blobManager.retryDownload(tx, blobid, blobType, pks, successCallback, errorCallback);
}
}
}
};
/**
* Method used to read meta info about the record in blobstore manager.
* @param tx - transaction id.
* @param blobid - id of the record in blob store manager.
* @param errorCallback - error callback for unsuccesful transactions.
* @returns {{}} JSON object with state and status information.
*/
kony.sync.blobManager.getBlobMetaDetails = function(tx, blobid, errorCallback) {
var wcs = [{
key : "id",
value : blobid
}];
var requiredColumns = [kony.sync.blobManager.state, kony.sync.blobManager.status,
kony.sync.blobManager.localPath, kony.sync.blobManager.retry];
var response = {};
resultset = kony.sync.queryTable(tx, kony.sync.blobStoreManagerTable, requiredColumns, wcs);
if(resultset !== null && resultset !== false) {
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
response.state = rowItem[kony.sync.blobManager.state];
response.status = rowItem[kony.sync.blobManager.status];
response.localPath = rowItem[kony.sync.blobManager.localPath];
response.retry = rowItem[kony.sync.blobManager.retry];
}
return response;
};
/**
* This method is used to get the fetch the rows from blob tables and populate the ondemand download request
* @return
*/
kony.sync.blobManager.prepareJobs = function(){
//incase current sync config params are undefined, retrieve them from local storage.
var errorcallback = function(err) {
sync.log.error("Error occured in prepareJobs "+ JSON.stringify(err));
};
var successcallback = kony.sync.blobManager.onDemandManager.setJobs;
var payloadList = [];
var isError = false;
var errorInfo = {};
sync.log.trace("Entering kony.sync.blobManager.prepareJobs ");
function single_transaction_success_callback() {
sync.log.trace("Entering kony.sync.blobManager.prepareJobs->single_select_transaction_success");
if(isError) {
sync.log.error("Error occured in single_transaction_success_callback " + JSON.stringify(errorInfo))
kony.sync.verifyAndCallClosure(errorcallback, errorInfo);
return;
}
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams) &&
!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.authTokenKey])) {
if (!kony.sync.isMbaasEnabled) {
kony.sync.isMbaasEnabled = true;
}
sync.log.trace("Refreshing claims token");
kony.sdk.claimsRefresh(claimsRefreshSuccessCallBack, claimsRefreshFailureCallBack);
} else {
sync.log.trace("Calling successcallback with payload list "+ JSON.stringify(payloadList));
kony.sync.verifyAndCallClosure(successcallback, payloadList);
}
}
function claimsRefreshSuccessCallBack() {
sync.log.trace("Entering kony.sync.blobManager.prepareJobs->claimsRefreshSuccessCallBack ");
var currentClaimToken = kony.sdk.getCurrentInstance().currentClaimToken;
if (kony.sync.currentSyncConfigParams[kony.sync.authTokenKey] != currentClaimToken) {
kony.sync.currentSyncConfigParams[kony.sync.authTokenKey] = currentClaimToken;
}
var payloadListSize = payloadList.length;
var payload = null;
for(var i=0; i<payloadListSize; i++) {
payload = payloadList[i];
if(!kony.sync.isNullOrUndefined(payload) && !kony.sync.isNullOrUndefined(payload.httpheaders)) {
payload.httpheaders["X-Kony-Authorization"] = currentClaimToken;
}
}
sync.log.trace("Calling successcallback with payloadlist "+ JSON.stringify(payloadList));
kony.sync.verifyAndCallClosure(successcallback, payloadList);
}
function claimsRefreshFailureCallBack(res) {
sync.log.error("kony.sync.blobManager.prepareJobs->claimsRefreshFailureCallBack " + JSON.stringify(res));
kony.sync.verifyAndCallClosure(errorcallback, res);
}
function single_transaction_error_callback() {
sync.log.error("Entering kony.sync.blobManager.prepareJobs->single_select_transaction_failed");
kony.sync.verifyAndCallClosure(errorcallback);
}
function populateOnDemandPayload(tx, rowItemsList, isDownload) {
try {
sync.log.trace("Entering kony.sync.blobManager.prepareJobs->populateOnDemandPayload isDOwnload "+isDownload);
sync.log.trace("populate on demand payload -> rowItemsList "+JSON.stringify(rowItemsList));
var rowItemsListLength = rowItemsList.length;
var binaryMetaColumnName = null;
var binaryColumnName = null;
var binaryTableName = null;
var rowItem = null;
var query = null;
var query_compile = null;
var sql = null;
var params = null;
var resultSet = null;
var whereClause = [];
var queryOpenBrace = true;
var blobId = null;
//Iterating over the on demand download/upload rows
for(var j=0; j < rowItemsListLength; j++) {
rowItem = rowItemsList[j];
blobId = rowItem[kony.sync.blobManager.id];
binaryColumnName = rowItem[kony.sync.blobManager.columnName];
binaryTableName = rowItem[kony.sync.blobManager.tableName];
var scope = kony.sync.scopes[kony.sync.scopes.syncTableScopeDic[binaryTableName]];
var columns = kony.sync.createClone(scope.syncTableDic[binaryTableName].Pk_Columns);
columns.push(binaryColumnName);
if(!isDownload) {
columns.push(kony.sync.mainTableChangeTypeColumn);
}
var blobWhereClause = [];
binaryMetaColumnName = kony.sync.binaryMetaColumnPrefix + binaryColumnName;
kony.table.insert(blobWhereClause, {key:binaryMetaColumnName,value:blobId,optype: "EQ"});
resultSet = kony.sync.queryTable(tx, binaryTableName, columns, blobWhereClause);
if(resultSet === false) {
sync.log.error("Error executing query", sql, " params ", JSON.stringify(params));
isError = true;
return;
}
if(resultSet !== null && resultSet.rows.length > 0) {
var data = null;
for(var k=0; k<resultSet.rows.length; k++) {
data = kony.db.sqlResultsetRowItem(tx, resultSet, k);
//check if there is context in the binarycolumn. \
if(isDownload) {
if(data[binaryColumnName] === kony.sync.blobRefNotDefined){
sync.log.error("NULL found in binary data column. ");
isError = true;
return;
}
}
var payload = populateOnDemandParams(tx, blobId, binaryColumnName, binaryTableName, data, isDownload);
payloadList.push(payload);
}
}
var mp = {};
mp[kony.sync.queryKey] = kony.sync.blobManager.id;
mp[kony.sync.queryValue] = rowItem[kony.sync.blobManager.id];
mp[kony.sync.optype] = "EQ";
mp[kony.sync.comptype] = "OR";
if(j===0) {
mp[kony.sync.openbrace] = true;
}
if(j=== (rowItemsListLength-1) ) {
mp[kony.sync.closebrace] = true;
}
whereClause.push(mp);
}
//Update blobstoremanager table with DOWNLOAD_INPROGRESS/UPLOAD_INPROGRESS FOR corresponding ids
//if there are any jobs.
if(whereClause.length > 0) {
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, kony.sync.blobStoreManagerTable);
var setClause = {};
//TODO - add a check before updating the state.
if(isDownload) {
setClause[kony.sync.blobManager.state] = kony.sync.blobManager.DOWNLOAD_IN_PROGRESS;
} else {
setClause[kony.sync.blobManager.state] = kony.sync.blobManager.UPLOAD_IN_PROGRESS;
}
kony.sync.qb_set(query, setClause);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
sync.log.trace("Executing query for updating states ", sql, " params ", JSON.stringify(params));
resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet === false) {
isError = true;
return;
}
}
}
catch(err) {
isError = true;
//to avoid the thread to wait in case of exception.
kony.sync.blobManager.onDemandManager.setJobs(null);
sync.log.trace("catch block for the error-> populateOnDemandPayload "+JSON.stringify(err));
errorInfo = err;
}
}
function populateOnDemandParams(tx, blobIndex, binaryColumnName, tableName, data, isDownload) {
sync.log.trace("Entering kony.sync.blobManager.prepareJobs->populateOnDemandParams ");
sync.log.trace("params to the method are blobIdex "+blobIndex+" column "+tableName+"."+binaryColumnName);
var job = {};
var params = {};
var scopeName = kony.sync.scopes.syncTableScopeDic[tableName];
params.scopename = scopeName;
params.blobid = blobIndex;
params.strategy = kony.sync.scopes[scopeName][kony.sync.syncStrategy];
params.instanceid = kony.sync.getInstanceID();
params.clientid = kony.sync.getDeviceID();
params.appVersion = kony.sync.configVersion;
if(isDownload) {
params.url = kony.sync.getDownloadBinaryURL();
} else {
params.url = kony.sync.getUploadBinaryURL();
}
//This will populate userid, password, appid, sessionid, requestnumber
kony.sync.commonServiceParams(params);
params.enablebatching = "true";
var syncContext = getLastSyncContext(tx, scopeName);
//TODO - do we require these params in job?
/*
if (!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey])) {
params.httpconfig = {timeout: kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey]};
}
*/
// if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks]) &&
// !kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][scopeName])) {
// params[kony.sync.sessionTaskUploadErrorPolicy] = kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][scopeName][kony.sync.sessionTaskUploadErrorPolicy];
// }
// var syncContext = getLastSyncContext(tx, scopeName);
// sync.log.trace("populate on demand params -synccontext "+JSON.stringify(syncContext));
// if(!kony.sync.isNullOrUndefined(syncContext)) {
// var lastsynctime = syncContext[kony.sync.metaTableSyncTimeColumn];
// var upgradeSchemaLastSyncTime = syncContext[kony.sync.metaTableSchemaUpgradeSyncTimeColumn];
// if (kony.sync.schemaUpgradeDownloadPending) {
// params.tickcount = upgradeSchemaLastSyncTime;
// params.uppertickcount = lastsynctime;
// if (!kony.sync.isNullOrUndefined(kony.sync.schemaUpgradeContext)) {
// params.upgradecontext = kony.sync.schemaUpgradeContext;
// }
// } else {
// params.tickcount = lastsynctime;
// }
// }
var ondemandrequest = getOnDemandRequest(tx, syncContext, scopeName, tableName, data, isDownload, blobIndex, binaryColumnName);
sync.log.trace("populate on demand params -synccontext "+ondemandrequest);
if(isDownload) {
params.downloadrequest = ondemandrequest;
job[kony.sync.requestState] = kony.sync.blobManager.DOWNLOAD_IN_PROGRESS;
job[kony.sync.requestType] = kony.sync.isDownload;
} else {
params.uploadrequest = ondemandrequest;
job[kony.sync.requestState] = kony.sync.blobManager.UPLOAD_IN_PROGRESS;
job[kony.sync.requestType] = kony.sync.isUpload;
}
job[kony.sync.params] = params;
job[kony.sync.httpHeaders] = kony.sync.createClone(params[kony.sync.httpHeaders]);
if(isDownload) {
job[kony.sync.url] = kony.sync.getDownloadBinaryURL();
} else {
job[kony.sync.url] = kony.sync.getUploadBinaryURL();
}
job[kony.sync.blobId] = blobIndex;
job[kony.sync.blobName]= binaryColumnName;
delete params[kony.sync.httpHeaders];
sync.log.info("job details are "+JSON.stringify(job));
return job;
}
function getOnDemandRequest(tx, downloadContext, scopename, tableName, binaryColumnData, isDownload, blobIndex,
binaryColumnName) {
sync.log.trace("Entering kony.sync.blobManager.prepareJobs->getOnDemandRequest");
var resultSet = [];
var result = {};
var metaData = {};
metaData[kony.sync.type] = tableName;
//add the changetype for upload request.
if(!isDownload) {
metaData[kony.sync.syncStatusColumn] = "update";
}
result[kony.sync.metadata] = metaData;
result[kony.sync.konySyncReplaySequence] = 1;
if(!isDownload) {
delete binaryColumnData[kony.sync.mainTableChangeTypeColumn];
}
for(var column in binaryColumnData) {
if(column === binaryColumnName) {
if (isDownload) {
result[column] = binaryColumnData[column];
} else {
//read the filepath.
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobIndex, function(err){
});
//if the blobMeta has filePath.
//from the native, we read base64 content and add it to payload.
if(!kony.sync.isNullOrUndefined(blobMeta[kony.sync.blobManager.localPath])) {
result["filePath"] = blobMeta[kony.sync.blobManager.localPath];
}
}
} else {
result[column] = binaryColumnData[column];
}
}
resultSet.push(result);
//creating the d object.
var d = {};
d[kony.sync.syncobjects] = resultSet;
d[kony.sync.sync] = "not implemented";
d[kony.sync.blobSyncScope] = scopename;
d[kony.sync.serverBlob] = downloadContext[kony.sync.metaTableSyncTimeColumn];
d[kony.sync.clientId] = kony.sync.getDeviceID();
d[kony.sync.moreChangesAvailable] = false;
d[kony.sync.SequenceNumber] = 0;
var request = {};
request["d"] = d;
sync.log.trace("request object in getOnDemandRequest --> "+JSON.stringify(request));
return request;
}
function getLastSyncContext(tx, scopename) {
sync.log.trace("Entering kony.sync.blobManager.prepareJobs->getLastSyncContext");
var scope = kony.sync.scopes[scopename];
var datasource = scope[kony.sync.scopeDataSource];
var whereClause = [
{ key : kony.sync.metaTableScopeColumn, value : scopename },
{ key : kony.sync.metaTableFilterValue, value : "no filter"}
];
var resultSet = kony.sync.queryTable(tx, kony.sync.metaTableName, null, whereClause);
if(resultSet === false) {
sync.log.error("Error executing query on table "+kony.sync.metaTableName);
isError = true;
return;
}
var rowItem = null;
if(resultSet !== null && resultSet.rows.length > 0) {
rowItem = kony.db.sqlResultsetRowItem(tx, resultSet, 0);
}
return rowItem;
}
function getNextOnDemandRows(tx, isDownload) {
sync.log.trace("Entering kony.sync.blobManager.prepareJobs->getNextOnDemandRows");
//Select id, tablename, columnname from blobstoremanager table with status as 0% and state as DOWNLOAD_ACCEPTED
var selectClause = [kony.sync.blobManager.id, kony.sync.blobManager.tableName, kony.sync.blobManager.columnName]
var wcs = [];
if(isDownload) {
kony.table.insert(wcs, {key:kony.sync.blobManager.status,value:0,optype:"EQ",comptype:"AND"});
kony.table.insert(wcs, {key:kony.sync.blobManager.state,value:kony.sync.blobManager.DOWNLOAD_ACCEPTED,optype:"EQ"});
} else {
kony.table.insert(wcs, {key:kony.sync.blobManager.state,value:kony.sync.blobManager.UPLOAD_ACCEPTED,optype:"EQ"});
}
var resultSet = kony.sync.queryTable(tx, kony.sync.blobStoreManagerTable,selectClause, wcs, kony.sync.blobManager.ONDEMAND_FETCH_LIMIT);
return resultSet;
}
function single_transaction_callback(tx) {
try {
sync.log.trace("Entering kony.sync.blobManager.prepareJobs->single_transaction_callback");
//First check for ondemand rows to be downloaded
var download = true;
var resultSet = getNextOnDemandRows(tx, download);
var rowItemsList = [];
var rowItem = null;
var resultSetLength = null;
if(resultSet === false) {
sync.log.error("Error executing query ");
isError = true;
return;
}
if( ( resultSet !== null ) && ( resultSet.rows.length === 0) ) {
//If there are no records to download, fetch the records to be uploaded
sync.log.trace(" No records to download, get next records to upload ");
download = false;
resultSet = getNextOnDemandRows(tx, download);
if(resultSet === false) {
sync.log.error("Error executing query ");
isError = true;
return;
}
}
if(resultSet !== null) {
resultSetLength = resultSet.rows.length;
for(var i=0; i < resultSetLength; i++) {
rowItem = kony.db.sqlResultsetRowItem(tx, resultSet, i);
if(!kony.sync.isNullOrUndefined(rowItem)) {
rowItemsList.push(rowItem);
}
}
if(rowItemsList.length > 0) {
sync.log.trace("jobs retrieved from database.. "+JSON.stringify(rowItemsList));
populateOnDemandPayload(tx, rowItemsList, download);
} else {
return;
}
}
}catch(err) {
sync.log.error("kony.sync.blobManager.prepareJobs->exception occured "+JSON.stringify(err));
//errorcallback(err);
isError = true;
errorInfo = err;
}
}
var connection = kony.sync.getConnectionOnly(kony.sync.syncConfigurationDBName, kony.sync.syncConfigurationDBName, errorcallback);
if(connection !== null) {
kony.sync.startTransaction(connection, single_transaction_callback,
single_transaction_success_callback, single_transaction_error_callback);
}
};
kony.sync.blobManager.onDemandManager = function() {
};
kony.sync.blobManager.onDemandManager.jobs = null;
kony.sync.blobManager.onDemandManager.setJobs = function(jobs) {
kony.sync.blobManager.onDemandManager.jobs = null;
kony.sync.blobManager.onDemandManager.jobs = jobs;
binary.util.notifyToProcessJobs();
};
kony.sync.blobManager.getPreparedJobs = function() {
//var map = {'key':kony.sync.blobManager.onDemandManager.jobs};
//return map;
return kony.sync.blobManager.onDemandManager.jobs;
};
kony.sync.blobManager.onDemandManager.getJobs = function() {
return kony.sync.blobManager.onDemandManager.jobs;
};
kony.sync.blobManager.performCleanUp = function(cleanUpCallback) {
sync.log.trace("Entering kony.sync.performCleanUp");
var isError = false;
//once clean up is completed
function single_transaction_callback(tx) {
sync.log.trace("Entering kony.sync.performCleanUp - single_transaction_callback");
//parse through the konysyncBlobStoreManager and remove unwanted rows.
//Delete the rows in case of following states.
var deleteRecordStates = [kony.sync.blobManager.INSERT_PROCESSING,kony.sync.blobManager.INSERT_FAILED,
kony.sync.blobManager.DOWNLOAD_FAILED, kony.sync.blobManager.DOWNLOAD_IN_PROGRESS, kony.sync.blobManager.DOWNLOAD_ACCEPTED,
kony.sync.blobManager.UPDATE_FAILED, kony.sync.blobManager.UPDATE_PROCESSING,
kony.sync.blobManager.FILE_DOESNOT_EXIST
];
var whereClause = [];
for(var i = 0; i < deleteRecordStates.length; i++) {
var wc = {};
wc.key= kony.sync.blobManager.state;
wc.value = deleteRecordStates[i];
wc.comptype = "OR";
whereClause.push(wc);
}
var selectClause = [kony.sync.blobManager.id, kony.sync.blobManager.tableName, kony.sync.blobManager.columnName];
var result_set = kony.sync.queryTable(tx, kony.sync.blobStoreManagerTable, selectClause, whereClause);
var rowItem;
var valuesTable;
if(result_set !== null && result_set !== false) {
if(result_set.rows.length > 0) {
for(var k =0; k < result_set.rows.length; k++) {
//delete the blob entries with the given where clause.
rowItem = kony.db.sqlResultsetRowItem(tx, result_set, k);
sync.log.trace("record to be deleted in konysyncBlobStoreManager is "+JSON.stringify(rowItem));
var deleteResult = kony.sync.blobManager.deleteBlob(tx, rowItem[kony.sync.blobManager.id],
function(err) {
kony.sync.errorObject = err;
sync.log.error("kony.sync.blobManager.performCleanUp -error in deleteBlob "+
JSON.stringify(err));
isError = true;
});
sync.log.trace("after deleting record with id "+rowItem[kony.sync.blobManager.id]+" result is "+JSON.stringify(deleteResult));
if(deleteResult !== null && deleteResult !== false) {
//tx, tableName, values, wcs, errorCallback
var binaryColumnName = kony.sync.binaryMetaColumnPrefix + rowItem[kony.sync.blobManager.columnName];
valuesTable = {};
var wcs = [{
key: binaryColumnName,
value: rowItem[kony.sync.blobManager.id]
}];
valuesTable[binaryColumnName] = kony.sync.blobRefNotDefined;
var updateResult = kony.sync.blobManager.updateParentWithBlobReference(tx, rowItem[kony.sync.blobManager.tableName], valuesTable,
wcs, function (err) {
kony.sync.errorObject = err;
sync.log.error("kony.sync.blobManager.performCleanUp -error in updateParentWithBlobReference " +
JSON.stringify(err));
isError = true;
});
sync.log.trace("after updating record's blobref result is "+JSON.stringify(updateResult));
if(updateResult === null || updateResult === false) {
sync.log.error("kony.sync.blobManager.performCleanUp -error in updateParentWithBlobReference ");
isError = true;
}
} else {
sync.log.error("kony.sync.blobManager.performCleanUp -error in deleteBlob");
isError = true;
}
}
}
if(!isError) {
//change the state of upload_in_progress to upload_failed.
whereClause = [{
key: kony.sync.blobManager.state,
value: kony.sync.blobManager.UPLOAD_IN_PROGRESS
}];
result_set = kony.sync.queryTable(tx, kony.sync.blobStoreManagerTable, selectClause, whereClause);
if (result_set !== null && result_set !== false) {
if (result_set.rows.length > 0) {
for (var k = 0; k < result_set.rows.length; k++) {
rowItem = kony.db.sqlResultsetRowItem(tx, result_set, k);
valuesTable = {};
valuesTable.state = kony.sync.blobManager.UPLOAD_FAILED;
kony.sync.blobManager.updateBlobManager(tx, rowItem[kony.sync.blobManager.id], valuesTable,
function (err) {
kony.sync.errorObject = err;
sync.log.error("kony.sync.blobManager.performCleanUp -error in updateBlobManager " +
JSON.stringify(err));
isError = true;
}
);
}
}
} else {
sync.log.error("kony.sync.blobManager.performCleanUp - error in fetchFromBlobStoreManager");
isError = true;
}
}
} else {
sync.log.error("kony.sync.blobManager.performCleanUp - error in fetchFromBlobStoreManager");
isError = true;
}
}
function single_transaction_success_callback() {
sync.log.trace("Entering kony.sync.performCleanUp - single_transaction_success_callback");
if(!isError) {
kony.sync.isCleanUpJobCompleted = true;
}
cleanUpCallback(isError);
}
function single_transaction_error_callback() {
sync.log.trace("Entering kony.sync.performCleanUp - single_transaction_error_callback");
cleanUpCallback(true);
}
var connection = kony.sync.getConnectionOnly(kony.sync.syncConfigurationDBName, kony.sync.syncConfigurationDBName, cleanUpCallback);
if(connection !== null) {
kony.sync.startTransaction(connection, single_transaction_callback,
single_transaction_success_callback, single_transaction_error_callback);
}
};
// **************** End BlobStoreManager.js******************
// **************** End KonySyncBlobStoreManager.js*******************
// **************** Start KonySyncBlobUtils.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined") {
kony.sync.blobManager = {};
}
/**
* Method returns the download policy of the given column in the table if the type of column is binary
* else returns null
* @param tableName - tablename
* @param columnName - column name
* @returns {*} -downloadPolicy for binary column, null for non binary columns.
*/
kony.sync.getDownloadPolicy = function(tableName, columnName) {
var downloadPolicy = kony.sync.notSupported;
if(!kony.sync.isNullOrUndefined(kony.sync.scopes) && kony.sync.scopes.syncTableScopeDic.hasOwnProperty(tableName)) {
var scope = kony.sync.scopes[kony.sync.scopes.syncTableScopeDic[tableName]];
var tableColumns = scope.syncTableDic[tableName].Columns;
var isColumn = false;
for (var i = 0; i < tableColumns.length; i++) {
if (tableColumns[i].Name === columnName && tableColumns[i].type === "binary") {
isColumn = true;
if (tableColumns[i].hasOwnProperty(kony.sync.binaryPolicy)) {
downloadPolicy = tableColumns[i][kony.sync.binaryPolicy];
} else {
downloadPolicy = kony.sync.inline;
}
break;
}
};
}
return downloadPolicy;
};
/**
* Method checks whether the given column in binary column or not.
* @param tbname - table to which column belongs to.
* @param columnName - name of the column
* @returns {number|Number} - returns -1 if the column is not binary.
*/
kony.sync.getBinaryColumnsByPolicy = function(tbname, policy) {
var columnsWithRequestedPolicy = [];
if(!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname]) &&
!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns])) {
var binaryColumnsOfTable = kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns];
for (var j = 0; j < binaryColumnsOfTable.length; j++) {
var downloadPolicy = kony.sync.getDownloadPolicy(tbname, binaryColumnsOfTable[j]);
if (downloadPolicy === policy) {
columnsWithRequestedPolicy.push(binaryColumnsOfTable[j]);
}
}
}
return columnsWithRequestedPolicy;
};
/**
* Method checks whether the given column in binary column or not.
* @param tbname - table to which column belongs to.
* @param columnName - name of the column
* @returns {number|Number} - returns -1 if the column is not binary.
*/
kony.sync.isBinaryColumn = function(tbname, columnName) {
if(!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname]) &&
!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns])) {
var binaryColumnsOfTable = kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns];
return binaryColumnsOfTable.indexOf(columnName);
}
return -1;
};
/**
* Method used to find Blobref for the given record.
* @param tx - transaction id
* @param sql - sql statement
* @param params - sql params
* @param column - column name
* @param errorNotifier - error callback.
* @returns {{}} - blobref object containing pk values and blobreference.
*/
kony.sync.getBlobRef = function(tx, tableName, columnName, pks, errorNotifier) {
var wcs = [];
for (var key in pks) {
var wc = {};
wc.key = key;
wc.value = pks[key];
wc.comptype = "AND";
wcs.push(wc);
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_from(query, tableName);
var blobRefColumn = kony.sync.binaryMetaColumnPrefix + columnName;
kony.sync.qb_select(query, [blobRefColumn]);
kony.sync.qb_where(query, wcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var blobRef = kony.sync.blobRefNotFound;
//"NULL"
var result = kony.db.executeSql(tx, sql, params, function (err) {
kony.print("error in transaction call back " + JSON.stringify(err));
errorNotifier(err);
return;
});
if(result !== null && result !== false) {
if(result.rows.length > 0) {
var rowItem = kony.db.sqlResultsetRowItem(tx, result, 0);
blobRef= rowItem[kony.sync.binaryMetaColumnPrefix+columnName];
}
}
return blobRef;
}
/**
* Method used to validate pkTable.
* @param pkColumns - pkColumns related to the table
* @param pkTable - received pkTable from the user.
* @returns {*} - updated pkTable after removing non binary keys.
* returns null incase all the pk keys are not sent.
*/
kony.sync.validatePkTable = function(pkColumns, pkTable) {
var receivedPkColumns = Object.keys(pkTable);
//remove non pk columns..
for(var i = receivedPkColumns.length - 1; i >= 0 ; i--) {
if(pkColumns.indexOf(receivedPkColumns[i]) === -1) {
delete pkTable[receivedPkColumns[i]];
receivedPkColumns.splice(i , 1);
}
}
//check if info is received for all pks.
if(receivedPkColumns.length !== pkColumns.length) {
//throw an error. info about all pks is mandate.
return null;
} else {
return pkTable;
}
};
kony.sync.removeBinaryMetaColumns = function(tablename, columns) {
var nonMetaColumns = [];
for(var j =0; j < columns.length; j++) {
if(columns[j].Name.indexOf(kony.sync.binaryMetaColumnPrefix) !== 0) {
nonMetaColumns.push(columns[j]);
}
}
return nonMetaColumns;
}
kony.sync.getBlobContext = function(tx, tableName, columnName, pks, errorNotifier) {
var wcs = [];
for (var key in pks) {
var wc = {};
wc.key = key;
wc.value = pks[key];
wc.comptype = "AND";
wcs.push(wc);
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_from(query, tableName);
kony.sync.qb_select(query, [columnName]);
kony.sync.qb_where(query, wcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var blobContext = kony.sync.blobRefNotFound;
//"NULL"
var result = kony.db.executeSql(tx, sql, params, function (err) {
kony.print("error in transaction call back " + JSON.stringify(err));
errorNotifier(err);
});
if(result !== null && result !== false) {
if(result.rows.length > 0) {
var rowItem = kony.db.sqlResultsetRowItem(tx, result, 0);
blobContext= rowItem[columnName];
}
}
return blobContext;
};
kony.sync.getBinaryColumns = function(tablename) {
if(kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tablename]) ||
kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tablename][kony.sync.columns])){
return;
} else {
return kony.sync.scopes.syncScopeBlobInfoMap[tablename][kony.sync.columns];
}
};
kony.sync.getSyncToDeviceField = function(tableName, columnName) {
sync.log.trace("Entering kony.sync.getSyncToDeviceField for table "+tableName+" and column "+columnName);
if(kony.sync.isNullOrUndefined(kony.sync.scopes.syncToDeviceMap) &&
!kony.sync.scopes.syncToDeviceMap.hasOwnProperty(tableName+columnName)){
return;
}
return kony.sync.scopes.syncToDeviceMap[tableName+columnName];
};
//initialize Binary stats properties
kony.sync.initBinaryStatProperties = function() {
//current sync cycle stats
var uploadBinaryStats = {};
var downloadBinaryStats = {};
//initializing upload related stats..
uploadBinaryStats.totalNumberOfUploads = 0;
uploadBinaryStats.uploadsCompleted = 0;
uploadBinaryStats.uploadsFailed = 0;
//initializing download related stats..
downloadBinaryStats.totalNumberOfDownloads = 0;
downloadBinaryStats.downloadsCompleted = 0;
downloadBinaryStats.downloadsFailed = 0;
kony.sync.currentSyncStats.uploadBinaryStats = uploadBinaryStats;
kony.sync.currentSyncStats.downloadBinaryStats = downloadBinaryStats;
};
//initialize stat params
kony.sync.initBinaryStats = function() {
sync.log.trace("Entered kony.sync.initBinaryStats - initializing binary stats parameters.. ");
kony.sync.currentSyncStats = {};
kony.sync.initBinaryStatProperties();
//last sync cycle stats
kony.sync.lastSyncStats = {};
};
//assign currentSyncStats to lastSyncStats
kony.sync.reinitializeBinaryStats = function() {
kony.sync.lastSyncStats = kony.sync.currentSyncStats;
//current sync cycle stats
kony.sync.currentSyncStats = {};
kony.sync.initBinaryStatProperties();
};
//increment number of uploads/ downloads..
kony.sync.incrementTotalJobs = function(isDownload) {
if(isDownload) {
sync.log.trace("kony.sync.incrementTotalJobs downloads incremented");
kony.sync.currentSyncStats.downloadBinaryStats.totalNumberOfDownloads =
kony.sync.currentSyncStats.downloadBinaryStats.totalNumberOfDownloads + 1;
} else{
sync.log.trace("kony.sync.incrementTotalJobs uploads incremented");
kony.sync.currentSyncStats.uploadBinaryStats.totalNumberOfUploads =
kony.sync.currentSyncStats.uploadBinaryStats.totalNumberOfUploads + 1;
}
};
//increment number of completed uploads / downloads
kony.sync.incrementCompletedJobs = function(isDownload) {
if(isDownload) {
sync.log.trace("kony.sync.incrementCompletedJobs downloads incremented");
kony.sync.currentSyncStats.downloadBinaryStats.downloadsCompleted =
kony.sync.currentSyncStats.downloadBinaryStats.downloadsCompleted + 1;
} else {
sync.log.trace("kony.sync.incrementCompletedJobs uploads incremented");
kony.sync.currentSyncStats.uploadBinaryStats.uploadsCompleted =
kony.sync.currentSyncStats.uploadBinaryStats.uploadsCompleted + 1;
}
};
//increment number of failed uploads / downloads
kony.sync.incrementFailedJobs = function(isDownload) {
if(isDownload) {
sync.log.trace("kony.sync.incrementFailedJobs downloads incremented");
kony.sync.currentSyncStats.downloadBinaryStats.downloadsFailed =
kony.sync.currentSyncStats.downloadBinaryStats.downloadsFailed + 1;
} else {
sync.log.trace("kony.sync.incrementFailedJobs uploads incremented");
kony.sync.currentSyncStats.uploadBinaryStats.uploadsFailed =
kony.sync.currentSyncStats.uploadBinaryStats.uploadsFailed + 1;
}
};
kony.sync.invokeBinaryNotifiers = function(isDownload) {
if(isDownload) {
if(kony.sync.onBinaryDownload && kony.sync.isValidFunctionType(kony.sync.onBinaryDownload)) {
kony.sync.onBinaryDownload(kony.sync.currentSyncStats.downloadBinaryStats);
}
} else {
if(kony.sync.onBinaryUpload && kony.sync.isValidFunctionType(kony.sync.onBinaryUpload)) {
kony.sync.onBinaryUpload(kony.sync.currentSyncStats.uploadBinaryStats);
}
}
};
// **************** End KonySyncBlobUtils.js*******************
// **************** Start KonySyncChunkingHelper.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync)=== "undefined"){
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined") {
kony.sync.blobManager = {};
}
//Checks whether download response is eligible for chunking or not
kony.sync.eligibleForChunking = function(result){
sync.log.trace("Entering kony.sync.eligibleForChunking");
if(!kony.sync.isNull(result.opstatus) && result.opstatus !== 0){
return false;
}
return (!kony.sync.isNull(result.d) &&
result.d.error === "false" && !kony.sync.isNull(result.d.__sync[kony.sync.payloadIdKey]));
};
//Add chunk info in metatable
kony.sync.startChunking = function(url, serviceParams, result, callback){
sync.log.trace("Entering kony.sync.startChunking");
sync.log.info("storing payload info in konysyncchunkmetainfo");
var isError = false;
var payloadId = result.d.__sync[kony.sync.payloadIdKey];
var chunkCount = result.d.__sync[kony.sync.chunkCountKey];
var hashSum = result.d.__sync[kony.sync.chunkHashSum];
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, transactionFailedCallback);
if(dbconnection!==null){
kony.db.transaction(dbconnection, transactionCallback, transactionFailedCallback, transactionSuccessCallback);
}
function transactionCallback(tx){
sync.log.trace("Entering kony.sync.startChunking->transactionCallback");
//clear meta data from chunking table
if(kony.sync.clearChunkMetaData(tx, kony.sync.currentScope[kony.sync.scopeName])===false){
isError = true;
return;
}
//store payload info in konysyncchunkmetainfo
var values = {};
values[kony.sync.metaTablePayloadId] = payloadId;
values[kony.sync.metaTableChunkSize] = kony.sync.getChunkSize();
values[kony.sync.metaTableChunkAck] = kony.sync.chunkNotAcknowledged;
values[kony.sync.metaTableChunkHashSum] = hashSum;
values[kony.sync.metaTableChunkDiscarded] = kony.sync.chunkNotDiscarded;
values[kony.sync.metaTableChunkCount] = chunkCount;
values[kony.sync.metaTableScopeColumn] = kony.sync.currentScope[kony.sync.scopeName];
var query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, values);
kony.sync.qb_insert(query, kony.sync.chunkMetaTableName);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
}
}
//call callback with framed error
function transactionFailedCallback(){
sync.log.trace("Entering kony.sync.startChunking->transactionFailedCallback");
if(isError){
sync.log.error("Error occurred while inserting chunk information in metatable");
callback(kony.sync.frameDownloadError(null, null, 1));
}
else {
var errMsg = "Error occurred while opening transaction to store chunk information in metatable";
sync.log.error(errMsg);
callback(kony.sync.frameDownloadError(null, errMsg, 2));
}
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.startChunking->transactionSuccessCallback");
kony.sync.downloadChunks(url, serviceParams, payloadId, chunkCount, hashSum, result, false, null, callback);
}
};
//Starts Chunking
kony.sync.downloadChunks = function(url, serviceParams, payloadId, chunkCount, hashSum, initialData, isResumed, downloadedChunks, callback){
sync.log.trace("Entering kony.sync.downloadChunks");
if(kony.sync.isSyncStopped){
kony.sync.stopSyncSession();
return;
}
var retries = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
var serverParams = {};
serviceParams[kony.sync.payloadIdKey] = payloadId;
serviceParams[kony.sync.chunkCountKey] = chunkCount;
sync.log.trace("kony.sync.downloadChunks chunkCount "+chunkCount+" and downloadedChunks ",downloadedChunks);
var noOfParallelCalls = 1;
//temporarily disabling parallel calls
/*if(!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.maxParallelChunksKey])){
if(kony.sync.currentSyncConfigParams[kony.sync.maxParallelChunksKey] > 0){
noOfParallelCalls = kony.sync.currentSyncConfigParams[kony.sync.maxParallelChunksKey];
}
}*/
//sync.log.info("Maximum parallel chunks:" + noOfParallelCalls);
var chunkingFailed = 0;
var chunkProcessed = 0;
var chunkErrorMap = {};
var utf8data = null;
var corruptedData = false;
var callNo = 0;
var infoObj = {};
var chunkMap;
var i = null;
//process first chunk if chunking is not resumed from an earlier point
sync.log.trace("kony.sync.downloadChunks isResumed ",isResumed);
if(!isResumed){
downloadNetworkCallback(initialData, 1);
}
/*if(!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey])){
//infoObj[kony.sync.numberOfRetriesKey] = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
}*/
if(isResumed){
//find the remaining ids
//create map for all the ids
sync.log.trace("kony.sync.downloadChunks - isResumed true for chunkCount "+chunkCount+ " with downloadedChunks ",downloadedChunks);
chunkMap = {};
for(i=1; i<=chunkCount; i++) {
chunkMap[i] = 0; //initially set 0 for all the ids
}
for(i in downloadedChunks) {
sync.log.trace("kony.sync.downloadChunks process chunks ",downloadedChunks);
chunkMap[downloadedChunks[i]] = 1; //set 1 for downloaded ids
chunkProcessed++; //count processed chunks
}
i=1;
for(callNo=1; callNo<=chunkCount; callNo++){
if(chunkMap[callNo]===0){
infoObj[kony.sync.chunkNoKey] = callNo;
serviceParams[kony.sync.chunkNoKey] = callNo;
kony.sync.callOnChunkStart(chunkCount, payloadId, kony.sync.currentScope[kony.sync.scopeName], callNo, serviceParams);
sync.log.info("Hitting the service with URL :" + url + " with params:" + JSON.stringify(serviceParams));
retries = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
kony.sync.invokeServiceAsync(url, serviceParams, downloadNetworkCallbackStatus, infoObj);
if(i>=noOfParallelCalls){
callNo++;
break;
}
i++;
}
}
}
else{
for(callNo=2; callNo<=chunkCount; callNo++){
infoObj[kony.sync.chunkNoKey] = callNo;
serviceParams[kony.sync.chunkNoKey] = callNo;
kony.sync.callOnChunkStart(chunkCount, payloadId, kony.sync.currentScope[kony.sync.scopeName], callNo, serviceParams);
sync.log.info("Hitting the service with URL :" + url + " with params:" + JSON.stringify(serviceParams));
retries = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
kony.sync.invokeServiceAsync(url, serviceParams, downloadNetworkCallbackStatus, infoObj);
if(callNo > noOfParallelCalls){
callNo++;
break;
}
}
}
function downloadNetworkCallbackStatus(status, result, info){
sync.log.trace("Entering kony.sync.downloadChunks->downloadNetworkCallbackStatus with status "+status+" result "
+JSON.stringify(result)+ " info ",info);
if(status === 400){
sync.log.info("Got Response for Chunk No:" + info[kony.sync.chunkNoKey]);
//fallback when opstatus < 0
if(result.opstatus < 0){
sync.log.info("Got result.opstatus:" + result.opstatus + " and result.errcode:" + result.errcode + "setting errcode to opstatus");
result.opstatus = result.errcode;
}
if(kony.sync.eligibleForRetry(result.opstatus, retries)){
retries--;
kony.sync.retryServiceCall(url, result, info, retries, downloadNetworkCallback, serviceParams);
}
else{
kony.sync.setSessionID(result);
downloadNetworkCallback(result, info[kony.sync.chunkNoKey]);
}
}else if(status === 300){
downloadNetworkCallback(kony.sync.getNetworkCancelError(),info[kony.sync.chunkNoKey]);
}
}
function downloadNetworkCallback(result, info){
sync.log.trace("Entering kony.sync.downloadChunks->downloadNetworkCallback with result "+JSON.stringify(result)+" " +
"info -> ",info);
serverParams[kony.sync.hostName] = kony.sync.getServerDetailsHostName(result);
serverParams[kony.sync.ipAddress] = kony.sync.getServerDetailsIpAddress(result);
sync.log.trace("downloadNetworkCallback isResumed "+isResumed+" for callNo "+callNo+" withChunkMap ",chunkMap);
if(callNo <= chunkCount){
if(!isResumed){
if(callNo !== 0){
infoObj[kony.sync.chunkNoKey] = callNo;
serviceParams[kony.sync.chunkNoKey] = callNo;
kony.sync.callOnChunkStart(chunkCount, payloadId, kony.sync.currentScope[kony.sync.scopeName], callNo, serviceParams);
sync.log.info("Hitting the service with URL :" + url + " with params:", serviceParams);
retries = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
kony.sync.invokeServiceAsync(url, serviceParams, downloadNetworkCallbackStatus, infoObj);
callNo++;
}
}
else{
for(; callNo<=chunkCount; callNo++){
if(chunkMap[callNo]===0){
infoObj[kony.sync.chunkNoKey] = callNo;
serviceParams[kony.sync.chunkNoKey] = callNo;
kony.sync.callOnChunkStart(chunkCount, payloadId, kony.sync.currentScope[kony.sync.scopeName], callNo, serviceParams);
sync.log.info("Hitting the service with URL :" + url + " with params:", serviceParams);
retries = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
kony.sync.invokeServiceAsync(url, serviceParams, downloadNetworkCallbackStatus, infoObj);
if(callNo >= noOfParallelCalls + 1){
callNo++;
break;
}
}
}
}
}
var chunkId = info;
if(kony.sync.isValidJSTable(info)){
chunkId = info[kony.sync.chunkNoKey];
}
if(!kony.sync.isNull(result.opstatus) && result.opstatus !== 0){
chunkingFailed++;
sync.log.error("Error occurred while downloading chunks: Code=" + result.opstatus + ", message=" + result.errmsg);
chunkErrorMap[chunkId] = result.errmsg;
kony.sync.callOnChunkError(chunkCount, payloadId, kony.sync.currentScope[kony.sync.scopeName], chunkId, chunkCount - chunkProcessed, chunkProcessed, result.opstatus, result.errmsg, serverParams);
sync.log.trace("downloadNetworkCallback - calling allChunksProcessed - for result.opstatus !== 0");
if(allChunksProcessed()){
handleError();
}
}
else if(result.d.error === "true"){
chunkingFailed++;
sync.log.error("Error occurred while downloading chunks: message=" + result.d.msg);
chunkErrorMap[chunkId] = result.d.msg;
kony.sync.callOnChunkError(chunkCount, payloadId, kony.sync.currentScope[kony.sync.scopeName], chunkId, chunkCount - chunkProcessed, chunkProcessed, kony.sync.errorCodeUnknownServerError, result.d.msg, serverParams);
sync.log.trace("downloadNetworkCallback - calling allChunksProcessed - for result.d.error == true");
if(allChunksProcessed()){
handleError();
}
}
else{
//store in local DB
//sync.log.trace("calling kony.sync.storeChunkInDB with payl");
kony.sync.storeChunkInDB(payloadId, chunkId, result.d[kony.sync.chunkDataKey], kony.sync.currentScope[kony.sync.scopeName], chunkDataStoredCallback);
sync.log.trace("downloadNetworkCallback - calling allChunksProcessed -storeChunkInDB");
if(allChunksProcessed()){
handleError();
}
}
}
function allChunksProcessed(){
sync.log.trace("allChunksProcessed chunkProcessed "+chunkProcessed+" chunkingFailed "+chunkingFailed+" chunkCount "+chunkCount);
var areAllChunksProcessed = (chunkProcessed + chunkingFailed === chunkCount);
sync.log.trace("allChunksProcessed result "+areAllChunksProcessed);
return areAllChunksProcessed;
}
function handleError(){
sync.log.info("All chunking calls for current batch with total of " + chunkCount + " completed.")
if(chunkProcessed > 0){
sync.log.info("Chunks successfully downloaded and stored in DB:" + chunkProcessed);
}
//error occurred in one or more chunks
if(chunkingFailed > 0){
sync.log.error("Chunks failed either to downloaded or while storing in DB:" + chunkingFailed);
//frame error
var framedErrorResponse = kony.sync.frameDownloadError(kony.sync.getErrorMessage(kony.sync.errorCodeChunking), chunkErrorMap, null, kony.sync.errorCodeChunking);
sync.log.error(kony.sync.getErrorMessage(kony.sync.errorCodeChunking), chunkErrorMap);
//call download complete callback with error
callback(framedErrorResponse);
return false;
}else{
return true;
}
}
function chunkDataStoredCallback(chunkId, errorMap){
sync.log.trace("Entering kony.sync.downloadChunks->chunkDataStoredCallback");
//if error, add to errorMap
if(!kony.sync.isNull(errorMap)){
sync.log.error("chunkDataStoredCallback errorMap incrementing chunkingFailed. ",errorMap);
chunkingFailed++;
chunkErrorMap[chunkId] = errorMap.errorCode;
sync.log.error("Error occurred while storing chunk " + chunkId + " in DB");
kony.sync.callOnChunkError(chunkCount, payloadId, kony.sync.currentScope[kony.sync.scopeName], chunkId, chunkCount - chunkProcessed, chunkProcessed, errorMap.errorCode, errorMap.errorMessage, serverParams, errorMap.errorInfo);
}
else{
chunkProcessed++;
sync.log.trace("chunkDataStoredCallback incrementing number of chunks processed.."+chunkProcessed);
kony.sync.callOnChunkSuccess(chunkCount, payloadId, kony.sync.currentScope[kony.sync.scopeName], chunkId, chunkCount - chunkProcessed, chunkProcessed, serverParams);
}
sync.log.trace("chunkDataStoredCallback - calling allChunksProcessed ");
if(allChunksProcessed() && handleError()){
//gather all results from chunkMap
sync.log.trace("chunkDataStoredCallback allChunksProcessed true and handleError true");
kony.sync.getChunksFromDB(payloadId, chunkCount, kony.sync.currentScope[kony.sync.scopeName], chunkDataProcessCallback);
} /*else {
sync.log.error("chunkDataStoredCallback Either allChunksProcessed or handleError is not true..");
var errorObj = kony.sync.getErrorTable(kony.sync.errorCodeChunking, kony.sync.getErrorMessage(kony.sync.errorCodeChunking));
sync.log.error("Error in chunking ", errorObj);
//call download complete callback with error
callback(errorObj);
}*/
}
function chunkDataProcessCallback(data, isError, errorType){
sync.log.trace("Entering kony.sync.downloadChunks->chunkDataProcessCallback");
//error occurred while retrieving info
if(isError){
//frame error
sync.log.error(kony.sync.getErrorMessage(kony.sync.errorCodeChunking), data);
var framedErrorResponse = null;
if(errorType===1 || errorType===2){
framedErrorResponse = kony.sync.frameDownloadError(null, null, errorType);
}else{
framedErrorResponse = kony.sync.frameDownloadError(kony.sync.getErrorMessage(kony.sync.errorCodeChunking), data, null, kony.sync.errorCodeChunking);
}
//call download complete callback with error
callback(framedErrorResponse);
}
//all chunks downloaded successfully
else{
utf8data = data;
//calculate checksum hash of utf8data;
var checksum = kony.sync.createHash("sha256", utf8data);
//compare checksum with server sent hashsum;
if(!kony.string.equalsIgnoreCase(checksum, hashSum)){
sync.log.error("Received corrupted chunk data for payloadId= " + payloadId + ", clearing erroneous chunks from db.");
corruptedData = true;
}
//release checksum
checksum = null;
//clear the payload from metainfo;
kony.sync.clearChunkForPayload(payloadId, kony.sync.currentScope[kony.sync.scopeName], corruptedData, chunkDataClearback);
}
}
function chunkDataClearback(data, isError){
sync.log.trace("Entering kony.sync.downloadChunks->chunkDataClearback");
//error occurred while clearing chunkInfo
if(isError || corruptedData){
//create error message
var errMsg = "Following errors occurred:";
if(isError){
errMsg += "Error occurred while clearing chunk information from DB";
}
if(corruptedData){
if(isError){
errMsg += ", ";
}
errMsg += "Received corrupted chunk data for payloadId= " + payloadId;
}
errMsg += ".";
sync.log.error(errMsg);
//frame error
var framedErrorResponse = kony.sync.frameDownloadError(errMsg, data, null, kony.sync.errorCodeChunking);
//call download complete callback with error
callback(framedErrorResponse);
}
else{
//convert json string to json object
var myJsonObject = null;
try{
myJsonObject = JSON.parse(utf8data);
}
catch(e){
var errMsg = kony.sync.getErrorMessage(kony.sync.errorCodeParseError,utf8data,e);
sync.log.error(errMsg);
myJsonObject = null;
utf8data = null;
callback(kony.sync.frameDownloadError(errMsg, e, null, kony.sync.errorCodeParseError));
return;
}
utf8data = null;
//call the callback with final result
callback(myJsonObject);
}
}
};
//framing download error
kony.sync.frameDownloadError = function(errorMessage, errorInfo, dbError, errorCode){
sync.log.trace("Entering kony.sync.frameDownloadError");
var result = {};
result.d = {};
result.d.error = "true";
if(dbError===1){//statement error
result.d.opstatus = kony.sync.errorObject.errorCode;
result.d.msg = kony.sync.errorObject.errorMessage;
result.d.errorInfo = kony.sync.errorObject.errorInfo;
}
else if(dbError===2){//transaction error
result.d.opstatus = kony.sync.errorCodeTransaction;
result.d.msg = kony.sync.getErrorMessage(kony.sync.errorCodeTransaction);
result.d.errorInfo = kony.sync.errorObject.errorInfo;
sync.log.error(result.d.msg);
}
else{
result.d.msg = errorMessage;
result.d.errorInfo = errorInfo;
result.d.opstatus = errorCode;
}
return result;
};
//This method will store chunks in DB
kony.sync.storeChunkInDB = function(payloadId, chunkId, chunkData, scopeName, callback, storedChunkCallback){
sync.log.trace("Entering kony.sync.storeChunkInDB for chunkId "+chunkId);
var isError = false;
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
function transactionCallback(tx){
sync.log.trace("Entering kony.sync.storeChunkInDB->transactionCallback for chunkID "+chunkId);
sync.log.trace("kony.sync.storeChunkInDB - payloadId -> "+payloadId+" chunkId -> "+chunkId+" chunkData -> ",chunkData);
//check for dupicate chunks
var wcs = [];
wcs.push({key:kony.sync.metaTableScopeColumn, value:scopeName});
wcs.push({key:kony.sync.chunkTableChunkId, value:chunkId});
wcs.push({key:kony.sync.chunkTablePayloadId, value:payloadId});
var query = kony.sync.qb_createQuery();
kony.sync.qb_where(query, wcs);
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, kony.sync.chunkTableName);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params);
sync.log.trace("kony.sync.storeChunkInDB - resultset for check duplicate counts ",resultset);
if(resultset === null || resultset===false){
isError = true;
return;
}
if(resultset.rows.length > 0){
//ignore the chunk as it is already stored by some earlier call
return;
}
//store chunk into DB
var values = {};
values[kony.sync.chunkTableChunkData] = chunkData;
values[kony.sync.chunkTableChunkId] = chunkId;
values[kony.sync.chunkTablePayloadId] = payloadId;
values[kony.sync.metaTableScopeColumn] = scopeName;
values[kony.sync.chunkTableTimeStamp] = (new Date()).toString();
query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, values);
kony.sync.qb_insert(query, kony.sync.chunkTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
var storeChunkResultSet = kony.sync.executeSql(tx, sql, params);
sync.log.trace("kony.sync.storeChunkInDB - resultset storing chunk into db ",storeChunkResultSet);
if(storeChunkResultSet===false || storeChunkResultSet === null){
isError = true;
}
}
function transactionFailedCallback(){
sync.log.trace("Entering kony.sync.storeChunkInDB->transactionFailedCallback");
callback(chunkId, kony.sync.getTransactionError(isError));
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.storeChunkInDB->transactionSuccessCallback");
callback(chunkId);
}
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, transactionFailedCallback);
if(dbconnection!==null){
sync.log.trace("kony.sync.storeChunkInDb - dbConnection successful");
kony.db.transaction(dbconnection, transactionCallback, transactionFailedCallback, transactionSuccessCallback);
}
};
//This method will retrieve all chunks from DB
kony.sync.getChunksFromDB = function(payloadId, chunkCount, scopeName, callback){
sync.log.trace("Entering kony.sync.getChunksFromDB");
var isError = false;
var base64 = "";
var unknownError = "";
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, transactionFailedCallback);
if(dbconnection!==null){
kony.db.transaction(dbconnection, transactionCallback, transactionFailedCallback, transactionSuccessCallback);
}
function transactionCallback(tx){
sync.log.trace("Entering kony.sync.getChunksFromDB->transactionCallback");
var wcs = [];
wcs.push({key:kony.sync.metaTableScopeColumn, value:scopeName});
wcs.push({key:kony.sync.chunkTablePayloadId, value:payloadId});
var query = kony.sync.qb_createQuery();
kony.sync.qb_where(query, wcs);
kony.sync.qb_select(query, null);
kony.sync.qb_orderBy(query, [{key:kony.sync.chunkTableChunkId, sortType:"asc"}]);
kony.sync.qb_from(query, kony.sync.chunkTableName);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params);
if(resultset===false){
isError = true;
return;
}
if(resultset.rows.length !== chunkCount){
//should never reach here
unknownError = "Unknown Error: Chunks in DB(" + resultset.rows.length + ") are not equal to chunkcount(" + chunkCount + ")";
sync.log.error(unknownError);
isError = true;
return;
}
for(var i=0; i<resultset.rows.length; i++){
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, i);
base64 = base64 + rowItem[kony.sync.chunkTableChunkData];
}
}
function transactionFailedCallback(){
sync.log.trace("Entering kony.sync.getChunksFromDB->transactionFailedCallback");
callback(null, true, isError===true?1:2);
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.getChunksFromDB->transactionSuccessCallback");
if(isError){
callback(unknownError, true);
}
else{
callback(base64, false);
}
}
};
//clear chunking info from DB
kony.sync.clearChunkForPayload = function(payloadId, scopeName, chunkError, callback){
sync.log.trace("Entering kony.sync.clearChunkForPayload");
var isError = false;
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, transactionFailedCallback);
if(dbconnection!==null){
kony.db.transaction(dbconnection, transactionCallback, transactionFailedCallback, transactionSuccessCallback);
}
function transactionCallback(tx){
sync.log.trace("Entering kony.sync.clearChunkForPayload->transactionCallback");
//set complete flag in metainfo table
var values = {};
values[kony.sync.metaTableChunkAck] = kony.sync.chunkCompleteButNotAcknowledged;
//if problem occurred while chunking, mark discard flag for next download
if(chunkError===true){
values[kony.sync.metaTableChunkDiscarded] = kony.sync.chunkDiscarded;
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, values);
kony.sync.qb_update(query, kony.sync.chunkMetaTableName);
kony.sync.qb_where(query, [{key:kony.sync.metaTableScopeColumn, value:scopeName}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
return;
}
//clearing chunkdata from chunk table
var wcs = [];
wcs.push({key:kony.sync.metaTableScopeColumn, value:scopeName});
wcs.push({key:kony.sync.chunkTablePayloadId, value:payloadId});
query = kony.sync.qb_createQuery();
kony.sync.qb_where(query, wcs);
kony.sync.qb_delete(query, kony.sync.chunkTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
return;
}
}
function transactionFailedCallback(){
sync.log.trace("Entering kony.sync.clearChunkForPayload->transactionFailedCallback");
var errMsg = "";
if(isError){
errMsg = "Error occurred while clearing chunk information from " + kony.sync.chunkTableName;
callback({"errorCode":kony.sync.errorCodeSQLStatement, "errorMessage":errMsg}, true);
}
else{
errMsg = "Error occurred while opening transaction for clearing chunk information from " + kony.sync.chunkTableName;
callback({"errorCode":kony.sync.errorCodeTransaction, "errorMessage":errMsg}, true);
}
sync.log.error(errMsg);
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.clearChunkForPayload->transactionSuccessCallback");
callback(null, false);
}
};
kony.sync.getChunkSize = function(){
sync.log.trace("Entering kony.sync.getChunkSize");
if(!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.chunkSizeKey])){
return kony.sync.currentSyncConfigParams[kony.sync.chunkSizeKey];
}
};
//This API checks whether chunking should be called before download or not
kony.sync.checkForChunkingBeforeDownload = function(serverblob, normalDownloadCallback, downloadNetworkCallback, schemaUpgradeServerblob){
sync.log.trace("Entering kony.sync.checkForChunkingBeforeDownload");
var scopeName = kony.sync.currentScope[kony.sync.scopeName];
var isError = false;
var chunkingResumed = 0;
var lastsynctime = serverblob;
var chunkData = [];
var chunkMetaData = null;
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, transactionFailedCallback);
if(dbconnection!==null){
kony.db.transaction(dbconnection, transactionCallback, transactionFailedCallback, transactionSuccessCallback);
}
function transactionCallback(tx){
sync.log.trace("Entering kony.sync.checkForChunkingBeforeDownload->transactionCallback");
var wcs = [];
wcs.push({key:kony.sync.metaTableScopeColumn, value:scopeName});
var query = kony.sync.qb_createQuery();
kony.sync.qb_where(query, wcs);
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, kony.sync.chunkMetaTableName);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params);
if(resultset===false){
isError = true;
return;
}
if(resultset.rows.length > 0){
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
var pendingAck = rowItem[kony.sync.metaTableChunkAck];
var chunkDiscarded = rowItem[kony.sync.metaTableChunkDiscarded];
if(pendingAck === 0 && chunkDiscarded === 0){
chunkingResumed = 1; //resume chunking
}
else{
chunkingResumed = 2; //just send payloadid for acknowledgement
}
chunkMetaData = rowItem; //get meta data
if(chunkingResumed===2 && pendingAck!==kony.sync.chunkCompleteAndWaitingForAck){
//updating metadata status as sent for acknowledgement
var values = {};
values[kony.sync.metaTableChunkAck] = kony.sync.chunkCompleteAndWaitingForAck;
query = kony.sync.qb_createQuery();
kony.sync.qb_where(query, wcs);
kony.sync.qb_set(query, values);
kony.sync.qb_update(query, kony.sync.chunkMetaTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
resultset = kony.sync.executeSql(tx, sql, params);
if(resultset===false){
isError = true;
return;
}
}
//get chunk ids for that payloadid
wcs = [];
wcs.push({key:kony.sync.metaTableScopeColumn, value:scopeName});
wcs.push({key:kony.sync.chunkTablePayloadId, value:rowItem[kony.sync.metaTablePayloadId]});
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.chunkTableChunkId]);
kony.sync.qb_where(query, wcs);
kony.sync.qb_from(query, kony.sync.chunkTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
resultset = kony.sync.executeSql(tx, sql, params);
if(resultset===false){
isError = true;
return;
}
for(var i=0; i<resultset.rows.length; i++){
rowItem = kony.db.sqlResultsetRowItem(tx, resultset, i);
chunkData[i] = rowItem[kony.sync.chunkTableChunkId];
}
}
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.checkForChunkingBeforeDownload->transactionSuccessCallback");
if(chunkingResumed===1){
//continue chunking from last point
var params = kony.sync.getChunkingParams(lastsynctime, schemaUpgradeServerblob);
var hashSum = chunkMetaData[kony.sync.metaTableChunkHashSum];
var chunkCount = chunkMetaData[kony.sync.metaTableChunkCount];
var payloadId = chunkMetaData[kony.sync.metaTablePayloadId];
kony.sync.globalIsDownloadStarted = false;
kony.sync.downloadChunks(kony.sync.getChunkDownloadURL(), params, payloadId, chunkCount, hashSum, null, true, chunkData, downloadNetworkCallback);
}
else if(chunkingResumed===2){
normalDownloadCallback(chunkMetaData[kony.sync.metaTablePayloadId]);
}
else{
//proceed with normal download
normalDownloadCallback();
}
}
function transactionFailedCallback(){
sync.log.trace("Entering kony.sync.checkForChunkingBeforeDownload->transactionFailedCallback");
var errMsg = "";
if(isError){
errMsg = "Error occurred while inserting chunk information in metatable";
downloadNetworkCallback(kony.sync.frameDownloadError(null,errMsg,1));
}
else{
errMsg = "Error occurred while opening transaction to store chunk information in metatable";
downloadNetworkCallback(kony.sync.frameDownloadError(null,errMsg,2));
}
sync.log.error(errMsg);
}
};
kony.sync.getChunkingParams = function(serverblob, schemaUpgradeServerblob) {
sync.log.trace("Entering kony.sync.getChunkingParams");
//create params
if (kony.sync.isNullOrUndefined(serverblob)) {
serverblob = "";
}
var params = {};
kony.sync.commonServiceParams(params);
if(kony.sync.schemaUpgradeDownloadPending){
params.tickcount = schemaUpgradeServerblob;
params.uppertickcount = serverblob;
if(!kony.sync.isNullOrUndefined(kony.sync.schemaUpgradeContext)){
params.upgradecontext = kony.sync.schemaUpgradeContext;
}
} else {
params.tickcount = serverblob;
}
params.clientid = kony.sync.getDeviceID();
if(!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey])){
params.httpconfig = {timeout:kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey]};
}
return params;
};
//API to abort all pending chunk requests
sync.cancelPendingChunkRequests = function(successcallback, errorcallback){
sync.log.trace("Entering kony.sync.cancelPendingChunkRequests");
if(!kony.sync.isSyncInitialized(errorcallback)){
return;
}
var isError = false;
var dbname = kony.sync.scopes[0][kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, transactionFailedCallback);
if(dbconnection!==null){
kony.db.transaction(dbconnection, transactionCallback, transactionFailedCallback, transactionSuccessCallback);
}
function transactionCallback(tx){
sync.log.trace("Entering kony.sync.cancelPendingChunkRequests->transactionCallback");
//change status in metatable to discarded
var values = {};
values[kony.sync.metaTableChunkDiscarded] = kony.sync.chunkDiscarded;
var query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, values);
kony.sync.qb_update(query, kony.sync.chunkMetaTableName);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
}
//delete pending chunks from chunk table
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, kony.sync.chunkTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
return;
}
}
function transactionFailedCallback(){
sync.log.trace("Entering kony.sync.cancelPendingChunkRequests->transactionFailedCallback");
kony.sync.callTransactionError(errorcallback, isError);
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.cancelPendingChunkRequests->transactionSuccessCallback");
kony.sync.verifyAndCallClosure(successcallback);
}
};
//This will delete chunk data from metatable after receiving acknowledgement
kony.sync.clearChunkMetaData = function(tx, scopeName){
sync.log.trace("Entering kony.sync.clearChunkMetaData");
var wcs = [];
wcs.push({key:kony.sync.metaTableScopeColumn, value:scopeName});
wcs.push({key:kony.sync.metaTableChunkAck, value:kony.sync.chunkCompleteAndWaitingForAck});
var query = kony.sync.qb_createQuery();
kony.sync.qb_where(query, wcs);
kony.sync.qb_delete(query, kony.sync.chunkMetaTableName);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
};
kony.sync.callOnChunkStart = function(chunkCount, payloadId, scope, chunkid, chunkRequest){
sync.log.trace("Entering kony.sync.callOnChunkStart");
var params = {};
params[kony.sync.chunkCountKey] = chunkCount;
params[kony.sync.payloadIdKey] = payloadId;
params[kony.sync.metaTableScopeColumn] = scope;
params[kony.sync.chunkTableChunkId] = chunkid;
params[kony.sync.chunkRequestKey] = chunkRequest;
return kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onChunkStart], params);
};
kony.sync.callOnChunkSuccess = function(chunkCount, payloadId, scope, chunkid, pendingChunks, chunksDownloaded, serverParams){
sync.log.trace("Entering kony.sync.callOnChunkSuccess");
var params = {};
params[kony.sync.chunkCountKey] = chunkCount;
params[kony.sync.payloadIdKey] = payloadId;
params[kony.sync.metaTableScopeColumn] = scope;
params[kony.sync.chunkTableChunkId] = chunkid;
params[kony.sync.pendingChunksKey] = pendingChunks;
params[kony.sync.chunksDownloadedKey] = chunksDownloaded;
params[kony.sync.serverDetails] = serverParams;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onChunkSuccess], params);
};
kony.sync.callOnChunkError = function(chunkCount, payloadId, scope, chunkid, pendingChunks, chunksDownloaded, errorCode, errorMsg, serverParams, errorInfo){
sync.log.trace("Entering kony.sync.callOnChunkError");
var params = {};
params[kony.sync.chunkCountKey] = chunkCount;
params[kony.sync.payloadIdKey] = payloadId;
params[kony.sync.metaTableScopeColumn] = scope;
params[kony.sync.chunkTableChunkId] = chunkid;
params[kony.sync.pendingChunksKey] = pendingChunks;
params[kony.sync.chunksDownloadedKey] = chunksDownloaded;
params.errorCode = errorCode;
params.errorMessage = errorMsg;
params[kony.sync.serverDetails] = serverParams;
params.errorInfo = errorInfo;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onChunkError], params);
};
// **************** End KonySyncChunkingHelper.js*******************
// **************** Start KonySyncDBOperations.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync)=== "undefined"){
sync = {};
}
kony.sync.insert = function (tx, tablename, values, insert_callback, markForUpload) {
sync.log.trace("Entering kony.sync.insert ");
var scopename = kony.sync.scopes.syncTableScopeDic[tablename];
if (markForUpload === false){
values[kony.sync.mainTableChangeTypeColumn] = kony.sync.insertColStatusDI;
} else {
values[kony.sync.mainTableChangeTypeColumn] = kony.sync.insertColStatus;
}
values[kony.sync.mainTableSyncVersionColumn] = kony.sync.currentSyncScopesState[scopename];
var scope = kony.sync.scopes[scopename];
var generatedPK = kony.sync.replaceautogeneratedPK(scopename, scope.syncTableDic[tablename], values, tx, insert_callback);
if (generatedPK === false) {
return false;
}
//Check if it is original or save the original state.
if (markForUpload === false) {
if (kony.sync.addToRollBack(tx, tablename, values, kony.sync.insertColStatusDI, null, insert_callback) === false) {
return false;
}
} else {
if (kony.sync.addToRollBack(tx, tablename, values, kony.sync.insertColStatus, null, insert_callback) === false) {
return false;
}
}
if (kony.sync.insertEx(tx, tablename, values, insert_callback) === false) {
return false;
}
var syncorder = kony.sync.getSyncOrder(scopename, tx, insert_callback);
if (syncorder !== null && syncorder !== false) {
values[kony.sync.mainTableChangeTypeColumn] = null;
values[kony.sync.mainTableSyncVersionColumn] = null;
if (markForUpload === false) {
values[kony.sync.historyTableChangeTypeColumn] = kony.sync.insertColStatusDI;
} else {
values[kony.sync.historyTableChangeTypeColumn] = kony.sync.insertColStatus;
}
values[kony.sync.historyTableSyncVersionColumn] = kony.sync.currentSyncScopesState[scopename];
values[kony.sync.historyTableReplaySequenceColumn] = syncorder + 1;
if (kony.sync.insertEx(tx, tablename + kony.sync.historyTableName, values, insert_callback) === false) {
return false;
}
if (kony.sync.setSyncOrder(scopename, syncorder + 1, tx, insert_callback) === false) {
return false;
}
} else {
// not expected to come here
sync.log.fatal("Invalid sync order in insert function");
}
return generatedPK;
};
kony.sync.insertEx = function (tx, tablename, values, errorcallback, rollback) {
sync.log.trace("Entering kony.sync.insertEx ");
var query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, values);
kony.sync.qb_insert(query, tablename);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params, errorcallback, rollback);
};
kony.sync.purgeInsertEx = function (tx, tablename, values, rollback) {
sync.log.trace("Entering kony.sync.purgeInsertEx ");
var query = kony.sync.qb_createQuery();
kony.sync.qb_purgeInsert(query, tablename, values);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params, null, rollback);
};
kony.sync.error_callbackdb = function (error) {
sync.log.trace("Entering kony.sync.error_callbackdb ");
sync.log.error("@@@@@@@@@@@@@ -" + error.message + " @@@ " + error.code);
};
kony.sync.update = function (tx, tablename, values, wc, markForUpload) {
sync.log.trace("Entering kony.sync.update ");
//Check if it is original or save the original state.
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename + "_history");
kony.sync.qb_where(query, wc);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var myres = kony.sync.executeSql(tx, sql, params);
if (myres === false) {
return false;
}
for(var k=0;k< myres.rows.length; k++){
var recordres = kony.db.sqlResultsetRowItem(tx, myres, 0);
if(recordres === null){
return false;
}
var prevMarkForupload = recordres.konysyncchangetype;
if( prevMarkForupload == 90 && markForUpload == true ){
return kony.sync.errorCodeInvalidMarkForUploadValue;
}
}
if (markForUpload === false) {
if(kony.sync.addToRollBack(tx, tablename, values, kony.sync.updateColStatusDU, wc)===false){
return false;
}
} else {
if(kony.sync.addToRollBack(tx, tablename, values, kony.sync.updateColStatus, wc)===false){
return false;
}
}
var scopename = kony.sync.scopes.syncTableScopeDic[tablename];
if (markForUpload === false) {
values[kony.sync.mainTableChangeTypeColumn] = kony.sync.updateColStatusDU;
} else {
values[kony.sync.mainTableChangeTypeColumn] = kony.sync.updateColStatus;
}
values[kony.sync.mainTableSyncVersionColumn] = kony.sync.currentSyncScopesState[scopename];
var resultSet = kony.sync.updateEx(tx, tablename, values, wc);
var updateResult = {};
if(resultSet===false){
return false;
}else{
updateResult[kony.sync.numberOfRowsUpdated] = resultSet.rowsAffected;
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
kony.sync.qb_where(query, wc);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var syncorder = kony.sync.getSyncOrder(scopename, tx);
if(syncorder === false){
return false;
}
resultSet = kony.sync.executeSql(tx, sql, params);
if (resultSet === false) {
return false;
} else if(resultSet.rows.length === 0) {
sync.log.error("No record found with the given where condition "+JSON.stringify(wc));
kony.sync.errorObject = kony.sync.getErrorTable(
kony.sync.errorCodeRecordDoNotExist,
kony.sync.getErrorMessage(kony.sync.errorCodeRecordDoNotExist, JSON.stringify(wc))
);
return false;
}
var record = kony.db.sqlResultsetRowItem(tx, resultSet, 0);
if(record === null){
return false;
}
if (!kony.sync.isNullOrUndefined(syncorder)) {
record[kony.sync.historyTableReplaySequenceColumn] = syncorder + 1;
if (markForUpload === false) {
record[kony.sync.historyTableChangeTypeColumn] = kony.sync.updateColStatusDU;
} else {
record[kony.sync.historyTableChangeTypeColumn] = kony.sync.updateColStatus;
}
record[kony.sync.historyTableSyncVersionColumn] = kony.sync.currentSyncScopesState[scopename];
if(kony.sync.addUpdateToHistoryTable(tx, tablename + kony.sync.historyTableName, record)===false){
return false;
}
if(kony.sync.setSyncOrder(scopename, syncorder + 1, tx) === false) {
return false;
}
} else {
// not expected to come here
sync.log.fatal("Invalid sync order in insert function");
}
return updateResult;
};
kony.sync.updateBatch = function (tx, tablename, values, wc, markForUpload, primaryKey) {
sync.log.trace("Entering kony.sync.updateBatch ");
//adding original values to rollback tables if exists
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0] + " " + wc;
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params, null, null, "Adding original values to rollback tables if exists");
var i = 0;
var record = null;
if (resultSet === false) {
return false;
}
var num_records = resultSet.rows.length;
for (i = 0; i < num_records; i++) {
record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
if (markForUpload === false) {
record[kony.sync.originalTableChangeTypeColumn] = kony.sync.updateColStatusDU;
} else {
record[kony.sync.originalTableChangeTypeColumn] = kony.sync.updateColStatus;
}
record[kony.sync.originalTableSyncVersionColumn] = record[kony.sync.originalTableChangeTypeColumn];
record[kony.sync.mainTableChangeTypeColumn] = null;
record[kony.sync.mainTableSyncVersionColumn] = null;
//record[kony.sync.mainTableHashSumColumn] = null;
kony.sync.insertEx(tx, tablename + kony.sync.originalTableName, record, null, false);
}
//Get Primary Key from where clause
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0] + " " + wc;
params = query_compile[1];
resultSet = kony.sync.executeSql(tx, sql, params);
if (resultSet === false) {
return false;
}
num_records = resultSet.rows.length;
var pkSet = [];
for (i = 0; i < num_records; i++) {
record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
var pkRecord = [];
for(var j in primaryKey){
pkRecord.push({"key":primaryKey[j], "value":record[primaryKey[j]]});
}
pkSet.push(pkRecord);
}
//updating main tables
var scopename = kony.sync.scopes.syncTableScopeDic[tablename];
if (markForUpload === false) {
values[kony.sync.mainTableChangeTypeColumn] = kony.sync.updateColStatusDU;
} else {
values[kony.sync.mainTableChangeTypeColumn] = kony.sync.updateColStatus;
}
values[kony.sync.mainTableSyncVersionColumn] = kony.sync.currentSyncScopesState[scopename];
// update the flag only if this record is present on server
resultSet = kony.sync.updateEx(tx, tablename, values, wc, null, true);
var updateResult = {};
if(resultSet===false){
return false;
}else{
updateResult[kony.sync.numberOfRowsUpdated] = resultSet.rowsAffected;
//kony.sync.verifyAndCallClosure(update_callback, {kony.sync.numberOfRowsUpdated:resultSet.rowsAffected});
}
var syncorder = kony.sync.getSyncOrder(scopename, tx);
if(syncorder === false){
return false;
}
for(i in pkSet){
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
kony.sync.qb_where(query, pkSet[i]);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
resultSet = kony.sync.executeSql(tx, sql, params);
if (resultSet === false) {
return false;
}
record = kony.db.sqlResultsetRowItem(tx, resultSet, 0);
syncorder = syncorder + 1;
record[kony.sync.historyTableReplaySequenceColumn] = syncorder;
record[kony.sync.historyTableSyncVersionColumn] = kony.sync.currentSyncScopesState[scopename];
if(kony.sync.addUpdateToHistoryTable(tx, tablename + kony.sync.historyTableName, record)===false){
return false;
}
}
if(kony.sync.setSyncOrder(scopename, syncorder, tx)===false){
return false;
}
return updateResult;
};
kony.sync.updateEx = function (tx, tablename, values, wc, update_callback, isBatch) {
sync.log.trace("Entering kony.sync.updateEx ");
var query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, values);
kony.sync.qb_update(query, tablename);
if(kony.sync.isNullOrUndefined(isBatch)) {
kony.sync.qb_where(query, wc);
}
//local sqlUpdate = "update "..tablename.." set "..updateStr..wc;
var query_compile = kony.sync.qb_compile(query);
var sqlUpdate = "";
if (isBatch === true) {
sqlUpdate = query_compile[0] + " " + wc;
} else {
sqlUpdate = query_compile[0];
}
var params = query_compile[1];
return kony.sync.executeSql(tx, sqlUpdate, params);
};
kony.sync.upsertEx = function (tx, tablename, values, wc, callback) {
sync.log.trace("Entering kony.sync.upsertEx ");
//#ifdef android
//Check whether row exists or not
//OLD Implementation
if ((kony.sync.isrowexists(tx, tablename, wc, callback))) {
//Do an update
kony.sync.serverUpdateCount = kony.sync.serverUpdateCount + 1;
// update if the user hasn't changed the record
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] + 1;
kony.sync.updateEx(tx, tablename, values, wc);
} else {
//Do an Insert
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] + 1;
kony.sync.insertEx(tx, tablename, values, callback);
kony.sync.serverInsertCount = kony.sync.serverInsertCount + 1;
}
//#else
//#ifdef tabrcandroid
//Check whether row exists or not
//OLD Implementation
if ((kony.sync.isrowexists(tx, tablename, wc, callback))) {
//Do an update
kony.sync.serverUpdateCount = kony.sync.serverUpdateCount + 1;
// update if the user hasn't changed the record
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] + 1;
kony.sync.updateEx(tx, tablename, values, wc);
} else {
//Do an Insert
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] + 1;
kony.sync.insertEx(tx, tablename, values, callback);
kony.sync.serverInsertCount = kony.sync.serverInsertCount + 1;
}
//#else
var result = kony.sync.purgeInsertEx(tx, tablename, values, callback);
if (result !== false && result.rowsAffected === 0) {
kony.sync.serverUpdateCount = kony.sync.serverUpdateCount + 1;
// update if the user hasn't changed the record
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] + 1;
kony.sync.updateEx(tx, tablename, values, wc);
} else {
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] + 1;
kony.sync.serverInsertCount = kony.sync.serverInsertCount + 1;
}
//#endif
//#endif
};
kony.sync.isrowexists = function (tx, tablename, wc, errorCallback) {
sync.log.trace("Entering kony.sync.isrowexists ");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
kony.sync.qb_where(query, wc);
//local sql = "select * from "..tablename..wc;
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params, errorCallback);
if (resultset === false) {
return false;
}
if (resultset.rows.length === 1) {
return true;
} else {
return null; //if row doesn't exists, we should add it to rollback table
}
};
//Function to delete one(batch)change
kony.sync.remove = function (tx, tablename, wc, isLocal, markForUpload, errorCallback) {
sync.log.trace("Entering kony.sync.remove ");
//Check if it is original or save the original state.
if (isLocal !== true) {
if (markForUpload === false) {
if(kony.sync.addToRollBack(tx, tablename, null, kony.sync.deleteColStatusDD, wc, errorCallback) === false) {
return false;
}
} else {
if(kony.sync.addToRollBack(tx, tablename, null, kony.sync.deleteColStatus, wc, errorCallback) === false) {
return false;
}
}
}
//Getting the records with the where clause
var scopename = kony.sync.scopes.syncTableScopeDic[tablename];
var scope = kony.sync.scopes[scopename];
var syncTable = scope.syncTableDic[tablename];
var record = null;
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
kony.sync.qb_where(query, wc);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params, errorCallback);
if (resultSet === false) {
return false;
}
var num_records = resultSet.rows.length;
var rowsDeleted = 0;
for (var i = 0; i < num_records; i++) {
//adding changes to history table
if(isLocal !== true) {
record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
var values = [];
values[kony.sync.historyTableHashSumColumn] = record[kony.sync.mainTableHashSumColumn];
if(!kony.sync.isNullOrUndefined(syncTable.Columns)){
for (var j = 0; j < syncTable.Columns.length; j++) {
var column = syncTable.Columns[j];
values[column.Name] = record[column.Name];
}
}
var syncorder = kony.sync.getSyncOrder(scopename, tx, errorCallback);
if(syncorder === false){
return false;
}
if (syncorder !== null) {
values[kony.sync.historyTableReplaySequenceColumn] = syncorder + 1;
if (markForUpload === false) {
values[kony.sync.historyTableChangeTypeColumn] = kony.sync.deleteColStatusDD;
} else {
values[kony.sync.historyTableChangeTypeColumn] = kony.sync.deleteColStatus;
}
values[kony.sync.historyTableSyncVersionColumn] = kony.sync.currentSyncScopesState[scopename];
if(kony.sync.insertEx(tx, tablename + kony.sync.historyTableName, values, null, errorCallback) === false){
return false;
}
if(kony.sync.setSyncOrder(scopename, syncorder + 1, tx, errorCallback) === false) {
return false;
}
} else {
// not expected to come here
sync.log.fatal("Invalid sync order in insert function");
}
} else {
//deleting all local changes from history
record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
sync.log.debug("Removing Local Changes: ", record);
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, null);
kony.sync.qb_from(query, tablename + kony.sync.historyTableName);
kony.sync.qb_where(query, wc);
query_compile = kony.sync.qb_compile(query);
params = query_compile[1];
sql = query_compile[0];
if(kony.sync.executeSql(tx, sql, params, errorCallback) === false){
return false;
}
//deleting all local changes from original
record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
sync.log.debug("Removing Local Changes from original: ", record);
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, null);
kony.sync.qb_from(query, tablename + kony.sync.originalTableName);
kony.sync.qb_where(query, wc);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params, errorCallback) === false){
return false;
}
}
//deleting from main table
var resultSet1 = kony.sync.removeEx(tx, tablename, wc, null , errorCallback);
if(resultSet1===false){
return false;
}
rowsDeleted = rowsDeleted + resultSet1.rowsAffected;
}
var deleteResult = {};
deleteResult[kony.sync.numberOfRowsDeleted] = rowsDeleted;
return deleteResult;
};
//Function to delete more than one(batch)changes
kony.sync.deleteBatch = function (tx, tablename, wc, isLocal, markForUpload, errorCallback) {
sync.log.trace("Entering kony.sync.deleteBatch ");
var scopename = kony.sync.scopes.syncTableScopeDic[tablename];
var i = null;
var record = null;
//adding original values to rollback tables if exists
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0] + " " + wc;
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params, errorCallback);
if (resultSet === false) {
return false;
}
var num_records = resultSet.rows.length;
if (isLocal === false) {
for (i = 0; i <= num_records - 1; i++) {
record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
record[kony.sync.originalTableChangeTypeColumn] = kony.sync.deleteColStatus;
record[kony.sync.originalTableSyncVersionColumn] = record[kony.sync.originalTableChangeTypeColumn];
record[kony.sync.mainTableChangeTypeColumn] = null;
record[kony.sync.mainTableSyncVersionColumn] = null;
//record[kony.sync.mainTableHashSumColumn] = null;
kony.sync.insertEx(tx, tablename + kony.sync.originalTableName, record, null, false);
}
}
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0] + " " + wc;
params = query_compile[1];
var syncorder = kony.sync.getSyncOrder(scopename, tx, errorCallback);
if(syncorder === false){
return false;
}
resultSet = kony.sync.executeSql(tx, sql, params, errorCallback);
if(resultSet === false){
return false;
}
num_records = resultSet.rows.length;
if ((syncorder !== null)) {
for (i = 0; i < num_records; i++) {
record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
//adding change replay to history tables
if (isLocal === false) {
syncorder = syncorder + 1;
record[kony.sync.historyTableReplaySequenceColumn] = syncorder;
if (markForUpload === false) {
record[kony.sync.historyTableChangeTypeColumn] = kony.sync.deleteColStatusDD;
} else {
record[kony.sync.historyTableChangeTypeColumn] = kony.sync.deleteColStatus;
}
record[kony.sync.historyTableSyncVersionColumn] = kony.sync.currentSyncScopesState[scopename];
if(kony.sync.insertEx(tx, tablename + kony.sync.historyTableName, record, errorCallback)===false){
return false;
}
}
//deleting local changes from history table
else {
sync.log.debug("Removing Local Changes: ", record);
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, null);
kony.sync.qb_from(query, tablename + kony.sync.historyTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0] + " " + wc;
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params, errorCallback)===false){
return false;
}
sync.log.debug("Removing Local Changes from original: ", record);
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, null);
kony.sync.qb_from(query, tablename + kony.sync.originalTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0] + " " + wc;
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params, errorCallback) === false) {
return false;
}
}
}
if(kony.sync.setSyncOrder(scopename, syncorder, tx, errorCallback)===false){
return false;
}
} else {
// not expected to come here
sync.log.fatal("Invalid sync order in insert function");
}
//deleting main tables
resultSet = kony.sync.removeEx(tx, tablename, wc, true, errorCallback);
if(resultSet === false){
return false;
}
var deleteResult = {};
deleteResult[kony.sync.numberOfRowsDeleted] = resultSet.rowsAffected;
return deleteResult;
};
kony.sync.removeEx = function (tx, tablename, wc, isBatch, errorcallback) {
sync.log.trace("Entering kony.sync.removeEx ");
var query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, tablename);
if (kony.sync.isNullOrUndefined(isBatch)) {
kony.sync.qb_where(query, wc);
}
//local sql = "delete from "..tablename.." "..wc;
var query_compile = kony.sync.qb_compile(query);
var sql = "";
if (isBatch === true) {
sql = query_compile[0] + " " + wc;
} else {
sql = query_compile[0];
}
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params, errorcallback);
};
kony.sync.addToRollBack = function (tx, tablename, values, changetype, wcs, errorCallback) {
sync.log.trace("Entering kony.sync.addToRollBack ");
var originalwcs = kony.sync.CreateCopy(wcs);
var originalvalues = kony.sync.CreateCopy(values);
var rowExists = null;
if(changetype === kony.sync.insertColStatus || changetype === kony.sync.insertColStatusDI){
originalvalues[kony.sync.originalTableChangeTypeColumn] = changetype;
originalvalues[kony.sync.originalTableSyncVersionColumn] = null;
originalvalues[kony.sync.mainTableChangeTypeColumn] = null;
originalvalues[kony.sync.mainTableSyncVersionColumn] = null;
originalvalues[kony.sync.mainTableHashSumColumn] = null;
var scope = kony.sync.scopes[kony.sync.scopes.syncTableScopeDic[tablename]];
var pkColumns = scope.syncTableDic[tablename].Pk_Columns;
var pkRecord = [];
for(var j in pkColumns){
pkRecord.push({"key":pkColumns[j], "value":originalvalues[pkColumns[j]]});
}
rowExists = kony.sync.isrowexists(tx, tablename + kony.sync.originalTableName, pkRecord);
if (rowExists === true) {
//Original State is already saved, no need to save again
return true;
} else if (rowExists === false) {
return false;
} else {
if (kony.sync.insertEx(tx, tablename + kony.sync.originalTableName, originalvalues) === false) {
return false;
} else {
return true;
}
}
}
rowExists = kony.sync.isrowexists(tx, tablename + kony.sync.originalTableName, wcs);
if (rowExists === true) {
//Original State is already saved, no need to save again
return true;
} else if (rowExists === false) {
return false;
} else if(rowExists === null){
kony.table.insert(originalwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : "nil",
comptype : "OR",
openbrace : true
});
kony.table.insert(originalwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : "-1",
comptype : "OR",
closebrace : true
});
//table.insert(originalwcs,{key = kony.sync.mainTableChangeTypeColumn, value = "-1"})
var record = kony.sync.getOriginalRow(tx, tablename, originalwcs, errorCallback);
if (record === false) {
return false;
}
/* This logic is not needed as when row is not already present in rollback table and
waiting for acknowledgement,it should not be backed up in original table because
rollbacking it would lead to inconsistency
Note: This case generally occurs in persistent strategy when record waits for acknowledgement
if (record === null) {
//means record got changed but pending for acknowledgement
kony.table.remove(originalwcs);
kony.table.insert(originalwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : "-1",
optype : "EQ",
comptype : "OR",
openbrace : true
});
kony.table.insert(originalwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : changetype,
optype : "EQ",
comptype : "OR"
});
kony.table.insert(originalwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : "90",
optype : "EQ",
comptype : "OR"
});
kony.table.insert(originalwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : "91",
optype : "EQ",
closebrace : true
});
record = kony.sync.getOriginalRow(tx, tablename, originalwcs, errorCallback);
if (record === false) {
return false;
}
}
*/
if (record !== null) {
//Records not equal to nil means that it is not pending to be uploaded/acknowledged. So original state has to saved.
record[kony.sync.originalTableChangeTypeColumn] = changetype;
record[kony.sync.originalTableSyncVersionColumn] = record[kony.sync.mainTableSyncVersionColumn];
record[kony.sync.mainTableChangeTypeColumn] = null;
record[kony.sync.mainTableSyncVersionColumn] = null;
//record[kony.sync.mainTableHashSumColumn] = null;
record[kony.sync.mainTableHashSumColumn] = record[kony.sync.originalTableHashSumColumn];
return kony.sync.insertEx(tx, tablename + kony.sync.originalTableName, record);
}
}
};
kony.sync.getOriginalRow = function (tx, tablename, wcs, errorcallback) {
sync.log.trace("Entering kony.sync.getOriginalRow ");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
kony.sync.qb_where(query, wcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params, errorcallback);
if (!resultset) {
return false;
}
if (resultset.rows.length === 1) {
return kony.db.sqlResultsetRowItem(tx, resultset, 0);
} else {
return null;
}
};
kony.sync.syncDropDatabase = function (dbList, successcallback, errorcallback) {
sync.log.trace("Entering kony.sync.syncDropDatabase ");
sync.log.info("Dropping database list: ", dbList);
var isError = false;
function single_transaction_success_callback(res) {
sync.log.trace("Entering single_transaction_success_callback");
sync.log.debug("Single Select callback result: ", res);
if (!kony.sync.isNullOrUndefined(dbList) && !kony.sync.isNullOrUndefined(dbList[0]) && !kony.sync.isNullOrUndefined(dbList[0].dbname)){
dbname = dbList[0].dbname;
//var connection1 = kony.db.openDatabaseSync(dbname, "1.0", dbname, 5 * 1024 * 1024);
//kony.db.transaction(connection1, single_transaction_callback, single_transaction_error_callback, single_transaction_success_callback);
var connection1 = kony.sync.getConnectionOnly(dbname, dbname);
kony.sync.startTransaction(connection1, single_transaction_callback, single_transaction_success_callback, single_transaction_error_callback);
} else {
sync.log.info("Deleting all binary files ");
if(typeof(binary) !== "undefined" && typeof(binary.util) !== "undefined") {
binary.util.deleteAllBinaryFiles();
}
sync.log.info("Reinitializing...");
sync.init(successcallback, errorcallback);
}
}
function single_transaction_callback(tx) {
sync.log.trace("Entering single_transaction_callback");
sync.log.info("Dropping database: ", dbList[0].dbname);
for (var i in dbList[0].tableList) {
var v = dbList[0].tableList[i];
if(kony.sync.dropTable(tx, v)===false){
isError = true;
return;
}
}
dbList = dbList.slice(1);
}
function single_transaction_error_callback(res) {
sync.log.trace("Entering single_transaction_error_callback");
sync.log.error("Sync Reset failed ", res);
//kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getSyncResetFailed());
kony.sync.isResetInProgress = false;
kony.sync.callTransactionError(isError, errorcallback);
}
var dbname = dbList[0].dbname;
var connection = kony.sync.getConnectionOnly(dbname, dbname);
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback, single_transaction_error_callback);
};
kony.sync.dropTable = function (tx, tablename) {
sync.log.trace("Entering kony.sync.dropTable ");
sync.log.info("Dropping tablename ", tablename);
var query = null;
if ((kony.sync.getBackEndDBType() === kony.sync.dbTypeSQLCE)) {
query = "Drop Table " + tablename;
} else if ((kony.sync.getBackEndDBType() === kony.sync.dbTypeSQLLite)) {
query = "Drop Table if exists " + tablename;
}
return kony.sync.executeSql(tx, query, null);
};
kony.sync.addUpdateToHistoryTable = function(tx, tablename, values){
sync.log.trace("Entering kony.sync.addUpdateToHistoryTable ");
var toUpdate = false;
if(!kony.sync.trackIntermediateUpdates){
//frame primary key
var scope = kony.sync.scopes[kony.sync.scopes.syncTableScopeDic[tablename]];
var pkColumns = scope.syncTableDic[tablename].Pk_Columns;
var wc = [];
if(!kony.sync.isNullOrUndefined(pkColumns )){
for (var j = 0;j < pkColumns.length; j++){
if(!kony.sync.isNullOrUndefined(values[pkColumns[j]])){
kony.table.insert(wc, {key:pkColumns[j], value:values[pkColumns[j]]});
}
}
}
//Get the row and check its changetype
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
kony.sync.qb_where(query, wc);
kony.sync.qb_orderBy(query, [{key:kony.sync.historyTableReplaySequenceColumn, sortType:"desc"}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
var lastRecord = null;
var lastChangeType = null;
if(resultSet===false){
return false;
}
if(resultSet.rows.length > 0){
lastRecord = kony.db.sqlResultsetRowItem(tx, resultSet, 0);
lastChangeType = "" + lastRecord[kony.sync.historyTableChangeTypeColumn];
if(lastChangeType === kony.sync.updateColStatus || lastChangeType === kony.sync.updateColStatusDU){
toUpdate = true;
//update the last row
query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, values);
kony.sync.qb_update(query, tablename);
kony.table.insert(wc, {key:kony.sync.historyTableReplaySequenceColumn, value:lastRecord[kony.sync.historyTableReplaySequenceColumn]});
kony.sync.qb_where(query, wc);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
}
}
}
if(!toUpdate){
var query1 = kony.sync.qb_createQuery();
kony.sync.qb_set(query1, values);
kony.sync.qb_insert(query1, tablename);
var query_compile1 = kony.sync.qb_compile(query1);
var sql1 = query_compile1[0];
var params1 = query_compile1[1];
return kony.sync.executeSql(tx, sql1, params1);
}
};
// **************** End KonySyncDBOperations.js*******************
// **************** Start KonySyncDownload.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync)=== "undefined"){
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined"){
kony.sync.blobManager = {};
}
kony.sync.syncDownloadChanges = function (sname, dbname, onCompletion){
sync.log.trace("Entering kony.sync.syncDownloadChanges ");
kony.sync.onDownloadCompletion = onCompletion;
kony.sync.resetbatchsessionglobals();
kony.sync.PersisChangestobeDeleted = []; //Used for upload after delete in persistence strategey
sync.log.info("Download started for scope : ", sname);
kony.sync.currentSyncScopeFilter = null;
if(kony.sync.isValidJSTable(kony.sync.currentSyncConfigParams[kony.sync.filterParams])){
var scopeFilter = kony.sync.currentSyncConfigParams[kony.sync.filterParams][kony.sync.currentScope[kony.sync.scopeName]];
sync.log.info("scope Filter for " + kony.sync.currentScope[kony.sync.scopeName] + " is :" + scopeFilter);
if (kony.sync.isNullOrUndefined(scopeFilter)) {
kony.sync.getLastSynctime(sname, dbname, kony.sync.syncDownloadchangesGetLastSynctime);
} else {
//current_sync_scopefilter_index = 0;
//kony.sync.syncDownloadbyFilter(current_sync_scopefilter_index);
kony.sync.syncDownloadbyFilter();
}
} else {
kony.sync.getLastSynctime(sname, dbname, kony.sync.syncDownloadchangesGetLastSynctime);
}
};
//kony.sync.syncDownloadbyFilter = function (index) {
kony.sync.syncDownloadbyFilter = function () {
sync.log.trace("Entering kony.sync.syncDownloadbyFilter ");
var scopeFilter = kony.sync.currentSyncConfigParams[kony.sync.filterParams][kony.sync.currentScope[kony.sync.scopeName]];
//if (index < scopeFilter.length) {
var scopejsonfilter = {
//"d" : scopeFilter[index]
"d" : scopeFilter
};
var filtervaluejson = JSON.stringify(scopejsonfilter);
sync.log.debug(filtervaluejson);
kony.sync.currentSyncScopeFilter = scopeFilter; //scopeFilter[index];
kony.sync.getLastSynctimeFilter(kony.sync.currentScope[kony.sync.scopeName], filtervaluejson, kony.sync.currentScope[kony.sync.scopeDataSource], kony.sync.syncDownloadchangesGetLastSynctime);
/*} else {
kony.sync.globalIsDownloadStarted = true;
kony.sync.onDownloadCompletion(false, null);
}*/
};
kony.sync.syncDownloadchangesGetLastSynctime = function(rowItem) {
sync.log.trace("Entering kony.sync.syncDownloadchangesGetLastSynctime ");
var lastsynctime = rowItem[0][kony.sync.metaTableSyncTimeColumn];
sync.log.info("Last Sync Time with Server : " + lastsynctime);
var upgradeSchemaLastSyncTime = rowItem[0][kony.sync.metaTableSchemaUpgradeSyncTimeColumn];
var serverChanges = null;
var startTime = new Date();
var isError = false;
if(kony.sync.schemaUpgradeDownloadPending && kony.sync.isSchemaUpgradeTimeStampEmpty(lastsynctime)){
sync.log.trace("Skipping download for schema upgrade as no data available");
kony.sync.onDownloadCompletion(false);
return;
}
function downloadNextBatch(tx) {
sync.log.trace("Entering downloadNextBatch");
var morechanges = serverChanges.d.__sync.moreChangesAvailable;
var serverblob = serverChanges.d.__sync.serverblob;
var pendingbatches = serverChanges.d.__sync.pendingBatches;
kony.sync.currentSyncReturnParams[kony.sync.lastSyncTimestamp] = serverblob;
if(kony.sync.isApplyChangesSync()){
if(kony.sync.applyChanges(tx, kony.sync.currentScope, serverChanges)===false){
isError = true;
return;
}
if(kony.sync.postApplyChanges(tx,serverblob, morechanges, pendingbatches)===false){
isError = true;
return;
}
}else{
kony.sync.applyChangesAsync(tx, kony.sync.currentScope, serverChanges, serverblob, morechanges);
}
}
function downloadCompleted() {
sync.log.trace("Entering downloadCompleted");
if(kony.sync.globalIsDownloadStarted){
//This means that download has failed and variable is reset;
return;
}
var endTime = new Date();
var diff = endTime.getTime() - startTime.getTime();
sync.log.debug("Time Taken for Batch Insertion Download : " + diff);
kony.sync.batchInsertionTimer = kony.sync.batchInsertionTimer + diff;
var params = {};
params.pending_batches = kony.sync.tonumber(kony.sync.syncPendingBatchesNo);
params.serverinsertcount = "Server Insert Count :" + kony.sync.serverInsertCount;
params.serverupdatecount = "Server Update Count :" + kony.sync.serverUpdateCount;
params.serverinsertackcount = "Server Insert Ack Count :" + kony.sync.serverInsertAckCount;
params.serverupdateackcount = "Server Update Ack Count :" + kony.sync.serverUpdateAckCount;
sync.log.debug("@@@@@@" + params);
kony.table.insert(kony.sync.currentSyncLog, params);
sync.log.debug(kony.sync.serverInsertCount);
if(kony.sync.isSyncStopped){
sync.log.debug("sync stopped in downloadCompleted");
kony.sync.stopSyncSession();
return;
}
var batchcontext = {};
batchcontext[kony.sync.numberOfRowsDownloaded] = kony.sync.serverInsertCount + kony.sync.serverUpdateCount + kony.sync.serverDeleteCount;
batchcontext[kony.sync.numberOfRowsInserted] = kony.sync.serverInsertCount;
batchcontext[kony.sync.numberOfRowsUpdated] = kony.sync.serverUpdateCount;
batchcontext[kony.sync.numberOfRowsDeleted] = kony.sync.serverDeleteCount;
batchcontext[kony.sync.numberOfRowsFailedtoUpload] = kony.sync.serverFailedCount;
batchcontext[kony.sync.failedRowInfo] = kony.sync.uploadSummary;
batchcontext[kony.sync.objectLevelInfo] = kony.sync.objectLevelInfoMap;
kony.sync.objectLevelInfoMap = {};
if ((kony.sync.currentScope[kony.sync.syncStrategy] !== kony.sync.syncStrategy_OTA)) {
batchcontext[kony.sync.numberOfRowsAcknowledged] = kony.sync.serverInsertAckCount + kony.sync.serverUpdateAckCount + kony.sync.serverDeleteAckCount;
batchcontext[kony.sync.numberOfRowsInsertedAck] = kony.sync.serverInsertAckCount;
batchcontext[kony.sync.numberOfRowsUpdatedAck] = kony.sync.serverUpdateAckCount;
batchcontext[kony.sync.numberOfRowsDeletedAck] = kony.sync.serverDeleteAckCount;
}
batchcontext[kony.sync.pendingBatches] = kony.sync.tonumber(kony.sync.syncPendingBatchesNo);
kony.sync.currentSyncReturnParams[kony.sync.batchContext] = batchcontext;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onBatchProcessingSuccess], kony.sync.currentSyncReturnParams);
if ((kony.sync.moreChangesAvailable)) {
kony.sync.syncDownloadChanges(kony.sync.currentScope[kony.sync.scopeName], kony.sync.currentScope[kony.sync.scopeDataSource], kony.sync.onDownloadCompletion);
} else {
kony.sync.printScopeLog(kony.sync.currentSyncLog);
delete kony.sync.currentSyncReturnParams[kony.sync.batchContext];
//clearing sync order and then deleting records after upload
if (kony.sync.isUploadErrorPolicyCOE(kony.sync.currentScope)) {
if(kony.sync.currentScope[kony.sync.syncStrategy] !== kony.sync.syncStrategy_OTA ) {
removeAfterUpload(0);
} else {
kony.sync.updateSyncOrderForScope(removeAfterUpload);
}
} else {
removeAfterUpload(0);
}
}
}
//wrapper for removeafterupload
function removeAfterUpload(code) {
sync.log.trace("Entering removeAfterUpload");
if(code===0){
kony.sync.deleteRecordsAfterUpload(postDownloadProcessing);
}else{
//statement error
if(code===kony.sync.errorCodeSQLStatement){
kony.sync.downloadFailed(true);
}
//transaction error
else{
kony.sync.downloadFailed(false);
}
}
}
//This function should be called after finishing all post download tasks like removeafterupload
function postDownloadProcessing(code) {
sync.log.trace("Entering postDownloadProcessing");
if(kony.sync.isSyncStopped){
sync.log.debug("Stopped in postDownloadProcessing");
kony.sync.stopSyncSession();
return;
}
if(code===0){
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onDownloadSuccess], kony.sync.currentSyncReturnParams);
/*if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncScopeFilter)) {
kony.sync.syncDownloadbyFilter(kony.sync.currentSyncScopeFilterIndex + 1);
} else {*/
kony.sync.globalIsDownloadStarted = true;
kony.sync.onDownloadCompletion(false, null);
//}
}
else{
//statement error
if(code===kony.sync.errorCodeSQLStatement){
kony.sync.downloadFailed(true);
}
//transaction error
else{
kony.sync.downloadFailed(false);
}
}
}
//Used for upload after delete in persistence strategey , Adding all the merged records in delete queue
function recsToBeDeletedAfterUploadForPersistentStrategy(serverChanges) {
var scopename = kony.sync.currentScope[kony.sync.scopeName];
if(!kony.sync.isNullOrUndefined(serverChanges.d) && !kony.sync.isNullOrUndefined(serverChanges.d.results)){
for(var i in serverChanges.d.results){
var tablename = serverChanges.d.results[i].__metadata.type;
if(kony.sync.checkForDeleteAfterUpload(tablename,scopename) === true
&& !kony.sync.isNullOrUndefined(serverChanges.d.results[i][kony.sync.mergedWithEIS])
&& serverChanges.d.results[i][kony.sync.mergedWithEIS] === "1") {
kony.sync.PersisChangestobeDeleted.push(serverChanges.d.results[i]);
}
}
sync.log.info("Changes to be deleted after upload", kony.sync.PersisChangestobeDeleted);
}
}
function downloadcallback(serverChangesResult) {
sync.log.trace("Entering downloadcallback");
var endTime = new Date();
var diff = endTime.getTime() - startTime.getTime();
sync.log.debug("Time Taken for Network Batch Download : " + diff);
kony.sync.batchDownloadTimer = kony.sync.batchDownloadTimer + diff;
serverChanges = serverChangesResult;
sync.log.info("ServerChanges:", serverChanges);
if(!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.removeAfterUpload])
&& kony.sync.currentScope[kony.sync.syncStrategy] !== kony.sync.syncStrategy_OTA ) {
recsToBeDeletedAfterUploadForPersistentStrategy(serverChanges);
}
if (!kony.sync.isNullOrUndefined(serverChanges.opstatus) && serverChanges.opstatus !== 0) {
kony.sync.globalIsDownloadStarted = true;
if(kony.sync.isSyncStopped){
sync.log.debug("Sync stopped in downloadcallback in opstatus check");
kony.sync.stopSyncSession();
return;
}
if (!kony.sync.isNullOrUndefined(serverChanges.d)) {
kony.sync.onDownloadCompletion(true, kony.sync.getServerError(serverChanges.d, "download"));
} else {
kony.sync.onDownloadCompletion(true, kony.sync.getServerError(serverChanges));
}
return;
}else if(kony.sync.isNullOrUndefined(serverChanges.d)){
if(kony.sync.isSyncStopped){
sync.log.debug("Sync stopped in downloadcallback in serverchanges.d check");
kony.sync.stopSyncSession();
return;
}
kony.sync.onDownloadCompletion(true, kony.sync.getServerError(serverChanges));
return;
}
kony.sync.currentSyncReturnParams[kony.sync.serverDetails] = {};
kony.sync.currentSyncReturnParams[kony.sync.serverDetails][kony.sync.hostName] = kony.sync.getServerDetailsHostName(serverChanges);
kony.sync.currentSyncReturnParams[kony.sync.serverDetails][kony.sync.ipAddress] = kony.sync.getServerDetailsIpAddress(serverChanges);
if ((serverChanges.d.error === "true")) {
kony.sync.globalIsDownloadStarted = true;
var hasResults = serverChanges.d.hasOwnProperty("results");
if(hasResults && (serverChanges.d["results"].length > 0)) {
applyDownloadBatchChangesToDBonError();
} else {
if(kony.sync.isSyncStopped){
sync.log.debug("Sync stopped in downloadcallback in serverchanges.d.error true");
kony.sync.stopSyncSession();
return;
}
kony.sync.onDownloadCompletion(true, kony.sync.getServerError(serverChanges.d, "download"));
}
return;
}
//If has uploadErrors for persistentSync incase of AbortOnError Sync Strategy
if(hasUploadErrors(serverChanges)) {
kony.sync.globalIsDownloadStarted = true;
var hasResults = serverChanges.d.hasOwnProperty("results");
if(hasResults && (serverChanges.d["results"].length > 0)) {
applyDownloadBatchChangesToDBonError();
//Update Sync Order for failed records
updateVersionNumberOnPersistentDownload();
} else {
var uploadErrorsInfoMap = getUploadErrorsInfoMap(serverChanges);
//Update Sync Order for failed records
updateVersionNumberOnPersistentDownload();
kony.sync.onDownloadCompletion(true, uploadErrorsInfoMap);
}
return;
}
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, kony.sync.syncFailed);
if(dbconnection===null){
return;
}
if(kony.sync.isApplyChangesSync()){
kony.db.transaction(dbconnection, downloadNextBatch, downloadNextBatchFailed, downloadCompleted);
}else{
kony.db.transaction(dbconnection, downloadNextBatch, downloadNextBatchFailed, downloadCompleted,{isCommitTransaction:false});
}
}
function hasUploadErrors(serverChanges) {
if( !kony.sync.isNullOrUndefined(serverChanges) && !kony.sync.isNullOrUndefined(serverChanges.d) && (serverChanges.d.error === "false")
&& !kony.sync.isNullOrUndefined(serverChanges.d.__sync) && !kony.sync.isNullOrUndefined(serverChanges.d.__sync.UploadErrors)) {
return true;
}
return false;
}
function getUploadErrorsInfoMap(serverChanges) {
var failedRowsInfoMap = {};
if( kony.sync.isNullOrUndefined(serverChanges) || kony.sync.isNullOrUndefined(serverChanges.d) ||
kony.sync.isNullOrUndefined(serverChanges.d.__sync) || kony.sync.isNullOrUndefined(serverChanges.d.__sync.UploadErrors)) {
return failedRowsInfoMap;
}
var errors = serverChanges.d.__sync.UploadErrors;
var failedRowsInfo = [];
var errorMap = null;
var serverDetails = {};
for(var i=0; i< errors.length; i++) {
errorMap = errors[i];
for(var key in errorMap) {
var contextMap = errorMap[key];
failedRowsInfo.push( {
key:contextMap.primaryKeys,
type:contextMap.type,
errorMessage:contextMap.errorMessage
});
}
}
failedRowsInfoMap[kony.sync.failedRowInfo] = failedRowsInfo;
if (!kony.sync.isNullOrUndefined(serverChanges.d.server)) {
serverDetails[kony.sync.hostName] = serverChanges.d.server.hostName;
serverDetails[kony.sync.ipAddress] = serverChanges.d.server.ipAddress;
}
failedRowsInfoMap[kony.sync.serverDetails] = serverDetails;
return failedRowsInfoMap;
}
function updateVersionNumberOnPersistentDownload() {
sync.log.trace("Entering updateVersionNumberOnPersistentDownload ");
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var scopename = kony.sync.currentScope[kony.sync.scopeName];
var sql = null;
var params = null;
var query = null;
var query_compile = null;
kony.sync.getConnection(dbname, dbname, transactionCallback, successCallback, failureCallback);
function transactionCallback(tx) {
var versionNo = kony.sync.getseqnumber(tx, scopename);
if (!kony.sync.isNullOrUndefined(kony.sync.currentScope.ScopeTables)) {
for (var i = 0; i < kony.sync.currentScope.ScopeTables.length; i++) {
var syncTable = kony.sync.currentScope.ScopeTables[i];
if (kony.sync.isNullOrUndefined(syncTable)) {
continue;
}
var tbname = syncTable.Name;
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tbname + kony.sync.historyTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if (resultSet !== false) {
var num_records = resultSet.rows.length;
if (num_records > 0) {
var versionMap = {};
versionMap[kony.sync.historyTableSyncVersionColumn] = versionNo.versionnumber;
var whereClause = [];
kony.table.insert(whereClause, {
key: kony.sync.historyTableChangeTypeColumn,
value: "9%",
optype: "NOT LIKE"
});
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tbname + kony.sync.historyTableName);
kony.sync.qb_set(query, versionMap);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if (kony.sync.executeSql(tx, sql, params) === false) {
return;
}
}
} else {
return;
}
}
}
}
function failureCallback() {
sync.log.error(" Failed to update version number for failed rows on persistent download ");
}
function successCallback() {
sync.log.trace(" Updated version number for failed rows on persistent download ");
}
}
function applyDownloadBatchChangesToDBonError() {
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, kony.sync.syncFailed);
if(dbconnection===null){
return;
}
if(kony.sync.globalIsDownloadStarted) {
if(kony.sync.isApplyChangesSync()) {
if(hasUploadErrors(serverChanges)) {
kony.db.transaction(dbconnection, downloadNextBatch, currentBatchDownloadError, kony.sync.onDownloadCompletion(true, getUploadErrorsInfoMap(serverChanges)));
}else {
kony.db.transaction(dbconnection, downloadNextBatch, currentBatchDownloadError, kony.sync.onDownloadCompletion(true, kony.sync.getServerError(serverChanges.d, "download")));
}
} else {
if(hasUploadErrors(serverChanges)) {
kony.db.transaction(dbconnection, downloadNextBatch, currentBatchDownloadError, kony.sync.onDownloadCompletion(true, getUploadErrorsInfoMap(serverChanges)),{isCommitTransaction:false});
} else {
kony.db.transaction(dbconnection, downloadNextBatch, currentBatchDownloadError, kony.sync.onDownloadCompletion(true, kony.sync.getServerError(serverChanges.d, "download")),{isCommitTransaction:false});
}
}
}
}
function currentBatchDownloadError() {
var serverError = null;
if(!kony.sync.isNullOrUndefined(serverChanges.d)) {
serverError = kony.sync.getServerError(serverChanges.d, "download");
}
var errorTable = kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null);
if(serverError === null) {
kony.sync.onDownloadCompletion(true, errorTable);
return;
}
if(serverError && serverError.errorMessage && errorTable && errorTable.errorMessage) {
serverError.errorMessage = serverError.errorMessage + " and " + errorTable.errorMessage;
}
kony.sync.onDownloadCompletion(true, serverError);
}
function downloadNextBatchFailed(){
sync.log.trace("Entering downloadNextBatchFailed");
kony.sync.downloadFailed(isError);
}
function scopeSettingsCallback(isInitialized) {
sync.log.trace("Entering scopeSettingsCallback");
kony.sync.konyDownloadChanges(lastsynctime, null, downloadcallback, isInitialized, upgradeSchemaLastSyncTime);
}
kony.sync.isScopeInitialized(kony.sync.currentScope[kony.sync.scopeName], kony.sync.currentScope[kony.sync.scopeDataSource], scopeSettingsCallback);
};
kony.sync.downloadFailed = function (dbError) {
sync.log.trace("Entering kony.sync.downloadFailed ");
kony.sync.gSyncFailed = true;
kony.sync.globalIsDownloadStarted = true;
//kony.sync.onDownloadCompletion(true, JSON.stringify(connection));
sync.log.error("Scope Download Failed");
if (!dbError) {
kony.sync.onDownloadCompletion(true, kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
}
else{
kony.sync.onDownloadCompletion(true, kony.sync.errorObject);
kony.sync.errorObject = null;
}
};
kony.sync.applyChanges = function (tx, currentScope, serverChanges) {
sync.log.trace("Entering kony.sync.applyChanges ");
sync.log.info("Applying Changes from Server................... ----------->");
var results = serverChanges.d.results;
if (!kony.sync.isNullOrUndefined(results)) {
return kony.sync.applyChangesToDB({
"tx" : tx,
"currentScope" : currentScope,
"results" : results,
"startposition" : 0,
"endposition" : results.length
});
}
};
kony.sync.postApplyChanges = function (tx, serverblob, moreChangesAvailable, pendingBatches) {
sync.log.trace("Entering kony.sync.postApplyChanges ");
if(kony.sync.clearChunkMetaData(tx, kony.sync.currentScope[kony.sync.scopeName])===false){
return false;
}
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncScopeFilter)) {
var scopejsonfilter = {
"d" : kony.sync.currentSyncScopeFilter
};
var filtervaluejson = JSON.stringify(scopejsonfilter);
if(kony.sync.setLastSyncTimeFilter(tx, kony.sync.currentScope[kony.sync.scopeName], filtervaluejson, null, serverblob)===false){
return false;
}
} else {
if(kony.sync.setLastSyncTime(tx, kony.sync.currentScope[kony.sync.scopeName], null, serverblob)===false){
return false;
}
}
//shrink memory execution
kony.db.executeSql(tx, "PRAGMA shrink_memory");
if (!kony.sync.isNullOrUndefined(moreChangesAvailable)) {
var temp = moreChangesAvailable;
temp = temp + "";
temp = temp.toLowerCase();
if ((temp === "true")) {
//Enable below code if PendingBatches is implemented.
if (!kony.sync.isNullOrUndefined(pendingBatches)) {
kony.sync.syncPendingBatchesNo = pendingBatches;
}
kony.sync.moreChangesAvailable = true;
} else {
kony.sync.moreChangesAvailable = false;
kony.sync.syncPendingBatchesNo = 0;
}
} else {
kony.sync.moreChangesAvailable = false;
}
sync.log.info("more changes available " + kony.sync.moreChangesAvailable);
if (!kony.sync.moreChangesAvailable) {
//After Every successful Scope download completion we will check and update the Scope Settings to make that scope Initialized;
if(kony.sync.updateScopeSettings(tx, kony.sync.currentScope[kony.sync.scopeName])===false){
return false;
}
//After Every successful Scope download completion we will check if this download was for schema upgrade and mark it complete
if(kony.sync.setSchemaUpgradeDownloadComplete(tx, kony.sync.currentScope[kony.sync.scopeName])===false){
return false;
}
}
};
kony.sync.applyChangesAsync = function (tx, currentScope, serverChanges, serverblob, morechanges) {
sync.log.trace("Entering kony.sync.applyChangesAsync ");
sync.log.info("Applying Changes from Server................... ----------->");
var results = serverChanges.d.results;
var bbBatchSize = kony.sync.getAsyncDownloadBatchSize();
var lastbatch = results.length % bbBatchSize;
var noofloops = (results.length - lastbatch) / bbBatchSize;
var context = {
"tx" : tx,
counter : 0,
"currentScope" : currentScope,
"results" : results,
"noofloops" : noofloops,
"lastbatch" : lastbatch,
"serverblob" : serverblob,
"morechanges" : morechanges
};
sync.log.debug("sending context");
kony.api.executeAsync(kony.sync.applyChangesToDBAsync, context);
};
kony.sync.applyChangesToDBAsync = function (context) {
sync.log.trace("Entering kony.sync.applyChangesToDBAsync ");
sync.log.debug("point ******b : ", context);
if (context.counter >= context.noofloops) {
if (context.lastbatch > 0) {
context.startposition = context.counter * kony.sync.getAsyncDownloadBatchSize();
context.endposition = context.startposition + context.lastbatch;
kony.sync.applyChangesToDB(context);
context.counter = context.counter + 1;
context.lastbatch = 0;
kony.api.executeAsync(kony.sync.applyChangesToDBAsync, context);
} else {
kony.sync.postApplyChanges(context.tx, context.serverblob, context.morechanges);
kony.db.commitTransaction(context.tx);
}
} else {
context.startposition = context.counter * kony.sync.getAsyncDownloadBatchSize();
context.endposition = context.startposition + kony.sync.getAsyncDownloadBatchSize();
kony.sync.applyChangesToDB(context);
context.counter = context.counter + 1;
sync.log.debug("point ******c : ", context);
kony.api.executeAsync(kony.sync.applyChangesToDBAsync, context);
}
};
kony.sync.updateSyncVerisonNumberForFailedRow = function (tx, tablename, pkKey, pkValue) {
sync.log.trace("Entering kony.sync.updateSyncVerisonNumberForFailedRow ");
var versionNo = kony.sync.getseqnumber(tx, kony.sync.currentScope[kony.sync.scopeName]);
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename + kony.sync.historyTableName);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if (resultSet !== false) {
if(resultSet.rows.length > 0) {
var versionMap = {};
versionMap[kony.sync.historyTableSyncVersionColumn] = versionNo.versionnumber;
var whereClause = [];
kony.table.insert(whereClause, {
key: kony.sync.historyTableChangeTypeColumn,
value: "9%",
optype: "NOT LIKE"
});
kony.table.insert(whereClause, {
key:pkKey,
value:pkValue
});
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tablename + kony.sync.historyTableName);
kony.sync.qb_set(query, versionMap);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if (kony.sync.executeSql(tx, sql, params) === false) {
return;
}
}
}
};
kony.sync.addBinaryRecordsToDownload = function(tx, tablename, pkColumns) {
function errorCallback(err) {
kony.sync.errorObject = err;
kony.sync.downloadFailed(false);
}
//from the table fetch all the records having NULL for blobref columns with "always" policy.
var alwaysColumns = kony.sync.getBinaryColumnsByPolicy(tablename, kony.sync.always);
//var pkColumns = kony.sync.currentScope.syncTableDic[tablename].Pk_Columns;
var resultSet;
for(var k in alwaysColumns) {
sync.log.trace("kony.sync.addBinaryRecordsToDownload - alwaysColumn is "+alwaysColumns[k]);
var konysyncBinaryMetaColumn = kony.sync.binaryMetaColumnPrefix + alwaysColumns[k];
var whereClause = [{
key : konysyncBinaryMetaColumn,
value : kony.sync.blobRefNotDefined
}, {
key : alwaysColumns[k],
value : kony.sync.blobRefNotDefined,
optype : "NOT_EQ"
}
];
resultSet = kony.sync.queryTable(tx, tablename, pkColumns, whereClause);
//parse through the result set, create blob record for each record and update its reference at parent table.
if(resultSet) {
sync.log.trace("kony.sync.addBinaryRecordsToDownload - Number of always records to be added to the download queue "+resultSet.rows.length);
for(var l = 0;l < resultSet.rows.length; l++) {
var rowItem = kony.db.sqlResultsetRowItem(tx, resultSet, l);
//create a record in blobStoreManager.
kony.sync.blobManager.triggerDownload(tx, tablename, alwaysColumns[k], rowItem ,errorCallback);
//increment total number of download jobs..
kony.sync.incrementTotalJobs(true);
}
} else {
sync.log.error("Error in querying table "+tablename);
return;
}
}
//for ifRecordValue columns...
var ifRecordValueColumns = kony.sync.getBinaryColumnsByPolicy(tablename, kony.sync.ifRecordValue);
for(var k in ifRecordValueColumns) {
//fetch the synctodevicefield for the column.
var syncToDeviceColumn = kony.sync.getSyncToDeviceField(tablename, ifRecordValueColumns[k]);
if(syncToDeviceColumn) {
sync.log.trace("kony.sync.addBinaryRecordsToDownload - alwaysColumn is "+ifRecordValueColumns[k]);
var konysyncBinaryMetaColumn = kony.sync.binaryMetaColumnPrefix + ifRecordValueColumns[k];
var whereClause = [{
key : konysyncBinaryMetaColumn,
value : kony.sync.blobRefNotDefined
}, {
key : ifRecordValueColumns[k],
value : kony.sync.blobRefNotDefined,
optype : "NOT_EQ"
}, {
key : syncToDeviceColumn,
value : "true"
}
];
resultSet = kony.sync.queryTable(tx, tablename, pkColumns, whereClause);
if(resultSet) {
sync.log.trace("kony.sync.addBinaryRecordsToDownload - Number of ifrecordvalue records to be added to the download queue "+resultSet.rows.length);
for(var l = 0;l < resultSet.rows.length; l++) {
var rowItem = kony.db.sqlResultsetRowItem(tx, resultSet, l);
//create a record in blobStoreManager.
kony.sync.blobManager.triggerDownload(tx, tablename, ifRecordValueColumns[k], rowItem ,errorCallback);
//increment total number of download jobs..
kony.sync.incrementTotalJobs(true);
}
} else {
sync.log.error("Error in querying table "+tablename);
return;
}
}
}
return true;
};
kony.sync.applyChangesToBlobStoreDB = function(tx, tablename, row, blobMap, changeType, pks) {
function errorCallback(err) {
kony.sync.errorObject = err;
kony.sync.downloadFailed(false);
}
var blobStoreIndices = {};
var blobId;
//adding the always, ifrecordvalue policy binaries to download queue..
var binaryColumns = kony.sync.getBinaryColumns(tablename);
if(binaryColumns) {
for(var k in binaryColumns) {
switch(kony.sync.getDownloadPolicy(tablename, binaryColumns[k])) {
case kony.sync.always:
blobId = kony.sync.blobManager.createBlobRecord(tx, tablename, binaryColumns[k], errorCallback);
if(!blobId){
return;
}
blobStoreIndices[kony.sync.binaryMetaColumnPrefix + binaryColumns[k]] = blobId;
//increment total number of download jobs..
kony.sync.incrementTotalJobs(true);
break;
case kony.sync.ifRecordValue:
var syncToDeviceField = kony.sync.getSyncToDeviceField(tablename, binaryColumns[k]);
if(syncToDeviceField && row[syncToDeviceField] === "true") {
blobId = kony.sync.blobManager.createBlobRecord(tx, tablename, binaryColumns[k], errorCallback);
if(!blobId){
return;
}
blobStoreIndices[kony.sync.binaryMetaColumnPrefix + binaryColumns[k]] = blobId;
//increment total number of download jobs..
kony.sync.incrementTotalJobs(true);
}
break;
}
binary.util.notifyToPrepareJobs();
}
}
sync.log.trace("inserting inline base64 data in kony blobstoremanager..");
if(changeType === "insert") {
if (Object.keys(blobMap).length > 0) {
var inlineBlobStoreIndices = kony.sync.blobstore_insert(tx, tablename, blobMap, errorCallback);
if (inlineBlobStoreIndices) {
for (var blobKey in inlineBlobStoreIndices) {
blobStoreIndices[blobKey] = inlineBlobStoreIndices[blobKey];
}
} else {
sync.log.error("applyChangesToDb - error in inserting inline base64 data for table " + tablename);
return false;
}
}
} else if(changeType === "update") {
if(Object.keys(blobMap).length > 0) {
var inlineBlobStoreIndices = kony.sync.blobstore_update(tx, tablename, blobMap, pks, false, errorCallback);
if (inlineBlobStoreIndices) {
for (var blobKey in inlineBlobStoreIndices) {
blobStoreIndices[blobKey] = inlineBlobStoreIndices[blobKey];
}
} else {
sync.log.error("applyChangesToDb - error in updating inline base64 data for table " + tablename);
return false;
}
}
}
if(Object.keys(blobStoreIndices).length > 0) {
var pkColumns = kony.sync.currentScope.syncTableDic[tablename].Pk_Columns;
sync.log.trace("updating blobref values in parent table.. " + JSON.stringify(blobStoreIndices));
//update the parent table with blob references.
var wcs = [];
for (var key in pkColumns) {
var wc = {};
wc.key = pkColumns[key];
wc.value = row[pkColumns[key]];
wcs.push(wc);
}
var resultset = kony.sync.blobManager.updateParentWithBlobReference(tx, tablename, blobStoreIndices, wcs, errorCallback);
if (resultset === false || kony.sync.isNullOrUndefined(resultset)) {
return false;
}
}
//invoke the status update notifier..
kony.sync.invokeBinaryNotifiers(true);
};
kony.sync.applyChangesToDB = function (context) {
sync.log.trace("Entering kony.sync.applyChangesToDB ");
var tx = context.tx;
var results = context.results;
var startposition = context.startposition;
var endposition = context.endposition;
var newVersion = kony.sync.getseqnumber(tx, kony.sync.currentScope.ScopeName);
var newVersionNo = newVersion.versionnumber;
var j = null;
var pk = null;
var query_compile = null;
var query = null;
var sql = null;
var params = null;
var resultset = null;
if(kony.sync.isNullOrUndefined(results)){
return;
}
//before updating changes to db, addBinaryRecordsToDownload.
sync.log.trace("kony.sync.applyChangesToDb - addBinaryRecordsToDownload.");
var syncscopes = konysyncClientSyncConfig.ArrayOfSyncScope;
if(!kony.sync.isNullOrUndefined(syncscopes)){
for (var scopeCount = 0; scopeCount < syncscopes.length; scopeCount++) {
var scope = syncscopes[scopeCount];
sync.log.trace("kony.sync.applyChangesToDb - current scope "+scope.ScopeName);
if(!kony.sync.isNullOrUndefined(scope.ScopeTables)) {
for (var tableCount = 0; tableCount < scope.ScopeTables.length; tableCount++) {
var syncTable = scope.ScopeTables[tableCount];
var tablename = syncTable.Name;
sync.log.trace("kony.sync.applyChangesToDb - addBinaryRecordsToDownload for "+tablename);
if(tablename) {
var addingPendingBinariesForDownload = kony.sync.addBinaryRecordsToDownload(tx, tablename, syncTable.Pk_Columns);
if(!addingPendingBinariesForDownload) {
sync.log.trace("kony.sync.applyChangesToDb - addBinaryRecordsToDownload failed..");
return false;
}
}
}
}
}
}
for (var i = startposition; i < endposition; i++) {
var row = results[i];
var tablename = row.__metadata.type;
if (kony.sync.isNullOrUndefined(kony.sync.objectLevelInfoMap[tablename])) {
kony.sync.objectLevelInfoMap[tablename] = {};
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDownloaded] = 0;
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] = 0;
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] = 0;
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDeleted] = 0;
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInsertedAck] = 0;
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdatedAck] = 0;
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDeletedAck] = 0;
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsAcknowledged] = 0;
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsFailedtoUpload] = 0;
}
if (kony.sync.objectLevelInfoMap[tablename][kony.sync.reconciledKeysKey] == null){
kony.sync.objectLevelInfoMap[tablename][kony.sync.reconciledKeysKey] = [];
}
var changeType = row.__metadata.changeType;
var values = [];
var pkColumns = kony.sync.currentScope.syncTableDic[tablename].Pk_Columns;
var pkwcs = [];
var pkset = null;
var pksetwcs = [];
var blobMap = {};
//var currentversion = kony.sync.getCurrentVersionNumber(tablename);
var MergedWithEIS = row[kony.sync.mergedWithEIS];
var versionNumber = row[kony.sync.mainTableSyncVersionColumn];
versionNumber = kony.sync.tonumber(versionNumber);
sync.log.trace("row is are "+JSON.stringify(row));
if(MergedWithEIS !== "1" && MergedWithEIS !== "0") {
if(!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tablename])){
var binaryDataColumns = kony.sync.scopes.syncScopeBlobInfoMap[tablename][kony.sync.columns];
sync.log.trace("values are "+JSON.stringify(values));
var binaryColumns = kony.sync.scopes.syncScopeBlobInfoMap[tablename][kony.sync.columns];
for(var j=0; j<binaryColumns.length; j++){
//getDownloadPolicy of the column
var downloadPolicy = kony.sync.getDownloadPolicy(tablename, binaryColumns[j]);
if(downloadPolicy == kony.sync.inline) {
if(!kony.sync.isNullOrUndefined(row[binaryColumns[j]]) && row[binaryColumns[j]].trim().length > 0)
blobMap[binaryColumns[j]] = row[binaryColumns[j]];
delete row[binaryColumns[j]];
}
}
}
}
sync.log.trace("after applyDB blobstore "+JSON.stringify(row));
if (kony.sync.isNullOrUndefined(kony.sync.queryStore[tablename + "purgeInsert"])) {
values = kony.sync.removeprovisioncolumns(row, kony.sync.currentScope.syncTableDic[tablename].Columns, true);
} else {
values = kony.sync.removeprovisioncolumns(row, kony.sync.currentScope.syncTableDic[tablename].Columns, false);
}
if (MergedWithEIS !== "1" && MergedWithEIS !== "0") {
if ((changeType === "update")) {
//do purge logic here.
var result = null;
//#ifdef KONYSYNC_ANDROID
result = kony.sync.purgeInsertEx(tx, tablename, values, false);
sync.log.trace("result is "+JSON.stringify(result));
if (result === false)
//#else
result = kony.sync.purgeInsertEx(tx, tablename, values, true);
if (result === false){
return false;
}
if (result !== false && result.rowsAffected === 0)
//#endif
{
sync.log.trace("Change type is update in sync session- insert failed.. ");
var _upgradeContext = kony.sync.schemaUpgradeContext;
var _upgradeContextJSON = null;
if(!kony.sync.isNullOrUndefined(_upgradeContext)){
_upgradeContextJSON = JSON.parse(_upgradeContext);
}
//add the null columns update scenario
if(kony.sync.isNullOrUndefined(_upgradeContextJSON) || kony.sync.isNullOrUndefined(_upgradeContextJSON[tablename])) {
var columnsDefinedForTable = kony.sync.removeBinaryMetaColumns(tablename, kony.sync.currentScope.syncTableDic[tablename].Columns);
values = kony.sync.removeprovisioncolumns(row, columnsDefinedForTable, true, false);
}
else{
//DSC scenario
var columnsDefinedForTable = kony.sync.removeBinaryMetaColumns(tablename, kony.sync.currentScope.syncTableDic[tablename].Columns);
values = kony.sync.removeprovisioncolumns(row, columnsDefinedForTable, true, true);
}
if(!kony.sync.isNullOrUndefined(pkColumns)){
for (j = 0; j < pkColumns.length; j++) {
pk = pkColumns[j];
if (!kony.sync.isNullOrUndefined(row[kony.sync.clientPKPrefix + pk])) {
//pkset = pkset.." "..pk.."='"..row[pk].."'";
if (kony.sync.isNullOrUndefined(pkset)) {
pkset = [];
}
kony.table.insert(pkwcs, {
key : pk,
value : row[kony.sync.clientPKPrefix + pk]
});
pkset[pk] = row[pk];
kony.table.insert(pksetwcs, {
key : pk,
value : row[pk]
});
} else {
kony.table.insert(pkwcs, {
key : pk,
value : row[pk]
});
kony.table.insert(pksetwcs, {
key : pk,
value : row[pk]
});
}
}
}
kony.table.insert(pkwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : "nil",
optype : "EQ",
comptype : "OR",
openbrace : true
});
kony.table.insert(pkwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : -1,
optype : "EQ",
comptype : "OR",
closebrace : true
});
/* kony.table.insert(pkwcs, {
key: kony.sync.mainTableSyncVersionColumn,
value: currentversion,
optype : "EQ"
});*/
var originalwcs = kony.sync.CreateCopy(pksetwcs);
var hasInstanceInHistoryTable = kony.sync.checkForHistoryInstance(tx, tablename, values, originalwcs);
//update the blob store manager..
function updateBlobStoreManager(pks){
kony.sync.applyChangesToBlobStoreDB(tx, tablename, row, blobMap, "update", pks);
}
//for binary columns, delete the existing entries.
function deleteOnDemandBinaryEntries() {
sync.log.trace("entering deleteOnDemandBinaryEntries..");
function updateBlobErrorCallback(err) {
kony.sync.errorObject = err;
kony.sync.downloadFailed(false);
}
var binaryColumns = kony.sync.getBinaryColumns(tablename);
if(binaryColumns) {
sync.log.trace("onDemandColumns for " + tablename + " are " + JSON.stringify(binaryColumns));
for (var j = 0; j < binaryColumns.length; j++) {
if (kony.sync.getDownloadPolicy(tablename, binaryColumns[j]) !== kony.sync.inline) {
var pkColumns = kony.sync.currentScope.syncTableDic[tablename].Pk_Columns;
var pkTable = {};
for (var pk in pkColumns) {
pkTable[pkColumns[pk]] = row[pkColumns[pk]];
}
//get the blobrefs of ondemand columns and delete that entries in blob store manager.
var blobRef = kony.sync.getBlobRef(tx, tablename, binaryColumns[j], pkTable, updateBlobErrorCallback);
sync.log.trace("blobRef for the data is " + blobRef + "for pkTable " + JSON.stringify(pkTable) + "in tablename " + tablename);
if (blobRef !== kony.sync.blobRefNotFound && blobRef !== kony.sync.blobRefNotDefined) {
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobRef, updateBlobErrorCallback);
//delete the record only if it is not in queue for upload.
if (blobMeta[kony.sync.blobManager.state] !== kony.sync.blobManager.UPLOAD_ACCEPTED
&& blobMeta[kony.sync.blobManager.state] !== kony.sync.blobManager.UPLOAD_IN_PROGRESS
&& blobMeta[kony.sync.blobManager.state] !== kony.sync.blobManager.UPLOAD_FAILED) {
//TODO - open item. delete the image after upload.
var isDeleteSuccessful = kony.sync.blobManager.deleteBlob(tx, blobRef, updateBlobErrorCallback);
sync.log.trace("isDeleteSuccessful uploadBlobStoreManager " + isDeleteSuccessful);
if (!isDeleteSuccessful) return false;
//update NULL in the parent table.
sync.log.trace("deleteOnDemandEntries - updating blobref column for " + binaryColumns[j] + " with NULL");
values[kony.sync.binaryMetaColumnPrefix + binaryColumns[j]] = kony.sync.blobRefNotDefined;
}
}
}
}
}
}
if( hasInstanceInHistoryTable === 0 ) {
return false;
}
if(hasInstanceInHistoryTable === false) {
//first delete the blob entries for the respective column.
deleteOnDemandBinaryEntries();
if (!kony.sync.isNullOrUndefined(pkset)) {
if(kony.sync.updateEx(tx, tablename, values, pksetwcs)===false){
return false;
} else {
//update blobstore manager ?
updateBlobStoreManager(pksetwcs);
}
} else {
if(kony.sync.updateEx(tx, tablename, values, pkwcs)===false){
return false;
} else {
//update blobstore manager ?
updateBlobStoreManager(pkwcs);
}
}
}
kony.sync.serverUpdateCount = kony.sync.serverUpdateCount + 1;
// update if the user hasn't changed the record
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] + 1;
// if(kony.sync.updateEx(tx, tablename, values, pkwcs)===false){
// return false;
// }
} else {
kony.sync.applyChangesToBlobStoreDB(tx, tablename, row, blobMap, "insert");
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] + 1;
kony.sync.serverInsertCount = kony.sync.serverInsertCount + 1;
}
}
else if ((changeType === "delete")) {
values = kony.sync.removeprovisioncolumns(row, kony.sync.currentScope.syncTableDic[tablename].Columns, true, true);
// delete the record if it hasn't been changed by the user
if(!kony.sync.isNullOrUndefined(pkColumns)){
for (j = 0; j < pkColumns.length; j++) {
pk = pkColumns[j];
if (!kony.sync.isNullOrUndefined(row[kony.sync.clientPKPrefix + pk])) {
//pkwc = pkwc.." "..pk.."='"..row["Client_"..pk].."'";
//pkset = pkset.." "..pk.."='"..row[pk].."'";
if (kony.sync.isNullOrUndefined(pkset)) {
pkset = [];
}
kony.table.insert(pkwcs, {
key : pk,
value : row[kony.sync.clientPKPrefix + pk]
});
pkset[pk] = row[pk];
kony.table.insert(pksetwcs, {
key : pk,
value : row[pk]
});
} else {
kony.table.insert(pkwcs, {
key : pk,
value : row[pk]
});
}
}
}
kony.table.insert(pkwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : "nil",
optype : "EQ",
comptype : "OR",
openbrace : true
});
kony.table.insert(pkwcs, {
key : kony.sync.mainTableChangeTypeColumn,
value : -1,
optype : "EQ",
closebrace : true
});
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDeleted] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDeleted] + 1;
kony.sync.serverDeleteCount = kony.sync.serverDeleteCount + 1;
/*WARNING: Undefined method call for kony.sync.deleteEx*/
function blobDeleteErrorCallback(err) {
kony.sync.errorObject = err;
kony.sync.downloadFailed(false);
}
//delete the blob record first.
if(!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tablename]) &&
!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tablename][kony.sync.columns])) {
var binaryDataColumns = kony.sync.scopes.syncScopeBlobInfoMap[tablename][kony.sync.columns];
//get the blobRef for the column and delete the blobrecord.
for (var blobColumn in binaryDataColumns) {
var pkColumns = kony.sync.currentScope.syncTableDic[tablename].Pk_Columns;
var pks = {};
for (var pk in pkColumns) {
pks[pkColumns[pk]] = row[pkColumns[pk]];
}
var blobRef = kony.sync.getBlobRef(tx, tablename, binaryDataColumns[blobColumn], pks, blobDeleteErrorCallback);
if (blobRef !== kony.sync.blobRefNotFound && blobRef !== kony.sync.blobRefNotDefined) {
var isDeleteSuccessful = kony.sync.blobManager.deleteBlob(tx, blobRef, blobDeleteErrorCallback);
if (!isDeleteSuccessful) return false;
}
}
}
if(kony.sync.removeEx(tx, tablename, pkwcs)===false){
return false;
}
}
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDownloaded] =
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInserted] +
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdated] +
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDeleted];
} else {
//deleting data of binary columns. but only in case of inline.
if(!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tablename]) &&
!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tablename][kony.sync.columns])){
var binaryDataColumns = kony.sync.scopes.syncScopeBlobInfoMap[tablename][kony.sync.columns];
var binaryColumn = null;
for(var k=0; k<binaryDataColumns.length; k++) {
binaryColumn = binaryDataColumns[k];
var downloadPolicy = kony.sync.getDownloadPolicy(tablename, binaryColumn);
if(downloadPolicy === kony.sync.inline) {
delete row[binaryColumn];
}
}
}
var pkTable = {};
var originalChangeType = row[kony.sync.mainTableChangeTypeColumn];
if (kony.sync.isNullOrUndefined(originalChangeType)){
originalChangeType = 1;
}
//ignore the blobref columns in removeprovisioncolumns method.
var columnsDefinedForTable = kony.sync.removeBinaryMetaColumns(tablename, kony.sync.currentScope.syncTableDic[tablename].Columns);
values = kony.sync.removeprovisioncolumns(row,columnsDefinedForTable , true, true);
//creating a map of reconciled primary keys
var keyMap = {};
var isAutoGenPkPresent = false;
if(!kony.sync.isNullOrUndefined(pkColumns)){
for (j = 0; j < pkColumns.length; j++) {
pk = pkColumns[j];
pkTable[pk] = row[pk]; //creating pk for uploadcontext
if (!kony.sync.isNullOrUndefined(row[kony.sync.clientPKPrefix + pk])) {
if (kony.sync.isNullOrUndefined(pkset)) {
pkset = [];
}
kony.table.insert(pkwcs, {
key : pk,
value : row[kony.sync.clientPKPrefix + pk]
});
pkset[pk] = row[pk];
kony.table.insert(pksetwcs, {
key : pk,
value : row[pk]
});
isAutoGenPkPresent = true;
keyMap[pk] = {newpk:row[pk],oldpk:row[kony.sync.clientPKPrefix + pk]};
} else {
kony.table.insert(pkwcs, {
key : pk,
value : row[pk]
});
kony.table.insert(pksetwcs, {
key : pk,
value : row[pk]
});
}
}
}
var originalwcs = kony.sync.CreateCopy(pksetwcs);
if(isAutoGenPkPresent){
kony.sync.objectLevelInfoMap[tablename][kony.sync.reconciledKeysKey].push(keyMap);
}
sync.log.debug("Inside MergedWithEis");
var isError = false;
var prevErrors = 0;
if (!kony.sync.isNullOrUndefined(row.__metadata.intermediateErrors)) {
prevErrors = row.__metadata.intermediateErrors.length;
}
//checking for error on continueonerror upload policy
if (!kony.sync.isNullOrUndefined(row.__metadata.errorMessage)) {
kony.sync.serverFailedCount = kony.sync.serverFailedCount + 1 + prevErrors;
kony.sync.uploadSummary.push({
key : pkTable,
type : row.__metadata.type,
errorMessage : row.__metadata.errorMessage,
errorRootCause : row.__metadata.errorRootCause,
intermediateErrors : row.__metadata.intermediateErrors
});
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsFailedtoUpload] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsFailedtoUpload] + 1 + prevErrors;
isError = true;
if( ( kony.sync.currentScope[kony.sync.syncStrategy] !== kony.sync.syncStrategy_OTA ) && kony.sync.isUploadErrorPolicyCOE(kony.sync.currentScope)) {
//Increase the version number of the failed row
kony.sync.updateSyncVerisonNumberForFailedRow(tx, tablename, pk, row[pk]);
}
}
//checking for previous errors
else if (prevErrors !== 0) {
kony.sync.uploadSummary.push({
key : pkTable,
type : row.__metadata.type,
errorMessage : null,
errorRootCause : null,
intermediateErrors : row.__metadata.intermediateErrors
});
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsFailedtoUpload] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsFailedtoUpload] + prevErrors;
kony.sync.serverFailedCount = kony.sync.serverFailedCount + prevErrors;
}
var settable = [];
//before updating the pk
//remove row from history, original and main(in case of removeafterupload) tables for COE error upload policy if success
var isRemoved = false;
isRemoved = kony.sync.clearDataForCOE(tx,kony.sync.currentScope.ScopeName, tablename, pkwcs, pksetwcs, changeType, pkset, row[kony.sync.historyTableReplaySequenceColumn], values, isError);
if(isRemoved===0){
return false;
}
if (!kony.sync.isNullOrUndefined(pkset)) {
/*update related tables foreign keys*/
//reconciliation starts here .....
//row implies record here,i inplies index of the record
var _isError = kony.sync.reconcileForeignKeyForChildren(tx,pkset,pkwcs,tablename,row,i,endposition,results);
if(_isError === 0)
return false;
}
if (isError === false) {
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsAcknowledged] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInsertedAck] + kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdatedAck] + kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDeletedAck];
//continue if removed to skip updates for same record
if (isRemoved === true) {
continue;
}
//if no error, change changetype to null in main table
settable[kony.sync.mainTableChangeTypeColumn] = "nil";
} else {
//checking for error on continueonerror upload policy and making the reconciled values consistent in child tables
if (!kony.sync.isNullOrUndefined(row.__metadata.errorMessage)){
//querying the foreignkey values from from child table and replacing in setclause to maintain reconciled values properly in child table
selectClause = [];
parentRelationshipMap = kony.sync.currentScope.syncTableDic[tablename+kony.sync.parentRelationshipMap];
//onetomany relationships from parent table
for(var tname in parentRelationshipMap){
var relationshipAttributes = parentRelationshipMap[tname];
var relationshipAttributes_length = relationshipAttributes.length;
for(var k = 0;k<relationshipAttributes_length;k++){
relationshipAttribute =relationshipAttributes[k];
var columnName = relationshipAttribute["ChildObject_Attribute"];
selectClause.push(columnName);
}
}
synctable = kony.sync.currentScope.syncTableDic[tablename];
ManyToOne = synctable.Relationships.ManyToOne;//manytone relationships
//manytoone relationships in childtable
if(!kony.sync.isNullOrUndefined(ManyToOne)){
ManyToOne_length = ManyToOne.length;
for(var k = 0;k<ManyToOne_length;k++){
if(!kony.sync.isNullOrUndefined(ManyToOne[k].RelationshipAttributes)) {
var relationshipAttributes = ManyToOne[k].RelationshipAttributes;
for (var j = 0; j < relationshipAttributes.length; j++) {
var columnName = relationshipAttributes[j].SourceObject_Attribute;
selectClause.push(columnName);
};
}
}
}
//reverse relationships in childtable
reverseRelationships = kony.sync.currentScope.reverseRelationships[tablename];
for(var k in reverseRelationships){
relationshipAttributes = reverseRelationships[k].RelationshipAttributes;
for(var j = 0;j<relationshipAttributes.length;j++){
var columnName = relationshipAttributes[j].SourceObject_Attribute;
selectClause.push(columnName);
}
}
if(selectClause.length != 0){
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query,selectClause);
kony.sync.qb_from(query,tablename);
kony.sync.qb_where(query,pkwcs);//using the whereClause already generated
query_compile =kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
resultset = kony.sync.executeSql(tx, sql,params);//need to handle error callback if required
//logic to process the resultset
if(resultset.rows.length >= 1 ){
var rowItem =kony.db.sqlResultsetRowItem(tx,resultset,0);
for(var j=0;j<selectClause.length;j++){
var columnName = selectClause[j];
values[columnName] =rowItem[columnName];
}
}
}
}
//updating history table to make relationship data consistent
var whereClause = kony.sync.CreateCopy(pkwcs);
//versionMap[kony.sync.historyTableSyncVersionColumn] = versionNo[ "versionnumber"];
kony.table.insert(whereClause, {
key: kony.sync.historyTableReplaySequenceColumn,
value: row[kony.sync.historyTableReplaySequenceColumn]
});
if(kony.sync.updateEx(tx, tablename + kony.sync.historyTableName, values, whereClause)===false){
return false;
}
//there is possibility that record is deleted by an earlier successful record, so insert it
if(changeType !== "delete"){
if (!kony.sync.isNullOrUndefined(pkset)) {
whereClause = pksetwcs;
} else {
whereClause = pkwcs;
}
values[kony.sync.mainTableChangeTypeColumn] = originalChangeType;
values[kony.sync.mainTableSyncVersionColumn] = newVersionNo + 1;
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
resultset = kony.sync.executeSql(tx, sql, params);
if (resultset !== false) {
var num_records = resultset.rows.length;
//updated if not deleted
if (num_records > 0) {
kony.sync.updateEx(tx, tablename, values, whereClause);
} else {
query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, values);
kony.sync.qb_insert(query, tablename);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
//exit incase of SQL error
return false;
}
}
}
else{
//exit incase of SQL error
return false;
}
}
continue;
}
if (!kony.sync.isNullOrUndefined(pkset)) {
/* clear dirty flag if not updated again*/
kony.table.insert(pksetwcs, {
key: kony.sync.mainTableSyncVersionColumn,
value: versionNumber,
optype : "LT_EQ",
openbrace : true,
comptype:"OR"
});
kony.table.insert(pksetwcs, {
key: kony.sync.mainTableSyncVersionColumn,
value: "nil",
closebrace : true
});
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tablename);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, pksetwcs);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
} else {
kony.table.insert(pkwcs, {
key: kony.sync.mainTableSyncVersionColumn,
value: versionNumber,
optype : "LT_EQ",
openbrace : true,
comptype :"OR"
});
kony.table.insert(pkwcs, {
key: kony.sync.mainTableSyncVersionColumn,
value: "nil",
closebrace : true
});
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tablename);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, pkwcs);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
}
if (changeType === "update") {
// clear the dirty flag
values[kony.sync.mainTableChangeTypeColumn] = "nil";
values[kony.sync.mainTableSyncVersionColumn] = "nil";
var hasInstanceInHistoryTable = kony.sync.checkForHistoryInstance(tx, tablename, values, originalwcs);
if(hasInstanceInHistoryTable === 0){
return false;
}
if(hasInstanceInHistoryTable === false){
if (!kony.sync.isNullOrUndefined(pkset)) {
if(kony.sync.updateEx(tx, tablename, values, pksetwcs)===false){
return false;
}
} else {
if(kony.sync.updateEx(tx, tablename, values, pkwcs)===false){
return false;
}
}
}
} else if(changeType === "delete"){
if(!kony.sync.isNullOrUndefined(pkset)) {
kony.table.insert(pksetwcs, {
key: kony.sync.mainTableSyncVersionColumn,
value: versionNumber
});
if(kony.sync.removeEx(tx, tablename, pksetwcs)===false){
return false;
}
} else {
kony.table.insert(pkwcs, {
key: kony.sync.mainTableSyncVersionColumn,
value: versionNumber
});
if(kony.sync.removeEx(tx, tablename, pkwcs)===false){
return false;
}
}
}
}
}
};
kony.sync.reconcileForeignKeyForChildren = function(tx,pksetwcs,pkwcs,tablename,parentRow,currentIndex,endposition,results){
//populate setClause and whereClause for the child tables
function populateMetaDataForReconciliation(_pkColumns,_row,_pkset,_pkwcs){
if(!kony.sync.isNullOrUndefined(_pkColumns)){
for (var j = 0; j < _pkColumns.length; j++) {
var pk = _pkColumns[j];
if (!kony.sync.isNullOrUndefined(_row[kony.sync.clientPKPrefix + pk])) {
kony.table.insert(_pkwcs, {
key : pk,
value : _row[kony.sync.clientPKPrefix + pk]
});
_pkset[pk] = _row[pk];
}
}
}
}
//get the childrow
var childRowFound = false;
for(var j = currentIndex+1; j < endposition;j++){
var childPkwcs = [];
var childPkset = [];
var childRow = results[j];
var childMetaData = childRow.__metadata;
var childTablename = childMetaData.type;
var childPkColumns = kony.sync.currentScope.syncTableDic[childTablename].Pk_Columns;
var parentAttributes = [];
var childAttributes = [];
//Forward Relationships(OneToMany) reconcilation
var OneToMany = kony.sync.currentScope.syncTableDic[tablename].Relationships.OneToMany;
if(!kony.sync.isNullOrUndefined(OneToMany)){
for(var k in OneToMany) {
if(OneToMany[k].TargetObject === childTablename){
var currentRelation = OneToMany[k];
//relation found add the SourceObject_Attributes and TargetObject_Attributes to corresponding arrays
var relationshipAttributes = currentRelation.RelationshipAttributes;
for(var l = 0;l<relationshipAttributes.length;l++){
parentAttributes.push(relationshipAttributes[l].SourceObject_Attribute);
childAttributes.push(relationshipAttributes[l].TargetObject_Attribute);
}
break;
}
}
}
//Forward Relationships(OneToOne) reconcilation
var OneToOne = kony.sync.currentScope.syncTableDic[tablename].Relationships.OneToOne;
if(!kony.sync.isNullOrUndefined(OneToOne)){
for(var k in OneToOne) {
if(OneToOne[k].TargetObject === childTablename){
var currentRelation = OneToOne[k];
//relation found add the SourceObject_Attributes and TargetObject_Attributes to corresponding arrays
var relationshipAttributes = currentRelation.RelationshipAttributes;
for(var l = 0;l<relationshipAttributes.length;l++){
parentAttributes.push(relationshipAttributes[l].SourceObject_Attribute);
childAttributes.push(relationshipAttributes[l].TargetObject_Attribute);
}
break;
}
}
}
//Reverse Relationships(ManyToOne) reconcilation
var ManyToOne = kony.sync.currentScope.reverseRelationships[tablename];
if(!kony.sync.isNullOrUndefined(ManyToOne)){
for(var k in ManyToOne) {
if(ManyToOne[k].TargetObject === childTablename){
var currentRelation = ManyToOne[k];
//relation found add the SourceObject_Attributes and TargetObject_Attributes to corresponding arrays
var relationshipAttributes = currentRelation.RelationshipAttributes;
for(var l = 0;l<relationshipAttributes.length;l++){
parentAttributes.push(relationshipAttributes[l].SourceObject_Attribute);
childAttributes.push(relationshipAttributes[l].TargetObject_Attribute);
}
break;
}
}
}
if(parentAttributes.length === 0)
continue;
else{
var matchCount = 0;
//identifying if the record is child of the parent record
for(var k=0;k<parentAttributes.length;k++){
var parentAttribute = parentAttributes[k];
var childAttribute = childAttributes[k];
//modifying the parent reconciled values in child record's non-reconciled field to make relationship data consistent
if(childRow[kony.sync.clientPKPrefix + childAttribute] != undefined){
if(childRow[kony.sync.clientPKPrefix + childAttribute] === parentRow[kony.sync.clientPKPrefix+parentAttribute])
matchCount++;
else
break;
}
}
//childrow found
if(matchCount === parentAttributes.length){
childRowFound = true;
populateMetaDataForReconciliation(childPkColumns,childRow,childPkset,childPkwcs);
//tx,pkset,pkwcs,tablename,parentRow,currentIndex
kony.sync.reconcileForeignKeyForChildren(tx,childPkset,childPkwcs,childTablename,childRow,j,endposition,results);//childrowindex
if(kony.sync.reconcileForeignKey(tx, pksetwcs, pkwcs, tablename)===false){
return false;
}
//reconcilation of child rows which are not part of changeset but exist in history table
//it should be done after because we should not do disturb changeset records in history table
reconcileChildrenInHistoryTable(tablename,pkwcs,pksetwcs);
//modifying the parent reconciled values in child record's non-reconciled field to make relationship data consistent
for(var k=0;k<parentAttributes.length;k++){
var parentAttribute = parentAttributes[k];
var childAttribute = childAttributes[k];
if(childRow[kony.sync.clientPKPrefix + childAttribute] != undefined)
childRow[kony.sync.clientPKPrefix + childAttribute] = parentRow[parentAttribute];
}
}
}
}
if(childRowFound === false){
var _isError = reconcileChildrenInHistoryTable(tablename,pkwcs,pksetwcs);
if(_isError === 0){
sync.log.error("error in reconciliation of records of history table not in changeset with parent "+tablename +" with setclause "+JSON.stringify(pksetwcs)+" and whereClause "+JSON.stringify(pkwcs));
return 0;
}
if(kony.sync.reconcileForeignKey(tx, pksetwcs, pkwcs, tablename)===false){
sync.log.error("error in reconciliation of records with parent "+tablename +" with setclause "+JSON.stringify(pksetwcs)+" and whereClause "+JSON.stringify(pkwcs));
return 0;
}
}
//reconcileChildrenInHistoryTable(tablename,pkwcs,pksetwcs);
// no need to check if this is a error record because as this call is made by non-error records
//reconcile records that are not part of server response inside device db ( history table records)
function reconcileChildrenInHistoryTable(parentTableName,parentwcs,parentSetClause){
function reconcileUpdateHelper(childTablename,childSetClause,childwcs){
//update history table
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, childTablename + kony.sync.historyTableName);
kony.sync.qb_set(query, childSetClause);
kony.sync.qb_where(query, childwcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
sync.log.error("reconcilation: error in updating records of "+childTablename + "" + kony.sync.historyTableName+" with whereClause "+ JSON.stringify(childwcs) +" and setclause "+childSetClause);
return 0;
}
//update main table
kony.sync.qb_update(query, childTablename);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if (kony.sync.executeSql(tx, sql, params) === false) {
sync.log.error("reconcilation: error in updating records of "+childTablename +" with whereClause "+ JSON.stringify(childwcs) +" and setclause "+childSetClause);
return 0;
}
}
function fetchChildHistoryTableRows(childTablename,childwcs){
//select the records
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query,null);
kony.sync.qb_from(query,childTablename + kony.sync.historyTableName);
kony.sync.qb_where(query, childwcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params);
return resultset;
}
//fill the current child whereClause and childSetClause
function populateChildQueryParams(relationshipAttributes,childwcs,childSetClause,childTablename,parentTableName){
for (var i = 0; i < relationshipAttributes.length; i++) {
var parentPk = relationshipAttributes[i].SourceObject_Attribute;
var childPk = relationshipAttributes[i].TargetObject_Attribute;
var whereClauseValue = null;
//need to set only the parentSetClause Columns not all the columns in relationshipattributes set
if(parentSetClause[parentPk] != undefined){
childSetClause[childPk] = parentSetClause[parentPk];
}
for(var j = 0;j< parentwcs.length;j++){
var currentObject = parentwcs[j];
if(currentObject.key == parentPk){
whereClauseValue = currentObject.value;
break;
}
}
if(whereClauseValue === null){
sync.log.error("reconcilation:error in forming whereClause for "+childTablename + " having foreign key "+childPk+" with parent table "+parentTableName+" primary key "+parentPk);
return 0;
}
kony.table.insert(childwcs, {
key : childPk,
value : whereClauseValue
});
}
}
//make new whereClause to go recursive
function populateChildWCSParams(rowItem,childPkColumns,newWhereClause,childTablename){
for(var i=0;i<childPkColumns.length;i++){
var columnName = childPkColumns[i];
var columnValue = rowItem[columnName];
if(columnName === undefined){
sync.log.error("reconcilation:error in creating where clause for "+childTablename + " with childrow "+JSON.stringify(rowItem));
return 0;
}
kony.table.insert(newWhereClause, {
key : columnName,
value : columnValue
});
}
}
function checkIfParentColumnsArePrimaryKeys(parentRelationshipAttributes,childPkColumns){
var columnCount = 0;
for(var i=0;i<parentRelationshipAttributes.length;i++){
for(var j =0;j<childPkColumns.length;j++){
if(parentRelationshipAttributes[i].TargetObject_Attribute === childPkColumns[j]){
columnCount++;
break;
}
}
}
return columnCount;
}
//entry here
function reconcileForRelation(RelationShipSet,parentTableName){
if(!kony.sync.isNullOrUndefined(RelationShipSet)){
for(var k in RelationShipSet) {
var currentRelation = RelationShipSet[k];
var childTablename = currentRelation.TargetObject;
var childwcs = [];// all foreign key columns
var childSetClause = {};
var parentRelationshipAttributes = currentRelation.RelationshipAttributes;
var childPkColumns = kony.sync.currentScope.syncTableDic[childTablename].Pk_Columns;
var _isError = populateChildQueryParams(parentRelationshipAttributes,childwcs,childSetClause,childTablename,parentTableName);//child tablename and parent tablename are passed only for error handling
if(_isError === 0)
return _isError;
//call child only if parent columns are part of primary key set
var columnCount = checkIfParentColumnsArePrimaryKeys(parentRelationshipAttributes,childPkColumns);
if(columnCount === parentRelationshipAttributes.length){
// newWhereClause to goto parent grand child
var newWhereClause = [];
//fetch rows from child history table
var childresultset = fetchChildHistoryTableRows(childTablename,childwcs);
if(childresultset === false){
sync.log.error("Reconciliation:error in fetching records from "+ childTablename +" history table with parent "+ parentTableName);
return 0;
}
else{
for(var m=0;m<childresultset.rows.length;m++){
var rowItem = kony.db.sqlResultsetRowItem(tx, childresultset,0);
var _isError = populateChildWCSParams(rowItem,childPkColumns,newWhereClause,childTablename);
if(_isError === 0)
return _isError;
//make recursive call
_isError = reconcileChildrenInHistoryTable(childTablename,newWhereClause,childSetClause);
if(_isError === 0)
return _isError;
}
}
}
var _isError = reconcileUpdateHelper(childTablename,childSetClause,childwcs);
if(_isError === 0)
return _isError;
}
}
}
//Forward Relationships(OneToMany) reconcilation
var OneToMany = kony.sync.currentScope.syncTableDic[parentTableName].Relationships.OneToMany;
var _isError = reconcileForRelation(OneToMany,parentTableName);
if(_isError === 0)
return _isError;
//Forward Relationships(OneToOne) reconcilation
var OneToOne = kony.sync.currentScope.syncTableDic[parentTableName].Relationships.OneToOne;
var _isError = reconcileForRelation(OneToOne,parentTableName);
if(_isError === 0)
return _isError;
//Reverse Relationships(ManyToOne) reconcilation
var ManyToOne = kony.sync.currentScope.reverseRelationships[parentTableName];
var _isError = reconcileForRelation(ManyToOne,parentTableName);
if(_isError === 0)
return _isError;
}
}
kony.sync.checkForHistoryInstance = function(tx, tablename, values, whereClause){
//var sql = "select count(*) from " + tablename + kony.sync.historyTableName + " " + wcs;
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename + kony.sync.historyTableName);
kony.sync.qb_where(query, whereClause);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet === false){
return 0;
}
if(resultSet.rows.length === 0){
return false;
}
return true;
}
//This function removes successful uploads mostly in case of dummy updates
kony.sync.deleteRecordsAfterUpload = function (callback) {
sync.log.trace("Entering kony.sync.deleteRecordsAfterUpload ");
var isError = false;
if ( (kony.sync.OTAChangestobeDeleted.length === 0 && kony.sync.PersisChangestobeDeleted.length === 0 )
|| kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.removeAfterUpload])) {
callback(0);
return;
}
//Concatinating both OTA uploadqueue and persistent delete queue
var results = kony.sync.OTAChangestobeDeleted.concat(kony.sync.PersisChangestobeDeleted);
var length = results.length;
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var scopename = kony.sync.currentScope[kony.sync.scopeName];
kony.sync.getConnection(dbname, dbname, myTransactionCallBack, mySucessCallBack, myErrorCallBack);
function myTransactionCallBack(tx) {
sync.log.trace("Entering myTransactionCallBack");
for (var i = 0; i < length; i++) {
var row = results[i];
var tablename = row.__metadata.type;
//checking for removeafteruploadpolicy
if (kony.sync.checkForDeleteAfterUpload(tablename, scopename) !== true) {
continue;
}
//skipping if error
if (!kony.sync.isNullOrUndefined(row.__metadata.errorMessage)){
continue;
}
var pkColumns = kony.sync.currentScope.syncTableDic[tablename].Pk_Columns;
var pkwcs = [];
for (var j = 0; j < pkColumns.length; j++){
kony.table.insert(pkwcs,{
key: pkColumns[j],
value: row[pkColumns[j]],
optype: "EQ"
});
}
//Get records to be deleted from history table;
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename + kony.sync.historyTableName);
kony.sync.qb_where(query, pkwcs);
kony.sync.qb_distinct(query);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
//do not delete from main table if there is some instance in history table
if(resultSet === false){
isError = true;
return;
}
if(resultSet.rows.length!==0){
continue;
}
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, tablename);
kony.sync.qb_where(query, pkwcs);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
return;
}
}
}
function myErrorCallBack(){
sync.log.trace("Entering deleteRecordsAfterUpload myErrorCallBack");
kony.sync.OTAChangestobeDeleted=[];
kony.sync.PersisChangestobeDeleted = [];
if(isError){
callback(kony.sync.errorCodeSQLStatement);
}
else{
callback(kony.sync.errorCodeTransaction);
}
}
function mySucessCallBack(){
sync.log.trace("Entering deleteRecordsAfterUpload mySucessCallBack");
kony.sync.OTAChangestobeDeleted=[];
kony.sync.PersisChangestobeDeleted = [];
callback(0);
}
};
// **************** End KonySyncDownload.js*******************
// **************** Start KonySyncErrors.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync)=== "undefined"){
sync = {};
}
//error codes
kony.sync.errorCodeInvalidDataType=7001;
kony.sync.errorCodeMandatoryAttribute=7002;
kony.sync.errorCodePrimaryKeyNotSpecified =7003; //Primary Key CategoryID not specified in updating an item in Categories
kony.sync.errorCodeScopeLoading = 7004;//"Scopes loading failed",
kony.sync.errorCodeSyncReset= 7005;//"Sync Reset failed",
kony.sync.errorCodeRegisterDevice = 7006 ; //"Register device failed",
kony.sync.errorCodeSessionBreak = 7007;//"Session breaks since user scope failure",
kony.sync.errorCodeSessionInProgress = 7008; //"Session in progress",
kony.sync.errorCodeNoDataWithPrimaryKey = 7009; //No data with specified primary key found in SyncObject Categories
kony.sync.errorCodeTransaction = 7010;//"Transaction failed"
kony.sync.errorCodeDbConnection = 7011; //"Database connection closed"
kony.sync.errorCodeMarkForUpload = 7012; // "ERROR: [KONYSYNC] Record does not exist on server, mark it for upload before updating/deleting it"
kony.sync.errorCodeDeferredUpload = 7013; // "Error during Deferred Upload Transaction"
kony.sync.errorCodeReferentialIntegrity = 7014; //"Error because of referential integrity failure"
kony.sync.errorCodeLengthValidationFailed = 7015;//Length exceeds than specified limit
kony.sync.errorCodeDuplicatePrimaryKey = 7016;
kony.sync.errorCodeInputTableNotDefined = 7017;
kony.sync.errorCodeMaliciousType = 7018;
kony.sync.errorCodeSQLStatement = 7019;
kony.sync.errorCodeUploadFailed = 7020;
kony.sync.errorCodeDownloadFailed = 7021;
kony.sync.errorCodeSyncError = 7022;
kony.sync.errorCodeParseError = 7023;
kony.sync.errorCodeChunking = 7024;
kony.sync.errorCodeNetworkCallCancelled = 7025;
kony.sync.errorCodeMetatableError = 7026;
kony.sync.errorCodeNullValue = 7027;
kony.sync.errorCodeInvalidMarkForUploadValue = 7028;
kony.sync.errorUnknown = 7777;
kony.sync.errorCodeUnknownServerError = 8888;
kony.sync.errorCodeBlobFileNotCreated = 9000;
kony.sync.errorCodeInvalidColumnType = 9001;
kony.sync.errorCodeEmptyOrNullBase64 = 9002;
kony.sync.errorCodeBlobFileDoesnotExist = 9003;
kony.sync.errorCodeBlobInvalidState = 9004;
kony.sync.errorCodeDownloadAlreadyInQueue = 9005;
kony.sync.errorCodeBlobInvalidStateForDelete = 9006;
kony.sync.errorCodeBlobInvalidStateForUpdate = 9007;
kony.sync.errorCodeInvalidPksGiven = 9008;
kony.sync.errorCodeInvalidColumnParams = 9009;
kony.sync.errorCodeDownloadPolicyNotSupported = 9010;
kony.sync.errorCodeInvalidStateForDownload = 9011;
kony.sync.errorCodeBinaryDownloadFailed = 9012;
kony.sync.errorCodeBlobFileDoesnotExistOnDemand = 9013;
kony.sync.errorCodeParentMappingAttributeNotFound = 9014;
kony.sync.errorCodeChildObjectShouldBeArray = 9015;
kony.sync.errorCodeNullPrimaryKeyValue = 9016;
kony.sync.errorCodeInvalidTableName = 9017;
kony.sync.errorCodeRecordDoNotExist = 9018;
kony.sync.errorCodeBinaryUploadFailed = 9019;
kony.sync.retryErrors = {};
//Server ErrorCodes
kony.sync.servercodes = {};
kony.sync.servercodes.appVersionNotLatest = "SY3001E";
kony.sync.getSessionInProgressError = function() {
sync.log.trace("Entering kony.sync.getSessionInProgressError ");
return kony.sync.getErrorTable(kony.sync.errorCodeSessionInProgress,kony.sync.getErrorMessage(kony.sync.errorCodeSessionInProgress),null);
};
kony.sync.getScopeLoadingFailed = function() {
sync.log.trace("Entering kony.sync.getScopeLoadingFailed ");
return kony.sync.getErrorTable(kony.sync.errorCodeScopeLoading, kony.sync.getErrorMessage(kony.sync.errorCodeScopeLoading),null);
};
kony.sync.getSyncResetFailed = function() {
sync.log.trace("Entering kony.sync.getSyncResetFailed ");
return kony.sync.getErrorTable(kony.sync.errorCodeSyncReset,kony.sync.getErrorMessage(kony.sync.errorCodeSyncReset),null);
};
kony.sync.getSyncRegisterationFailed = function() {
sync.log.trace("Entering kony.sync.getSyncRegisterationFailed ");
return kony.sync.getErrorTable(kony.sync.errorCodeRegisterDevice,kony.sync.getErrorMessage(kony.sync.errorCodeRegisterDevice),null);
};
kony.sync.getScopeFailed = function() {
sync.log.trace("Entering kony.sync.getScopeFailed ");
return kony.sync.getErrorTable(kony.sync.errorCodeSessionBreak,kony.sync.getErrorMessage(kony.sync.errorCodeSessionBreak),null);
};
kony.sync.getServerError = function(ServerReport, moduleType) {
sync.log.trace("Entering kony.sync.getServerError ");
var serverDetails = {};
if (!kony.sync.isNullOrUndefined(ServerReport)) {
if(!kony.sync.isNullOrUndefined(ServerReport.server)){
serverDetails[kony.sync.hostName] = ServerReport.server.hostName;
serverDetails[kony.sync.ipAddress] = ServerReport.server.ipAddress;
}
//error occurred at application layer
if (!kony.sync.isNullOrUndefined(ServerReport.msg )) {
var errorCode = ServerReport.errcode;
if (kony.sync.isNullOrUndefined(ServerReport.errcode)) { //should not hit this ideally
if (moduleType === "upload") {
errorCode = kony.sync.errorCodeUploadFailed;
} else if (moduleType === "download") {
errorCode = kony.sync.errorCodeDownloadFailed;
} else {
errorCode = kony.sync.errorCodeUnknownServerError;
}
}
var otherParams = {};
if(errorCode === kony.sync.servercodes.appVersionNotLatest){
otherParams.newApplicationVersion = ServerReport.newapplicationversion;
otherParams.oldApplicationVersion = ServerReport.oldapplicationversion;
}
if(kony.sync.isMbaasEnabled && !kony.sync.isNullOrUndefined(ServerReport.mfcode)) {
otherParams.mfcode = ServerReport.mfcode;
ServerReport.msg = getAuthErrorMessage(ServerReport.mfcode);
}
return kony.sync.getErrorTable(errorCode, ServerReport.msg, ServerReport.stacktrace, serverDetails, otherParams);
}
//error occurred at network layer
if (!kony.sync.isNullOrUndefined(ServerReport.errmsg )) {
return kony.sync.getErrorTable(ServerReport.opstatus, ServerReport.errmsg, null, serverDetails);
}
}
return kony.sync.getErrorTable(kony.sync.errorCodeUnknownServerError, "Unknown Error from the server", ServerReport, serverDetails);
};
kony.sync.getErrorTable = function(errorCode, errorMessage, errorInfo, serverDetails, otherParams) {
sync.log.trace("Entering kony.sync.getErrorTable ");
var errorTable = {};
errorTable.errorCode = errorCode;
errorTable.errorMessage = errorMessage;
errorTable.errorInfo = errorInfo;
errorTable[kony.sync.serverDetails] = serverDetails;
if(!kony.sync.isNullOrUndefined(otherParams)) {
for (var i in otherParams) {
errorTable[i] = otherParams[i];
}
}
if(!kony.sync.isNullOrUndefined(errorInfo)){
if(!kony.sync.isNullOrUndefined(errorInfo[kony.sync.errorInfoDatabaseError])){
if(!kony.sync.isEmptyString(errorInfo[kony.sync.errorInfoDatabaseError])){
errorTable.errorMessage = errorMessage + ". \n" + "System Error:" + errorInfo[kony.sync.errorInfoDatabaseError].message;
}
}
}
return errorTable;
};
kony.sync.getErrorMessage = function(errorCode,objectName, attributeName) {
sync.log.trace("Entering kony.sync.getErrorMessage ");
var errorMap = {};
errorMap[kony.sync.errorCodeMandatoryAttribute] = "Mandatory attribute " + attributeName + " is missing for the SyncObject " + objectName + ".",
errorMap[kony.sync.errorCodeScopeLoading] = "Scopes loading failed.",
errorMap[kony.sync.errorCodeSyncReset] = "Sync Reset failed.",
errorMap[kony.sync.errorCodeRegisterDevice] = "Register device failed.",
errorMap[kony.sync.errorCodeSessionBreak] = "Session breaks since user scope failure.",
errorMap[kony.sync.errorCodeSessionInProgress] = "Session in progress.",
errorMap[kony.sync.errorCodeTransaction] = "Transaction failed.",
errorMap[kony.sync.errorCodeDbConnection] = "Error occurred while establishing a Database connection.",
errorMap[kony.sync.errorCodeMarkForUpload] = "Record does not exist on server, mark it for upload before updating/deleting it.",
errorMap[kony.sync.errorCodeDeferredUpload] = "Error during Deferred Upload Transaction.",
errorMap[kony.sync.errorCodeNoDataWithPrimaryKey] = "No data with specified primary key found in SyncObject " + objectName + ".",
errorMap[kony.sync.errorCodeDuplicatePrimaryKey] = "Primary Key " + attributeName +" already exists in table " + objectName + ". Please give different value of primary key.",
errorMap[kony.sync.errorCodeInputTableNotDefined] = "Input Table not defined",
errorMap[kony.sync.errorCodeMaliciousType] = "Malicious value '" + attributeName + "' given for attribute " + objectName + ".",
errorMap[kony.sync.errorCodeSQLStatement] = "Some error occurred in executing SQL statement",
errorMap[kony.sync.errorCodeSyncError] = "Error occurred while syncing one or more scopes" ,
errorMap[kony.sync.errorCodeDownloadFailed] = "Error occurred in Downloading changes from Sever" ,
errorMap[kony.sync.errorCodeUploadFailed] = "Error occurred in Uploading changes to Server";
errorMap[kony.sync.errorUnknown] = "The following error occurred while performing " + objectName + " : \"" + attributeName + "\"." + " Possible reasons can be sync.init may not have been invoked.";
errorMap[kony.sync.errorCodeParseError] = "Following error occurred while parsing " + JSON.stringify(objectName) + " : \"" + attributeName + "\"";
errorMap[kony.sync.errorCodeChunking] = "Error occurred while downloading one or more chunks.";
errorMap[kony.sync.errorCodeMetatableError] = "Meta tables did not get created successfully because of some unknown problem in sync.init, please invoke sync.reset";
errorMap[kony.sync.errorCodeNullValue] = "Null values passed in input array";
errorMap[kony.sync.errorCodeBlobFileNotCreated] = "Error occurred when creating a file";
errorMap[kony.sync.errorCodeInvalidColumnType] = "Expecting an array and got type "+objectName+ "instead for columns";
errorMap[kony.sync.errorCodeEmptyOrNullBase64] = "Empty or Null value should not be passed for Base64";
errorMap[kony.sync.errorCodeBlobFileDoesnotExistOnDemand] = "Request file doesn't exist. Please retrigger the download of the binary";
errorMap[kony.sync.errorCodeBlobFileDoesnotExist] = "Request file doesn't exist.";
errorMap[kony.sync.errorCodeBlobInvalidState] = "BlobFile in invalid state. Could not upload.";
errorMap[kony.sync.errorCodeDownloadAlreadyInQueue] = "Binary download already requested";
errorMap[kony.sync.errorCodeBlobInvalidStateForDelete] = "Blob cannot be deleted in "+objectName+" state";
errorMap[kony.sync.errorCodeBlobInvalidStateForUpdate] = "Blob cannot be updated in "+objectName+" state";
errorMap[kony.sync.errorCodeInvalidPksGiven] = "Invalid primary keys given for table "+objectName;
errorMap[kony.sync.errorCodeInvalidColumnParams] = "Invalid column params ";
errorMap[kony.sync.errorCodeDownloadPolicyNotSupported] = "Download policy not supported for "+objectName;
errorMap[kony.sync.errorCodeInvalidStateForDownload] = "Blob cannot be downloaded in "+objectName+" state";
errorMap[kony.sync.errorCodeBinaryDownloadFailed] = "Binary Download operation failed ";
errorMap[kony.sync.errorCodeParentMappingAttributeNotFound] = "Parent Mapping Attribute not found for given child "+objectName;
errorMap[kony.sync.errorCodeChildObjectShouldBeArray] = "Child objects should be of Array type for complex object CUD";
errorMap[kony.sync.errorCodeNullPrimaryKeyValue] = "Null value passed for primary key "+objectName;
errorMap[kony.sync.errorCodeInvalidTableName] = "Invalid table name sent for DB Operation "+objectName;
errorMap[kony.sync.errorCodeRecordDoNotExist] = "Record doesn't exists with given conditions "+objectName;
errorMap[kony.sync.errorCodeInvalidMarkForUploadValue] = "MarkforUpload value can not be made true if the object is created with mark for upload as false";
errorMap[kony.sync.errorCodeBinaryUploadFailed] = "Binary Upload operation failed ";
if(errorMap[errorCode]===null){
return "Some unknown client error";
}
else{
return errorMap[errorCode];
}
};
kony.sync.getInvalidDataTypeMsg = function(objectName, attributeName, expectedType, actualType){
sync.log.trace("Entering kony.sync.getInvalidDataTypeMsg ");
return "Invalid data type for the attribute " + attributeName + " in " + objectName + ".\nExpected:\"" + expectedType + "\"\nActual:\"" + actualType + "\"";
};
kony.sync.getPrimaryKeyNotSpecifiedMsg = function (primaryKey,operation,table) {
sync.log.trace("Entering kony.sync.getPrimaryKeyNotSpecifiedMsg ");
return "Primary Key " + primaryKey + " not specified in " + operation + " an item in " + table + ".";
};
kony.sync.getReferetialIntegrityerrMessg = function (sourceAttribute,TargetAttributes,TargetValues){
sync.log.trace("Entering kony.sync.getReferetialIntegrityerrMessg ");
//return "Referential Integrity Constraints Violation: " + TargetAttribute+" = " + TargetValue + " does not exists in " + sourceAttribute + ".";
var integrityMessage = "";
for (var i = 0; i < TargetAttributes.length; i++) {
integrityMessage = integrityMessage + TargetAttributes[i]+" = "+TargetValues[i];
if(i != TargetAttributes.length-1) {
integrityMessage = integrityMessage + " AND ";
}
};
integrityMessage = integrityMessage + " does not exists in " +sourceAttribute+".";
//return "Referential Integrity Constraints Violation: " + TargetAttribute+" = " + TargetValue + " does not exists in " + sourceAttribute + ".";
return "Referential Integrity Constraints Violation: " + integrityMessage;
};
kony.sync.getReferetialIntegrityDeleteErrMessg = function (sourceAttribute, TargetAttribute, targetValue, srcValue){
sync.log.trace("Entering kony.sync.getReferetialIntegrityDeleteErrMessg ");
return "Referential Integrity Constraints Violation: " + "Delete dependent records from " + targetValue + " before deleting record(s) in " + srcValue + ".";
};
kony.sync.getValidateLengthErrMsg = function (tablename, colname, expectedLength, actualLength){
sync.log.trace("Entering kony.sync.getValidateLengthErrMsg ");
return "Length exceeds the limit for the attribute " + colname + " in " + tablename + ".\nExpected:\'" + expectedLength + "\'\nActual:\'" + actualLength + "\'";
};
kony.sync.getSchemaUpgradeNeededError = function(){
sync.log.trace("Entering kony.sync.getSchemaUpgradeNeededError");
//TODO:needs to be replaced with actual schema error
return kony.sync.getErrorTable(kony.sync.errorCodeSessionBreak,kony.sync.getErrorMessage(kony.sync.errorCodeSessionBreak),null);
};
kony.sync.getNetworkCancelError = function(){
var errCreate = {};
errCreate.opstatus = 7025;
errCreate.errmsg = "Error occurred, Network Call Cancelled";
return errCreate;
}
// **************** End KonySyncErrors.js*******************
// **************** Start KonySyncGlobals.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync)=== "undefined"){
sync = {};
}
//This enables the Print Statements in the Sync Library
kony.sync.syncLibPrint = true;
kony.sync.downloadNextBatchServerblob = null; //not used
kony.sync.scopes = [];
kony.sync.gMoreChanges = true; //not used
kony.sync.gSyncFailed = false;
kony.sync.gPolicy = 0;
kony.sync.isMbaasEnabled = false;
//Sync Config
kony.sync.currentSyncConfigParams = null;
kony.sync.currentSyncLog = [];
//Sync Call Backs Constants
kony.sync.sessionTasks = "sessiontasks";
kony.sync.sessionTaskDoUpload = "doupload";
kony.sync.sessionTaskDoDownload = "dodownload";
kony.sync.blobStoreManagerTable = "konysyncBLOBSTOREMANAGER";
kony.sync.filterParams = "filterparams";
kony.sync.onSyncStart = "onsyncstart";
kony.sync.onScopeStart = "onscopestart";
kony.sync.onScopeError = "onscopeerror";
kony.sync.onScopeSuccess = "onscopesuccess";
kony.sync.onAuthenticationSuccess = "onauthenticationsuccess";
kony.sync.onUploadStart = "onuploadstart";
kony.sync.onUploadSuccess = "onuploadsuccess";
kony.sync.onUploadBatchStart = "onuploadbatchstart";
kony.sync.onUploadBatchSuccess = "onuploadbatchsuccess";
kony.sync.onDownloadStart = "ondownloadstart";
kony.sync.onDownloadSuccess = "ondownloadsuccess";
kony.sync.onBatchStored = "onbatchstored";
kony.sync.onBatchProcessingStart = "onbatchprocessingstart";
kony.sync.onBatchProcessingSuccess = "onbatchprocessingsuccess";
kony.sync.onSyncSuccess = "onsyncsuccess";
kony.sync.onSyncError = "onsyncerror";
kony.sync.removeAfterUpload="removeafterupload";
kony.sync.passwordHashingAlgo="passwordhashalgo";
//Sync Context Params
kony.sync.objectLevelInfo = "objectlevelinfo";
kony.sync.authenticateURL = "authenticateurl";
kony.sync.uploadURL = "uploadurl";
kony.sync.downloadURL = "downloadurl";
kony.sync.uploadContext = "uploadcontext";
kony.sync.uploadBatchContext = "uploadbatchcontext";
kony.sync.failedRowInfo = "failedrowinfo";
kony.sync.uploadSummary = [];
kony.sync.numberOfRowsUploaded = "rowsuploaded";
kony.sync.numberOfRowsInserted = "rowsinserted";
kony.sync.numberOfRowsUpdated = "rowsupdated";
kony.sync.numberOfRowsDeleted = "rowsdeleted";
kony.sync.numberOfRowsInsertedAck = "ackinsertedrows";
kony.sync.numberOfRowsUpdatedAck = "ackupdatedrows";
kony.sync.numberOfRowsDeletedAck = "ackdeletedrows";
kony.sync.numberOfRowsAcknowledged = "acktotalrows";
kony.sync.numberOfRowsFailedtoUpload = "rowsfailedtoupload";
kony.sync.pendingBatches = "pendingbatches";
kony.sync.numberOfRowsDownloaded = "batchrowsdownloaded";
kony.sync.batchContext = "batchcontext";
kony.sync.lastSyncTimestamp = "lastsynctimestamp";
kony.sync.uploadSequenceNumber = "uploadsequencenumber";
kony.sync.currentScope = "currentscope";
kony.sync.dataSource = "DataSource";
kony.sync.scopeDataSource = "ScopeDatabaseName";
kony.sync.scopeName = "ScopeName";
kony.sync.syncStrategy = "Strategy";
kony.sync.syncStrategy_OTA = "OTA_SYNC";
kony.sync.versionNumber = "1.0";
kony.sync.dbSize = 5 * 1024 * 1024;
//Pending Batchs
kony.sync.syncPendingBatchesNo = 0;
kony.sync.syncStatusColumn = "changetype";
kony.sync.syncConfigurationDBName = "SyncConfig";
kony.sync.syncConfigurationTableName = "SyncConfigTable";
kony.sync.syncConfigurationColumnDeviceIDName = "DeviceID";
kony.sync.syncConfigurationColumnInstanceIDName = "InstanceID";
kony.sync.syncConfigurationColumnVersion = "SyncVersion";
kony.sync.syncConfigurationColumnSchemaUpgradeContext = "schemaupgradecontext";
kony.sync.configVersion = "";
kony.sync.metaTableName = "konysyncMETAINFO";
kony.sync.metaTableScopeColumn = "scopename";
kony.sync.metaTableSyncTimeColumn = "lastserversynccontext";
kony.sync.metaTableUploadSyncTimeColumn = "lastserveruploadsynccontext";
kony.sync.metaTableSchemaUpgradeSyncTimeColumn = "lastschemaupgradesynccontext";
kony.sync.metaTableSyncVersionCloumn = "versionnumber";
kony.sync.metaTableSyncOrderCloumn = "replaysequencenumber";
kony.sync.metaTableLastGeneratedId = "lastgeneratedid";
kony.sync.metaTableFilterValue = "filtervalue";
kony.sync.historyTableName = "_history";
kony.sync.changeTypeColumn = "changetype";
kony.sync.dbConnection = null;
kony.sync.mainTableSyncVersionColumn = "konysyncversionnumber";
kony.sync.mainTableChangeTypeColumn = "konysyncchangetype";
kony.sync.mainTableHashSumColumn = "konysynchashsum";
kony.sync.historyTableSyncVersionColumn = "konysyncversionnumber";
kony.sync.historyTableChangeTypeColumn = "konysyncchangetype";
kony.sync.historyTableReplaySequenceColumn = "konysyncreplaysequence";
kony.sync.historyTableChangeTimeColumn = "konysyncchangetime"; // Not used as of now.
kony.sync.historyTableHashSumColumn = "konysynchashsum";
kony.sync.originalTableName = "_original";
kony.sync.originalTableChangeTypeColumn = "konysyncoriginalchangetype";
kony.sync.originalTableSyncVersionColumn = "konysyncoriginalversionnumber";
kony.sync.originalTableHashSumColumn = "konysynchashsum";
kony.sync.mergedWithEIS = "konysyncMergedWithEIS";
kony.sync.clientPKPrefix = "konysyncClient";
kony.sync.parentRelationshipMap = "_parentrelationships";
//Global SyncSession Configurations
kony.sync.isSessionInProgress = false;
kony.sync.currentScope = null;
kony.sync.deviceId = null;
kony.sync.instanceId = null;
kony.sync.originalDeviceId = null;
//Global changetype columns
kony.sync.insertColStatus = "0";
kony.sync.updateColStatus = "1";
kony.sync.deleteColStatus = "2";
kony.sync.insertColStatusDI = "90";
kony.sync.updateColStatusDU = "91";
kony.sync.deleteColStatusDD = "92";
//storeid_callback_scope = null; Not used.
kony.sync.currentSyncScopesState = [];
kony.sync.isParameter = true;
kony.sync.dbTypeSQLLite = "sqllite";
kony.sync.dbTypeSQLCE = "sqlce";
kony.sync.platformName = null;
kony.sync.hashTypeSHA256 = "SHA256";
kony.sync.pendingAckIndex = 1;
kony.sync.pendingAckResult = {};
kony.sync.pendingAckCount = 0;
kony.sync.pendingUploadIndex = 1;
kony.sync.pendingUploadResult = {};
kony.sync.pendingUploadCount = 0;
kony.sync.deferredUploadIndex = 1;
kony.sync.deferredUploadResult = {};
kony.sync.deferredUploadCount = 0;
kony.sync.rollbackCurrentScope = null;
kony.sync.onDownloadCompletion = null;
kony.sync.globalIsDownloadStarted = true;
kony.sync.globalIsUploadStarted = true;
kony.sync.globalIsUploadFailed = true;
kony.sync.onUploadCompletion = null;
kony.sync.currentSyncReturnParams = {};
kony.sync.syncTotalBatchInserts = 0;
kony.sync.syncTotalBatchUpdates = 0;
kony.sync.syncTotalBatchDeletes = 0;
kony.sync.syncTotalInserts = 0;
kony.sync.syncTotalUpdates = 0;
kony.sync.syncTotalDeletes = 0;
kony.sync.serverInsertCount = 0;
kony.sync.serverUpdateCount = 0;
kony.sync.serverDeleteCount = 0;
kony.sync.serverInsertAckCount = 0;
kony.sync.serverUpdateAckCount = 0;
kony.sync.serverDeleteAckCount = 0;
kony.sync.serverFailedCount = 0;
kony.sync.objectLevelInfoMap = {};
kony.sync.queryStore = [];
kony.sync.batchDownloadTimer = 0;
kony.sync.batchInsertionTimer = 0;
kony.sync.OTAChangestobeDeleted = [];
kony.sync.PersisChangestobeDeleted = [];
kony.sync.sessionTaskUploadErrorPolicy = "uploaderrorpolicy";
kony.sync.sessionTaskUploadErrorPolicyCOE = "continueonerror";
kony.sync.sessionTaskUploadErrorPolicyAOE = "abortonerror";
//global variable to check whether reset already started or not
kony.sync.isResetInProgress = false;
kony.sync.errorInfoTransactionID = "transactionID";
kony.sync.errorInfoDatabaseError = "dbError";
//global variable to check whether sync for any scope got succeeded or not.
//If sync is not faled for any scope, then only call onsyncsuccess else onsyncerror
kony.sync.isErrorInAnyScope = false;
kony.sync.syncErrorMessage = {};
//This variable will save download request from first batch for subsequent batches
kony.sync.downloadRequest = null;
kony.sync.errorObject = null;
kony.sync.schemaUpgradeErrorObject = null;
kony.sync.enableORMValidations = true;
kony.sync.numberOfRetriesKey = "numberofretryattempts";
kony.sync.onRetry = "onretry";
kony.sync.networkTimeOutKey = "networktimeout";
kony.sync.retryErrorCodes = "retryerrorcodes";
kony.sync.retryWaitKey = "retrywaittime";
//kony.sync.numberOfRetries = 0;
kony.sync.numberOfRetriesMap = {};
kony.sync.maxParallelChunksKey = "maxparallelchunks";
kony.sync.payloadIdKey = "payloadid";
kony.sync.chunkCountKey = "chunkcount";
kony.sync.chunkNoKey = "chunknumber";
kony.sync.chunkDataKey = "chunkdata";
kony.sync.chunkSizeKey = "chunksize";
kony.sync.chunkHashSum = "checksum";
kony.sync.chunkMetaTableName = "konysyncCHUNKMETAINFO";
kony.sync.metaTablePayloadId = "payloadid";
kony.sync.metaTableChunkAck = "chunkacknowledged";
kony.sync.metaTableChunkSize = "chunksize";
kony.sync.metaTableChunkHashSum = "chunkhashsum";
kony.sync.metaTableChunkDiscarded = "chunkdiscarded";
kony.sync.metaTableChunkCount = "chunkcount";
kony.sync.chunkTableName = "konysyncCHUNKDATA";
kony.sync.chunkTableChunkData = "chunkdata";
kony.sync.chunkTableChunkId = "chunkid";
kony.sync.chunkTablePayloadId = "payloadid";
kony.sync.chunkTableTimeStamp = "timestamp";
kony.sync.chunkRequestKey = "chunkrequest";
kony.sync.pendingChunksKey = "pendingchunks";
kony.sync.chunksDownloadedKey = "chunksdownloaded";
kony.sync.onChunkStart = "onchunkstart";
kony.sync.onChunkSuccess = "onchunksuccess";
kony.sync.onChunkError = "onchunkerror";
kony.sync.chunkNotAcknowledged = 0;
kony.sync.chunkCompleteButNotAcknowledged = 1;
kony.sync.chunkCompleteAndWaitingForAck = 2;
kony.sync.chunkDiscarded = 1;
kony.sync.chunkNotDiscarded = 0;
kony.sync.trackIntermediateUpdates = true;
kony.sync.uploadcontextMap = {};
kony.sync.serverDetails = "serverDetails";
kony.sync.hostName = "hostName";
kony.sync.ipAddress = "ipAddress";
/*meta info about konysyncPENDINGUPLOADREQUESTINFO table */
kony.sync.pendingUploadTableName = "konysyncPENDINGUPLOADREQUESTINFO";
kony.sync.pendingUploadTableInsertCount = "insertcount";
kony.sync.pendingUploadTableUpdateCount = "updatecount";
kony.sync.pendingUploadTableDeleteCount = "deletecount";
kony.sync.pendingUploadTableBatchInsertCount = "batchinsertcount";
kony.sync.pendingUploadTableBatchUpdateCount = "batchupdatecount";
kony.sync.pendingUploadTableBatchDeleteCount = "batchdeletecount";
kony.sync.pendingUploadTableObjectLevelInfo = "objectlevelinfo";
kony.sync.pendingUploadTableUploadRequest = "uploadrequest";
kony.sync.pendingUploadTableUploadLimit = "uploadlimit";
kony.sync.deviceDBEncryptionKey = null;
kony.sync.deviceDBEncryptionKeyParam = "devicedbencryptionkey";
kony.sync.onSyncInitSuccessParam = "oninitsuccess";
kony.sync.onSyncInitErrorParam = "oniniterror";
kony.sync.onSyncResetSuccessParam = "onresetsuccess";
kony.sync.onSyncResetErrorParam = "onreseterror";
kony.sync.currentSyncScopeFilter = null;
kony.sync.currentSyncScopeFilterIndex = 1;
kony.sync.uploadClientContext = {};
kony.sync.downloadClientContext = {};
kony.sync.reconciledKeysKey = "reconciledprimarykeys";
kony.sync.schemaUpgradeNeeded = false;
kony.sync.schemaUpgradeContext = null;
kony.sync.schemaUpgradeDownloadPending = false;
kony.sync.omitUpload = false;
kony.sync.omitDownload = false;
kony.sync.onUpgradeQueriesDownloadStartKey = "onupgradescriptsdownloadstart";
kony.sync.onUpgradeQueriesDownloadSuccessKey = "onupgradescriptsdownloadsuccess";
kony.sync.onUpgradeQueriesDownloadErrorKey = "onupgradescriptsdownloaderror";
kony.sync.onUpgradeQueriesExecutionStartKey = "onupgradescriptsexecutionstart";
kony.sync.onUpgradeQueriesExecutionSuccessKey = "onupgradescriptsexecutionsuccess";
kony.sync.onUpgradeQueriesExecutionErrorKey = "onupgradescriptsexecutionerror";
kony.sync.onUpgradeRequiredKey = "onupgraderequired";
//Schema Upgrade Policies
kony.sync.onUpgradeActionAbort = "ABORT";
kony.sync.onUpgradeActionContinue = "CONTINUE"; //Not Implemented
kony.sync.onUpgradeActionContinueOnlyUpload = "CONTINUE_ONLY_UPLOAD"; //Not Implemented
kony.sync.onUpgradeActionUploadAbort = "UPLOAD_AND_ABORT";
kony.sync.onUpgradeActionUpgrade = "UPGRADE";
kony.sync.onUpgradeActionUploadUpgrade = "UPLOAD_AND_UPGRADE";
kony.sync.performOnlySchemaUpgrade = false;
kony.sync.onIsUpgradeRequiredSuccessKey = "isupgraderequiredsuccess";
kony.sync.onIsUpgradeRequiredErrorKey = "isupgraderequirederror";
kony.sync.onIsUpgradeRequiredStartKey = "isupgraderequiredstart";
kony.sync.onPerformUpgradeStartKey = "onperformupgradestart";
kony.sync.onPerformUpgradeSuccessKey = "onperformupgradesuccess";
kony.sync.onPerformUpgradeErrorKey = "onperformupgradeerror";
kony.sync.forceUpload = false;
kony.sync.forceUploadUpgrade = false;
kony.sync.uploadLimit = 0;
kony.sync.deviceIdentifierIOS7Key = "deviceidentifierios7";
kony.sync.isAlertEnabled = true;
kony.sync.invokeServiceFunctionKey = "invokeservicefunction";
kony.sync.authTokenKey = "authtoken";
kony.sync.sessionMap = {};
kony.sync.konySyncSessionID = "konysyncsessionid";
kony.sync.konySyncRequestNumber = "konysyncrequestnumber";
kony.sync.isSyncStopped = false;
kony.sync.onSyncStop = null;
kony.sync.httprequestsession = null;
kony.sync.DDL556to559Update = [];
kony.sync.DDL559to560Update = [];
kony.sync.scopeDict = {};
kony.sync.isAppInBackground = false;
kony.sync.isPhonegap = false;
//upload cache changes
kony.sync.scope = "scope";
kony.sync.offset = "offset";
kony.sync.limit = "limit";
kony.sync.lastSequenceNumber = "lastSeqNo";
kony.sync.batchSize = "batchsize";
kony.sync.changeSet = "changeset";
kony.sync.uploadChangesLimit = "uploadLimit";
kony.sync.lastBatch = "lastBatch";
kony.sync.columns = "binarycolumns";
kony.sync.binaryMetaColumnPrefix = "blobref_";
kony.sync.blob = "binary";
kony.sync.onDemand = "ondemand";
kony.sync.always = "always";
kony.sync.ifRecordValue = "ifrecordvalue";
kony.sync.syncToDeviceField = "downloadToDeviceField";
kony.sync.inline = "Inline";
kony.sync.notSupported = "NotSupported";
kony.sync.blobRefNotFound = -1;
kony.sync.blobRefNotDefined = "NULL";
kony.sync.binaryPolicy = "downloadToDevice";
kony.sync.blobTypeBase64 = "base64";
kony.sync.blobTypeStream = "stream";
kony.sync.forceDownload = "forceDownload";
kony.sync.maxFilePercent = 100;
kony.sync.minFilePercent = 0;
kony.sync.maxRetries = 3;
kony.sync.optype = "optype";
kony.sync.comptype = "comptype";
kony.sync.openbrace = "openbrace";
kony.sync.closebrace = "closebrace";
kony.sync.queryKey = "key";
kony.sync.queryValue = "value";
kony.sync.params = "params";
kony.sync.httpHeaders = "httpheaders";
kony.sync.url = "url";
kony.sync.blobId = "blobid";
kony.sync.blobName = "blobname";
kony.sync.type = "type";
kony.sync.metadata = "metadata";
kony.sync.changetype = "changetype";
kony.sync.syncobjects = "syncobjects";
kony.sync.serverBlob = "serverBlob";
kony.sync.blobSyncScope = "scopeName";
kony.sync.clientId = "clientid";
kony.sync.moreChangesAvailable = "moreChangesAvailable";
kony.sync.requestState = "requestState";
kony.sync.currentSyncConfigKey = "currentSyncConfigParams";
kony.sync.requestType = "requestType";
kony.sync.isUpload = false;
kony.sync.isDownload = true;
kony.sync.konySyncReplaySequence = "konysyncreplaysequence";
kony.sync.SequenceNumber = "SequenceNumber";
kony.sync.sync = "sync";
kony.sync.oneToMany = "OneToMany";
kony.sync.targetObject = "TargetObject";
kony.sync.sourceAttribute = "ParentObject_Attribute";
kony.sync.targetAttribute = "ChildObject_Attribute";
kony.sync.isCleanUpJobCompleted = false;
kony.sync.onBinaryDownloadFunction = "onBinaryDownload";
kony.sync.onBinaryUploadFunction = "onBinaryUpload";
// **************** End KonySyncGlobals.js*******************
// **************** Start KonySyncHelper.js*******************
if(typeof(kony.sync) === "undefined"){
kony.sync = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
//This function is used inside sync library to handle prints
kony.sync.syncPrint = function (param){
sync.log.trace("Entering kony.sync.syncPrint ");
if (kony.sync.syncLibPrint){
kony.print(param);
}
};
/*
--This function formats the sqllite resultset. This is temporary and should be done at platform level.
--function format_row(rowItem)
kony.sync.format_row = function(rowItem)
local rowtemp = {}
if(rowItem ~= nil)then
for key,value in pairs(rowItem) do
value = ""..value;
if(string.isnumeric(value))then
string.replace(value,".0","");
end
rowtemp[key] = string.replace(value, "'", "");
end
if ( value ~= nil ) then
string.replace(value, "'", "");
end
else
return nil;
end
return rowtemp;
end
--*/
kony.sync.getTableInfo = function (tablename) {
sync.log.trace("Entering kony.sync.getTableInfo ");
for (var i = 0; i < kony.sync.scopes.length; i++) {
var scope = kony.sync.scopes[i];
if(!kony.sync.isNullOrUndefined(scope.syncTableDic[tablename])) {
return scope.syncTableDic[tablename];
}
}
return null;
};
kony.sync.is_SQL_select = function (sql) {
sync.log.trace("Entering kony.sync.is_SQL_select ");
sql = kony.string.trim(sql);
return kony.string.startsWith(sql, "select", true);
};
kony.sync.dummyerror = function (tid, err) {
sync.log.trace("Entering kony.sync.dummyerror ");
if (kony.sync.isNullOrUndefined(err)) {
sync.log.debug("dummyerror");
} else {
sync.log.debug("dummy error --->", err);
}
};
kony.sync.verifyAndCallClosure = function (closure, params) {
sync.log.trace("Entering kony.sync.verifyAndCallClosure ");
if (kony.sync.isValidFunctionType(closure)) {
return closure(params);
} else {
sync.log.warn("Invalid callback type : ", closure);
}
};
kony.sync.getArrayCount = function (tab) {
sync.log.trace("Entering kony.sync.getArrayCount ");
var count = 0;
if (!kony.sync.isNullOrUndefined(tab)) {
for (var i in tab) {
count = count + 1;
}
}
return count;
};
kony.sync.getDeviceID = function () {
sync.log.trace("Entering kony.sync.getDeviceID");
if(kony.sync.deviceId !== ""){
return kony.sync.deviceId;
}
//#ifdef KONYSYNC_IOS
var deviceInfo = kony.os.deviceInfo();
if(deviceInfo.osversion < 7){
return deviceInfo.deviceid;
}else{
if(kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.deviceIdentifierIOS7Key])){
return deviceInfo.identifierForVendor;
}else{
return kony.sync.currentSyncConfigParams[kony.sync.deviceIdentifierIOS7Key];
}
}
//#else
return kony.os.deviceInfo().deviceid;
//#endif
};
kony.sync.getInstanceID = function () {
sync.log.trace("Entering kony.sync.getInstanceID ");
return kony.sync.instanceId;
};
kony.sync.getOriginalDeviceID = function () {
sync.log.trace("Entering kony.sync.getOriginalDeviceID ");
if (kony.sync.isNullOrUndefined(kony.sync.originalDeviceId)) {
kony.sync.originalDeviceId = kony.os.deviceInfo().deviceid;
return kony.os.deviceInfo().deviceid;
} else {
return kony.sync.originalDeviceId;
}
};
kony.sync.removeprovisioncolumns = function (row, columns, isArray, isUpdate) {
sync.log.trace("Entering kony.sync.removeprovisioncolumns ");
//remove the blobref_columns from the columns.
var length = columns.length;
var record = [];
var i = null;
if (!isArray) {
for (i = length - 1; i >= 0; i--) {
if (!kony.sync.isNullOrUndefined(row[columns[i].Name])){
record.push(row[columns[i].Name]);
}
else if(isUpdate !== true){
record.push("NULL");
}
}
if (!kony.sync.isNullOrUndefined(row.konysynchashsum)) {
record.push(row.konysynchashsum);
}
return record;
} else {
for (i = length - 1; i >= 0; i--) {
if (!kony.sync.isNullOrUndefined(row[columns[i].Name])){
record[columns[i].Name] = row[columns[i].Name];
}
else if(isUpdate !== true){
record[columns[i].Name] = "NULL";
}
}
if(!kony.sync.isNullOrUndefined(row.konysynchashsum)) {
record.konysynchashsum = row.konysynchashsum;
}
return record;
}
};
kony.sync.replaceautogeneratedPK = function (sname, synctable, values, tx, errorCallback) {
sync.log.trace("Entering kony.sync.replaceautogeneratedPK ");
var id = null;
var pkTab = {};
if(!kony.sync.isNullOrUndefined(synctable.Pk_Columns)){
for (var i = 0; i < synctable.Pk_Columns.length; i++){
var pk = synctable.Pk_Columns[i];
if (synctable.ColumnsDic[pk].Autogenerated === "true") {
id = kony.sync.getLastGeneratedID(sname, tx, errorCallback);
if (id === false) {
return false;
}
id = id - 1;
if (synctable.ColumnsDic[pk].type === "string") {
id = id.toString();
}
values[pk] = id;
pkTab[pk] = id;
if (!kony.sync.setLastGeneratedID(sname, id, tx, errorCallback)) {
return false;
}
} else {
pkTab[pk] = values[pk];
}
}
}
//implemented for composite primary key
return pkTab;
};
kony.sync.CreateCopy = function (tab) {
sync.log.trace("Entering kony.sync.CreateCopy ");
if (kony.sync.isNullOrUndefined(tab)){
return null;
}
var copy = [];
for (var key in tab) {
var value = tab[key];
if (kony.sync.isValidJSTable(value)) {
copy[key] = kony.sync.CreateCopy(tab[key]);
} else {
copy[key] = tab[key];
}
}
return copy;
};
kony.sync.getautogeneratePK = function (sname, synctable) {
sync.log.trace("Entering kony.sync.getautogeneratePK ");
var agPKs = [];
if(!kony.sync.isNullOrUndefined(synctable.Pk_Columns)){
for (var i = 0; i < synctable.Pk_Columns.length; i++) {
var pk = synctable.Pk_Columns[i];
if ((synctable.ColumnsDic[pk].Autogenerated === "true")) {
kony.table.insert(agPKs, pk);
}
}
}
return agPKs;
};
kony.sync.getDBNamefromDataSource = function (dsname) {
sync.log.trace("Entering kony.sync.getDBNamefromDataSource ");
sync.log.debug("validatint dsname : ",dsname);
for (var i in konysyncClientSyncConfig.ArrayOfDataSource) {
var datasource = konysyncClientSyncConfig.ArrayOfDataSource[i];
sync.log.debug("datasource.type:" + datasource.type + ":datasource.ID:" + datasource.ID);
if ((datasource.type === "database" && datasource.ID === dsname)) {
return datasource.Database.DatabaseName;
}
}
return null;
};
kony.sync.getAppId = function () {
sync.log.trace("Entering kony.sync.getAppId ");
return kony.sync.currentSyncConfigParams.appid;
};
kony.sync.getBatchSize = function () {
sync.log.trace("Entering kony.sync.getBatchSize ");
if(!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams.batchsize)) {
return kony.sync.currentSyncConfigParams.batchsize;
}
if (kony.os.deviceInfo().name === "blackberry") {
return "50";
} else {
return "500";
}
};
kony.sync.resetsyncsessionglobals = function (opName) {
sync.log.trace("Entering kony.sync.resetsyncsessionglobals ");
kony.sync.currentScope = null;
kony.sync.currentSyncReturnParams = {};
kony.sync.isSyncStopped = false;
if(opName==="startSession"){
kony.sync.currentSyncReturnParams[kony.sync.uploadURL] = kony.sync.getUploadURL();
kony.sync.currentSyncReturnParams[kony.sync.downloadURL] = kony.sync.getDownloadURL();
}
kony.sync.currentSyncLog = [];
};
kony.sync.resetscopesessionglobals = function (CallBack) {
var isError = false;
function clearSchemaUpgradeContext(tx){
//resetting the schemaupgrade flag once the download of the columns is done in memory and in db
kony.sync.schemaUpgradeContext = null;
var sql = "update " + kony.sync.syncConfigurationTableName + " set " +
kony.sync.syncConfigurationColumnSchemaUpgradeContext + " = null";
if (kony.sync.executeSql(tx, sql, null) === false) {
isError = true;
return;//error
}
sync.log.info("schemaupgrade context cleared successfully in memory and db");
}
function clearSchemaSuccessCallBack(){
CallBack(true);
}
function dbErrorCallBack(errInfo){
sync.log.error("error in opening db connection " +JSON.stringify(errInfo));
clearSchemaErrorCallBack(errInfo);
}
function clearSchemaErrorCallBack(errInfo){
sync.log.error("failed to clear schemaupgradeinfo in synconfigtable after dsc " +JSON.stringify(errInfo));
kony.sync.isErrorInAnyScope = true;
CallBack(true);
}
sync.log.trace("Entering kony.sync.resetscopesessionglobals ");
kony.sync.syncPendingBatchesNo = 0;
delete kony.sync.currentSyncReturnParams[kony.sync.batchContext];
delete kony.sync.currentSyncReturnParams[kony.sync.uploadContext];
if(kony.sync.currentScope === null) {
kony.sync.currentScope = kony.sync.scopes[0]; //- Start 1st Scope Sync
CallBack(false);
}else{
sync.log.debug("Scope index: ", kony.sync.currentScope.Index);
sync.log.debug("Scope count: ", kony.sync.scopes.scopecount);
if (kony.sync.currentScope.Index === kony.sync.scopes.scopecount - 1) {
if(!kony.sync.isNullOrUndefined(kony.sync.schemaUpgradeContext)){
var dbName = kony.sync.currentScope[kony.sync.scopeDataSource];
var conn = kony.sync.getConnectionOnly(dbName,dbName,dbErrorCallBack);
if(conn !== null){
kony.db.transaction(conn, clearSchemaUpgradeContext,clearSchemaErrorCallBack,clearSchemaSuccessCallBack);
}
}
else
CallBack(true);//Sync Complete
}
else{
kony.sync.currentScope = kony.sync.scopes[kony.sync.currentScope.Index + 1]; //Get Next Scope
CallBack(false);
}
}
};
kony.sync.resetuploadsessioglobals = function () {
sync.log.trace("Entering kony.sync.resetuploadsessioglobals ");
delete kony.sync.currentSyncReturnParams[kony.sync.uploadContext];
delete kony.sync.currentSyncReturnParams[kony.sync.lastSyncTimestamp];
delete kony.sync.currentSyncReturnParams[kony.sync.uploadSequenceNumber];
//sync_total_inserts = 0;
kony.sync.syncTotalInserts = 0;
kony.sync.syncTotalUpdates = 0;
kony.sync.syncTotalDeletes = 0;
kony.sync.serverInsertCount = 0;
kony.sync.serverUpdateCount = 0;
kony.sync.serverDeleteCount = 0;
kony.sync.serverInsertAckCount = 0;
kony.sync.serverUpdateAckCount = 0;
kony.sync.serverDeleteAckCount = 0;
kony.sync.serverFailedCount = 0;
kony.sync.uploadSummary = [];
};
kony.sync.resetbatchsessionglobals = function () {
sync.log.trace("Entering kony.sync.resetbatchsessionglobals ");
delete kony.sync.currentSyncReturnParams[kony.sync.batchContext];
delete kony.sync.currentSyncReturnParams[kony.sync.uploadContext];
delete kony.sync.currentSyncReturnParams[kony.sync.uploadSequenceNumber];
kony.sync.serverInsertCount = 0;
kony.sync.serverUpdateCount = 0;
kony.sync.serverDeleteCount = 0;
kony.sync.serverInsertAckCount = 0;
kony.sync.serverUpdateAckCount = 0;
kony.sync.serverDeleteAckCount = 0;
kony.sync.serverFailedCount = 0;
kony.sync.uploadSummary = [];
kony.sync.objectLevelInfoMap = {};
};
kony.sync.getSyncTable = function (tablename) {
sync.log.trace("Entering kony.sync.getSyncTable ");
var scopename = kony.sync.scopes.syncTableScopeDic[tablename];
return kony.sync.scopes[scopename].syncTableDic[tablename];
};
kony.sync.getCurrentVersionNumber = function (tbname) {
sync.log.trace("Entering kony.sync.getCurrentVersionNumber ");
var scopename = kony.sync.scopes.syncTableScopeDic[tbname];
return kony.sync.currentSyncScopesState[scopename];
};
kony.sync.getBackEndDBType = function () {
sync.log.trace("Entering kony.sync.getBackEndDBType ");
if (kony.sync.platformName === null) {
kony.sync.platformName = kony.os.deviceInfo().name;
}
if (kony.sync.platformName === "winmobile") {
return kony.sync.dbTypeSQLCE;
}
return kony.sync.dbTypeSQLLite;
};
kony.sync.printScopeLog = function () {
sync.log.trace("Entering kony.sync.printScopeLog ");
sync.log.info("Sync complete");
sync.log.info("----------------------------------------------------");
for (var i = 0; i < kony.sync.currentSyncLog.length; i++) {
var batch = kony.sync.currentSyncLog[i];
sync.log.info("Batch No: ", i);
sync.log.info("Batch log: ", batch);
}
sync.log.info("----------------------------------------------------");
};
//To generate hash
kony.sync.genHash = function (hashType, plaintext) {
sync.log.trace("Entering kony.sync.genHash ");
//return same in case of null/undefined plaintext
if (kony.sync.isNull(plaintext)) {
return plaintext;
}
//if hashType is callback, get the value from it
if(kony.sync.isValidFunctionType(hashType)){
return hashType(plaintext);
}
//convert plaintext to string if not already
plaintext = plaintext.toString();
//apply default value in case of invalid/null/undefined hashtype
if (kony.sync.isNull(hashType) || kony.string.equalsIgnoreCase(kony.type(hashType), "string")===false) {
return kony.crypto.createHash("sha256", plaintext);
}
//return same if hashtype is none
else if(kony.string.equalsIgnoreCase(hashType, "none")===true){
return plaintext;
}
//apply the desired hash algo
else{
return kony.crypto.createHash(hashType, plaintext);
}
};
kony.sync.tonumber = function(arg) {
sync.log.trace("Entering kony.sync.tonumber ");
if(kony.sync.isNullOrUndefined(arg)) {
return null;
}
//duplicating kony.os.toNumber in order to avoid Android platform dependency issues
if (arguments.length !== 1) {
throw new Error("Invalid argument to os.toNumber");
}
if (typeof(arg) === "number") {
return arg;
} else if (typeof(arg) === "string") {
var str = arg.replace(/^\s*/, '').replace(/\s*$/, '');
if (str === '') {
return null;
} else {
var num = str - 0;
return (isNaN(num) ? null : num);
}
} else {
return null;
}
};
kony.sync.filterNullsFromSelectResult = function(res){
sync.log.trace("Entering kony.sync.filterNullsFromSelectResult ");
if(kony.sync.enableORMValidations){
var tableToMap = [ ];
for (var j in res){
var u = res[j];
var rowToMap = {};
for(var k in u){
var v = u[k];
if(!kony.sync.isNull(v)){
rowToMap[k] = v;
}
}
kony.table.insert(tableToMap, rowToMap);
}
return tableToMap;
}
else{
return res;
}
};
kony.sync.getAsyncDownloadBatchSize = function () {
sync.log.trace("Entering kony.sync.getAsyncDownloadBatchSize ");
if(!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams.asyncbatchsize)){
return kony.sync.currentSyncConfigParams.asyncbatchsize;
}
return 50;
};
kony.sync.isApplyChangesSync = function () {
sync.log.trace("Entering kony.sync.isApplyChangesSync ");
var returnVal;
//#ifdef bb
returnVal = false;
//#else
returnVal = true;
//#endif
return returnVal;
};
kony.sync.getChangeTypeForUploadTrue = function(type) {
sync.log.debug("ValueSentForChange: ", type);
if(typeof(type) === "number"){
type = type.toString();
}
if (type === "90") {
return "0";
}
if (type === "91") {
return "1";
}
if (type === "92") {
return "2";
}
return type;
};
//Checking whether table is defined for delete after upload or not
kony.sync.checkForDeleteAfterUpload = function (tablename, scopename) {
sync.log.trace("Entering kony.sync.checkForDeleteAfterUpload ");
var i = null;
var myTab = kony.sync.currentSyncConfigParams[kony.sync.removeAfterUpload];
if(kony.sync.isNullOrUndefined(myTab)){
return false;
}
if(!kony.sync.isNullOrUndefined(scopename)){
if(kony.sync.isNullOrUndefined(myTab[scopename])){
return false;
}
if (myTab[scopename].length === 0){
return true;
}
for (i in myTab[scopename]){
if(myTab[scopename][i] === tablename){
return true;
}
}
} else {
for(i in myTab) {
for (var j in myTab[i]) {
if (myTab[i][j] === tablename) {
return true;
}
}
}
}
return false;
};
//checking for false updates
kony.sync.checkForFalseUpdate = function (dbname, tbname, twcs, markForUpload, errorcallback, successcallback) {
sync.log.trace("Entering kony.sync.checkForFalseUpdate ");
var uploadstatus = true;
var isError = false;
if(markForUpload === false){
return true;
} else {
kony.table.insert(twcs, {
key : kony.sync.historyTableChangeTypeColumn,
value : "90",
optype : "EQ",
comptype : "AND"
});
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.historyTableChangeTypeColumn]);
kony.sync.qb_from(query, tbname + "_history");
kony.sync.qb_where(query, twcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var connection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback, "check for false update");
if(connection !== null){
kony.sync.startTransaction(connection, transaction_callback, update_successcallback, single_transaction_error_callback, "check for false update");
}
}
function transaction_callback(tx) {
sync.log.trace("Entering kony.sync.checkForFalseUpdate transaction_callback");
var resultSet = kony.sync.executeSql(tx, sql, params, errorcallback);
if (resultSet !== false) {
var num_records = resultSet.rows.length;
if (num_records !== 0) {
sync.log.error("Record does not exist on server, mark it for upload before updating/deleting it");
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(kony.sync.errorCodeMarkForUpload, kony.sync.getErrorMessage(kony.sync.errorCodeMarkForUpload), null));
uploadstatus = false;
} else {
uploadstatus = true;
}
} else {
//return;
isError = true;
}
}
function update_successcallback() {
sync.log.trace("Entering kony.sync.checkForFalseUpdate update_successcallback");
if (!isError && uploadstatus === true) {
successcallback();
}
}
function single_transaction_error_callback() {
sync.log.error("Entering kony.sync.checkForFalseUpdate single_transaction_error_callback");
if (!isError) {
sync.log.error("Transaction error occurred", "check for false update");
kony.sync.showTransactionError(errorcallback, "check for false update");
}else{
sync.log.error("Transaction error occurred", kony.sync.errorObject);
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
};
kony.sync.checkForFalseUpdateWCS = function (dbname, tbname, twcs, markForUpload, errorcallback, successcallback) {
sync.log.trace("Entering kony.sync.checkForFalseUpdateWCS ");
var uploadstatus = true;
var isError = false;
if (markForUpload === false) {
return true;
}
if(twcs !== "" && !kony.sync.isNull(twcs)){
twcs = twcs + " AND " + kony.sync.historyTableChangeTypeColumn + " = 90";
}
else{
twcs = " where " + kony.sync.historyTableChangeTypeColumn + " = 90";
}
var sql = "select " + kony.sync.historyTableChangeTypeColumn + " from " + tbname + "_history " + twcs;
var connection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback, "check for false update WCS");
if(connection !== null){
kony.sync.startTransaction(connection, transaction_callback, update_successcallback, update_failurecallback, "check for false update WCS");
}
function transaction_callback(tx) {
sync.log.trace("Entering kony.sync.checkForFalseUpdateWCS transaction_callback");
var resultSet = kony.sync.executeSql(tx, sql, null, errorcallback);
if (resultSet !== false){
var num_records = resultSet.rows.length;
if (num_records !== 0){
sync.log.error("Record does not exist on server, mark it for upload before updating/deleting it");
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(kony.sync.errorCodeMarkForUpload, kony.sync.getErrorMessage(kony.sync.errorCodeMarkForUpload), null));
uploadstatus = false;
} else {
uploadstatus = true;
}
} else {
isError = true;
}
}
function update_successcallback() {
sync.log.trace("Entering kony.sync.checkForFalseUpdateWCS update_successcallback");
if (!isError && uploadstatus === true) {
successcallback();
}
}
function update_failurecallback() {
sync.log.trace("Entering kony.sync.checkForFalseUpdateWCS update_failurecallback");
if (!isError && uploadstatus === true){
sync.log.error("Transaction error occurred : ", "check for false update WCS");
kony.sync.showTransactionError(errorcallback,"check for false update WCS");
}else{
sync.log.error("Transaction error occurred : ", kony.sync.errorObject);
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
};
kony.sync.getConnection = function (dbName, displayName, transactionCallBack, successCallBack, errorCallBack) {
sync.log.trace("Entering kony.sync.getConnection ");
var connection = kony.sync.getConnectionOnly(dbName, displayName, errorCallBack);
if(connection!==null){
kony.db.transaction(connection, transactionCallBack, errorCallBack, successCallBack);
}
};
//This function starts a transaction given a connection
kony.sync.startTransaction = function (connection, transactionCallBack, successCallBack, errorCallBack) {
sync.log.trace("Entering kony.sync.startTransaction ");
kony.db.transaction(connection, transactionCallBack, errorCallBack, successCallBack);
};
kony.sync.showTransactionError = function (errorCallBack, moduleName){
sync.log.trace("Entering kony.sync.showTransactionError ");
if(kony.sync.isNullOrUndefined(moduleName)){
moduleName = "";
}
sync.log.fatal(moduleName + ":" + " Db connection is null");
kony.sync.verifyAndCallClosure(errorCallBack, kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
};
kony.sync.checkIntegrity = function (dbname, rMap, successCallback, errorCallBack) {
sync.log.trace("Entering kony.sync.checkIntegrity ");
if(!kony.sync.enableORMValidations){
kony.sync.verifyAndCallClosure(successCallback);
return;
}
var status = true;
var isError = false;
var integrityFailedMap = null;
var connection = kony.sync.getConnectionOnly(dbname, dbname, errorCallBack, "Checking integrity");
if(connection !== null){
kony.sync.startTransaction(connection, integrityTransaction, integritySuccess, integrityFailure, "Checking Referential Integrity Constraints");
}
function integrityTransaction(tx) {
integrityFailedMap = kony.sync.checkIntegrityinTransaction(tx,rMap);
}
function integritySuccess() {
var error = "";
if (integrityFailedMap === true) {
kony.sync.verifyAndCallClosure(successCallback);
}
else{
for(var key in integrityFailedMap){
error = error + integrityFailedMap[key];
}
kony.sync.verifyAndCallClosure(errorCallBack, kony.sync.getErrorTable(kony.sync.errorCodeReferentialIntegrity, error));
}
}
function integrityFailure() {
if (!integrityFailedMap) {
kony.sync.showTransactionError(errorCallBack,"Checking integrity");
}else{
kony.sync.verifyAndCallClosure(errorCallBack, kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
};
kony.sync.checkIntegrityinTransaction_old = function (tx, rMap) {
sync.log.trace("Entering kony.sync.checkIntegrityinTransaction ");
var integrityFailedMap = {};
if(!kony.sync.enableORMValidations){
return true;
}
for(var obj in rMap){
for (var key in rMap[obj]) {
if (kony.sync.isNull(rMap[obj][key].targetAttributeValue)) {
continue;
}
if(integrityFailedMap[rMap[obj][key].foreignKeyAttribute] === false){
continue;
}
if(rMap[obj][key].targetAttributeValue === ""){
rMap[obj][key].targetAttributeValue = "''";
}
var sql = "select * from " + obj + " where " + rMap[obj][key].sourceAttribute[0] + " = " + rMap[obj][key].targetAttributeValue[0] + "";
var resultSet = kony.sync.executeSql(tx, sql, null);
if (resultSet !== false) {
if (resultSet.rows.length === 0) {
sync.log.error("Referential Integrity Check Failed", kony.sync.getErrorTable(kony.sync.errorCodeReferentialIntegrity, kony.sync.getReferetialIntegrityerrMessg(obj, rMap[obj][key].sourceAttribute, rMap[obj][key].targetAttributeValue)));
if(kony.sync.isNullOrUndefined(integrityFailedMap[rMap[obj][key].foreignKeyAttribute])){
integrityFailedMap[rMap[obj][key].foreignKeyAttribute] = kony.sync.getReferetialIntegrityerrMessg(obj, rMap[obj][key].sourceAttribute, rMap[obj][key].targetAttributeValue);
}else{
integrityFailedMap[rMap[obj][key].foreignKeyAttribute] = integrityFailedMap[rMap[obj][key].foreignKeyAttribute] + kony.sync.getReferetialIntegrityerrMessg(obj, rMap[obj][key].sourceAttribute, rMap[obj][key].targetAttributeValue);
}
}else {
integrityFailedMap[rMap[obj][key].foreignKeyAttribute] = false;
}
} else {
return false;
}
}
}
var logicalBreak = false;
for(var key in integrityFailedMap){
if(integrityFailedMap[key] !== false){
logicalBreak = true;
}
}
return logicalBreak === false?true:integrityFailedMap;
};
kony.sync.checkIntegrityinTransaction = function (tx, rMap) {
sync.log.trace("Entering kony.sync.checkIntegrityinTransactionFK ");
var integrityFailedMap = {};
if(!kony.sync.enableORMValidations){
return true;
}
for(var obj in rMap){
for (var key in rMap[obj]) {
var relationShipMap = rMap[obj][key];
var whereClause = " where ";
for (var i = 0; i < relationShipMap.targetAttributeValue.length; i++) {
if (kony.sync.isNull(relationShipMap.targetAttributeValue[i])) {
continue;
}
if(integrityFailedMap[relationShipMap.foreignKeyAttribute[i]] === false){
continue;
}
if(relationShipMap.targetAttributeValue[i] === ""){
relationShipMap.targetAttributeValue[i] = "''";
}
whereClause = whereClause + relationShipMap.sourceAttribute[i] + " = " + relationShipMap.targetAttributeValue[i];
if(i != relationShipMap.targetAttributeValue.length - 1) {
whereClause = whereClause + " AND ";
}
};
var sql = "select * from " + obj + whereClause + "";
var resultSet = kony.sync.executeSql(tx, sql, null);
if (resultSet !== false) {
if (resultSet.rows.length === 0) {
sync.log.error("Referential Integrity Check Failed", kony.sync.getErrorTable(kony.sync.errorCodeReferentialIntegrity, kony.sync.getReferetialIntegrityerrMessg(obj, relationShipMap.sourceAttribute, relationShipMap.targetAttributeValue)));
integrityFailedMap[relationShipMap.foreignKeyAttribute[0]] = kony.sync.getReferetialIntegrityerrMessg(obj, relationShipMap.sourceAttribute, relationShipMap.targetAttributeValue);
}
else{
integrityFailedMap[relationShipMap.foreignKeyAttribute[0]] = false;
}
} else {
return false;
}
}
}
var logicalBreak = false;
for(var key in integrityFailedMap){
if(integrityFailedMap[key] !== false){
logicalBreak = true;
}
}
return logicalBreak === false?true:integrityFailedMap;
};
kony.sync.convertOrderByMapToValuesTable = function (orderByMap) {
sync.log.trace("Entering kony.sync.convertOrderByMapToValuesTable ");
var valuesTable = {};
for (var i in orderByMap) {
valuesTable[orderByMap[i].key] = orderByMap[i].key;
}
return valuesTable;
};
kony.sync.convertToValuesTableOrderByMap = function (orderByMap, valuesTable) {
sync.log.trace("Entering kony.sync.convertToValuesTableOrderByMap ");
var orderByMapFiltered = [];
var j = 0;
for(var i in orderByMap) {
if (valuesTable[orderByMap[i].key] === orderByMap[i].key) {
orderByMapFiltered[j] = orderByMap[i];
j++;
}
}
return orderByMapFiltered;
};
kony.sync.isValidFunctionType = function (closure) {
sync.log.trace("Entering kony.sync.isValidFunctionType ");
return kony.type(closure) === "function";
};
kony.sync.initializeScopeSettings = function (tx) {
sync.log.trace("Entering kony.sync.initializeScopeSettings ");
var query = kony.sync.qb_createQuery();
var json = "{\"scopeSettings\" : {}}";
kony.sync.qb_set(query, {
"id" : 1,
"action" : "",
"details" : json
});
kony.sync.qb_insert(query, "konysyncDIAGNOSTICS");
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
};
kony.sync.updateScopeSettings = function (tx, scopename) {
sync.log.trace("Entering kony.sync.updateScopeSettings ");
var resultset = kony.sync.executeSql(tx, "select * from konysyncDIAGNOSTICS");
if(resultset === false){
return false;
}
var settings = "";
var rowItem = null;
if(resultset.rows.length > 0){
rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
settings = rowItem.details;
}else{
sync.log.error("Updation of Scope Settings Failed");
}
var table = JSON.parse(settings);
if(kony.sync.isNullOrUndefined(table.scopeSettings[scopename])){
table.scopeSettings[scopename] = {
"initialize" : true
};
}else if(kony.sync.isNullOrUndefined(table.scopeSettings[scopename].initialize)) {
table.scopeSettings[scopename].initialize = true;
}
var query = kony.sync.qb_createQuery();
var json = JSON.stringify(table);
kony.sync.qb_set(query, {
"details" : json
});
kony.sync.qb_update(query, "konysyncDIAGNOSTICS");
kony.sync.qb_where(query, [{
"key" : "id",
"value" : 1
}
]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
};
kony.sync.getScopeSettings = function (scopename, dbname, callback, errorcallback) {
sync.log.trace("Entering kony.sync.getScopeSettings ");
var settings = null;
var isError = false;
function getSettingsTransaction(tx) {
var resultset = kony.sync.executeSql(tx, "select * from konysyncDIAGNOSTICS");
var set = "";
var rowItem = null;
if (resultset !== false) {
if (resultset.rows.length > 0) {
rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
set = rowItem.details;
} else {
sync.log.error("Updation of Scope Settings Failed");
}
} else {
sync.log.error("Updation of Scope Settings Failed");
isError = true;
return;
}
var table = JSON.parse(set);
if(!kony.sync.isNullOrUndefined(table.scopeSettings[scopename])) {
settings = table.scopeSettings[scopename];
}
}
function getSettingsCompleted() {
callback(settings);
}
function getSettingsFailed() {
kony.sync.callTransactionError(isError, errorcallback);
}
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, getSettingsFailed, "getScopeSettings");
if(dbconnection !== null){
kony.sync.startTransaction(dbconnection, getSettingsTransaction, getSettingsCompleted, getSettingsFailed);
}
};
kony.sync.isScopeInitialized = function (scopename, dbname, callback) {
sync.log.trace("Entering kony.sync.isScopeInitialized ");
function localcallback(settings) {
if (settings !== null){
if(settings.initialize === true) {
callback(true);
} else {
callback(false);
}
} else {
callback(false);
}
}
function errorCallback(res){
kony.sync.onDownloadCompletion(true, res);
}
var settings = kony.sync.getScopeSettings(scopename, dbname, localcallback, errorCallback);
};
kony.sync.setPragmaSize = function (tx) {
sync.log.trace("Entering kony.sync.setPragmaSize ");
return kony.sync.executeSql(tx, "PRAGMA CACHE_SIZE=50");
};
kony.sync.isValidJSTable = function(inputTable) {
if (kony.sync.isNullOrUndefined(inputTable)) {
return false;
}
return kony.type(inputTable) === "object" || kony.type(inputTable) === "Object" || kony.type(inputTable) === "Array";
};
kony.sync.isNull = function (val) {
sync.log.trace("Entering kony.sync.isNull ");
if (kony.sync.isNullOrUndefined(val)){
return true;
}
val = val + "";
return (kony.string.equalsIgnoreCase(val, "null"));
};
//returns whether a error upload policy is continueonerror or not
kony.sync.isUploadErrorPolicyCOE = function (currentScope) {
sync.log.trace("Entering kony.sync.isUploadErrorPolicyCOE ");
var scopename = currentScope.ScopeName;
//Added these redundant checks to check for OTA or Persistent Sync. As proper checks
//have not made in earlier implementation, we are doing this to avoid any backward compatibility issues.
if(currentScope[kony.sync.syncStrategy] === kony.sync.syncStrategy_OTA) {
if (currentScope[kony.sync.syncStrategy] === kony.sync.syncStrategy_OTA &&
!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks]) &&
!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][scopename])&&
kony.string.equalsIgnoreCase(kony.sync.getString(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][scopename][kony.sync.sessionTaskUploadErrorPolicy]), kony.sync.sessionTaskUploadErrorPolicyCOE)){
return true;
}
return false;
}else {
if (currentScope[kony.sync.syncStrategy] !== kony.sync.syncStrategy_OTA &&
!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks]) &&
!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][scopename])&&
kony.string.equalsIgnoreCase(kony.sync.getString(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][scopename][kony.sync.sessionTaskUploadErrorPolicy]), kony.sync.sessionTaskUploadErrorPolicyCOE)){
return true;
}
return false;
}
};
kony.sync.isEmptyString = function (val) {
sync.log.trace("Entering kony.sync.isEmptyString ");
if(!kony.sync.isNullOrUndefined(val) && typeof(val)==="string" && val.trim()==="") {
return true;
} else {
return false;
}
};
kony.sync.isValidNumberType = function (val) {
sync.log.trace("Entering kony.sync.isValidNumberType ");
if (kony.string.equalsIgnoreCase(kony.type(val), "number")){
return true;
}
else if (kony.string.equalsIgnoreCase(kony.type(val), "string") && null !== kony.sync.tonumber(val)){
return true;
}
else{
return false;
}
};
kony.sync.isValidBooleanType = function (val) {
sync.log.trace("Entering kony.sync.isValidBooleanType ");
if (kony.string.equalsIgnoreCase(kony.type(val), "boolean")) {
return true;
} else if (kony.string.equalsIgnoreCase(kony.type(val), "string")) {
if (kony.string.equalsIgnoreCase(val, "false") || kony.string.equalsIgnoreCase(val, "true") || kony.string.equalsIgnoreCase(val, "0") || kony.string.equalsIgnoreCase(val, "1")) {
return true;
}
} else if (kony.string.equalsIgnoreCase(kony.type(val), "number")) {
if (val === 0 || val === 1) {
return true;
}
}
return false;
};
kony.sync.isMaliciousType = function (val) {
sync.log.trace("Entering kony.sync.isMaliciousType ");
if (kony.sync.isValidNumberType(val) && isNaN(val)){
return "NaN";
}
if (val === Number.POSITIVE_INFINITY || val === Number.NEGATIVE_INFINITY){
return "infinity";
}
return false;
};
kony.sync.genMaliciousTypeCheck = function (obj, errorcallback) {
sync.log.trace("Entering kony.sync.genMaliciousTypeCheck ");
if(!kony.sync.enableORMValidations){
return false;
}
var errorMessage = null;
var maliciousType = null;
if (kony.string.equalsIgnoreCase(kony.type(obj), "object") || kony.string.equalsIgnoreCase(kony.type(obj), "table")) {
for (var i in obj) {
maliciousType = kony.sync.isMaliciousType(obj[i]);
if (maliciousType !== false) {
errorMessage = kony.sync.getErrorMessage(kony.sync.errorCodeMaliciousType, i, maliciousType);
sync.log.error("Malicious object detected", kony.sync.getErrorTable(kony.sync.errorCodeMaliciousType, errorMessage));
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(kony.sync.errorCodeMaliciousType, errorMessage));
return true;
} else {
if (obj[i] === undefined){
obj[i] = "null";
}
}
}
} else {
maliciousType = kony.sync.isMaliciousType(obj);
if (maliciousType !== false) {
errorMessage = kony.sync.getErrorMessage(kony.sync.errorCodeMaliciousType, "", maliciousType);
sync.log.error("Malicious object detected", kony.sync.getErrorTable(kony.sync.errorCodeMaliciousType, errorMessage));
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(kony.sync.errorCodeMaliciousType, errorMessage));
return true;
}
}
return false;
};
kony.sync.getBoolean = function (val) {
sync.log.trace("Entering kony.sync.getBoolean ");
if (kony.sync.isValidBooleanType(val)) {
val = val + "";
if (kony.string.equalsIgnoreCase(val, "true") || kony.string.equalsIgnoreCase(val, "1") || val === 1) {
return true;
} else {
return false;
}
} else {
return val;
}
};
kony.sync.getString = function (val) {
sync.log.trace("Entering kony.sync.getString ");
if (kony.sync.isNull(val)) {
return "";
}
return val.toString();
};
kony.sync.getUploadStatus = function (markForUpload) {
sync.log.trace("Entering kony.sync.getUploadStatus ");
if (markForUpload === false || markForUpload === "false") {
return false;
} else {
return true;
}
};
kony.sync.getDBName = function () {
sync.log.trace("Entering kony.sync.getDBName ");
var syncscopes = konysyncClientSyncConfig.ArrayOfSyncScope;
if(syncscopes === null){
return null;
}
for (var i = 0; i < syncscopes.length; i++) {
var scope = syncscopes[i];
//This logic needs to be changed when we have separate DB for each scope
if (scope[kony.sync.scopeDataSource] !== null) {
return scope[kony.sync.scopeDataSource];
}
}
return null;
};
kony.sync.mergeTable = function (toObj, frmObj) {
sync.log.trace("Entering kony.sync.mergeTable ");
if (!kony.sync.isValidJSTable(frmObj)) {
return toObj;
}
if (!kony.sync.isValidJSTable(toObj)) {
return frmObj;
}
for (var k in frmObj) {
toObj[k] = frmObj[k];
}
return toObj;
};
kony.sync.pkNotFoundErrCallback = function(errorcallback, objName){
sync.log.trace("Entering kony.sync.pkNotFoundErrCallback ");
sync.log.error("No data with specified primary key found in SyncObject " + objName + ".");
errorcallback(kony.sync.getErrorTable(kony.sync.errorCodeNoDataWithPrimaryKey, kony.sync.getErrorMessage(kony.sync.errorCodeNoDataWithPrimaryKey, objName)));
};
kony.sync.skyEventObserver = function (event, args, eventFinishCallback, errorcallback, isCascade) {
sync.log.trace("Entering kony.sync.skyEventObserver ");
if (event !== "START") {
if (event === "ERROR") {
if (!kony.sync.isNull(args)) {
if (isCascade) {
sky.rollbackTransaction(kony.sky.skyEmptyFunction);
}
var errorCode = args.ERRORCODE;
var errorMsg = args.ERRORDESC;
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(errorCode, errorMsg));
}
}
if (event === "FINISH") {
kony.sync.verifyAndCallClosure(eventFinishCallback, args);
}
}
};
kony.sync.removeCascadeHelper_old = function (tx, srcAttribute, targetAttribute, tbname, wcs, targetObjectRemoveCascade, targetObjectName, isCascade, errorcallback, markForUpload, pkRecord, isLocal) {
sync.log.trace("Entering kony.sync.removeCascadeHelper_old ");
var wcsCascade = null;
if (pkRecord === null) {
var sqlTarget = "select " + srcAttribute + " from " + tbname + wcs;
var resultSet = kony.sync.executeSql(tx, sqlTarget, null);
if (resultSet === false) {
return false;
}
var num_records = resultSet.rows.length;
if (num_records === 0) {
return true;
}
if (isCascade) {
sync.log.debug("No of Records to be deleted in " + targetObjectName + " for cascade delete=" + num_records);
}
for (var i = 0; i <= num_records - 1; i++) {
var record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
wcsCascade = " where " + targetAttribute + " = '" + record[srcAttribute] + "'";
if (targetObjectRemoveCascade(tx, wcsCascade, errorcallback, markForUpload, isCascade, tbname, isLocal) === false) {
return false;
}
}
} else {
wcsCascade = " where " + targetAttribute + " = '" + pkRecord[srcAttribute] + "'";
return targetObjectRemoveCascade(tx, wcsCascade, errorcallback, markForUpload, isCascade, tbname, isLocal);
}
return true;
};
kony.sync.removeCascadeHelper = function (tx,srcAttributes,targetAttributes, tbname, wcs, targetObjectRemoveCascade, targetObjectName, isCascade, errorcallback, markForUpload, pkRecord, isLocal) {
sync.log.trace("Entering kony.sync.removeCascadeHelper ");
var wcsCascade = null;
if (pkRecord === null) {
var sqlTarget = "select ";
var sourceAttribute = "";
for (var i = 0; i < srcAttributes.length; i++) {
sourceAttribute = sourceAttribute + srcAttributes[i];
if(i != srcAttributes.length - 1) {
sourceAttribute = sourceAttribute + ","
}
};
sqlTarget = sqlTarget + sourceAttribute + " from " + tbname + wcs;
var resultSet = kony.sync.executeSql(tx, sqlTarget, null);
if (resultSet === false) {
return false;
}
var num_records = resultSet.rows.length;
if (num_records === 0) {
return true;
}
if (isCascade) {
sync.log.debug("No of Records to be deleted in " + targetObjectName + " for cascade delete=" + num_records);
}
wcsCascade = " where ";
for (var i = 0; i <= num_records - 1; i++) {
var record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
var srcAttributesLen = srcAttributes.length;
for (var j = 0; j < srcAttributesLen ; ++j) {
wcsCascade = wcsCascade + targetAttributes[j] + " = '" + record[srcAttributes[j]] + "'"
if(j != srcAttributesLen - 1) {
wcsCascade = wcsCascade + " and "
}
}
if(i != num_records - 1) {
wcsCascade = wcsCascade + " or " ;
}
}
if (targetObjectRemoveCascade(tx, wcsCascade, errorcallback, markForUpload, isCascade, tbname, isLocal) === false) {
return false;
}
}
else {
wcsCascade = " where ";
var srcAttributesLen = srcAttributes.length;
for (var j = 0; j < srcAttributesLen ; j++) {
wcsCascade = wcsCascade + targetAttributes[j] + " = '" + pkRecord[srcAttributes[j]] + "'"
if(j != srcAttributesLen - 1) {
wcsCascade = wcsCascade + " and "
}
}
return targetObjectRemoveCascade(tx, wcsCascade, errorcallback, markForUpload, isCascade, tbname, isLocal);
}
return true;
};
kony.sync.rollbackTransaction = function (tx) {
sync.log.trace("Entering kony.sync.rollbackTransaction ");
function dummyError() {
//rollback the transaction
return true;
}
//dummy statement
kony.db.executeSql(tx, "dummy", null, dummyError);
};
//Wrapper for kony.db.executeSql
kony.sync.executeSql = function (tx, sql, params, errorCallback, rollback, opMsg) {
sync.log.trace("Entering kony.sync.executeSql ");
kony.sync.errorObject = null;
if (!kony.sync.isNullOrUndefined(opMsg)) {
sync.log.debug(opMsg);
}
sync.log.debug("SQL Query : ", sql);
sync.log.debug("SQL Params : ", params);
var result = kony.db.executeSql(tx, sql, params, localErrorCallback);
if (result === null) {
sync.log.error("Query execution failed: " + sql + " with params : ",params);
return false;
} else {
sync.log.debug("Query execution success: "+ sql + " with params : ",params);
sync.log.debug("Result of query execution is: ", result);
return result;
}
function localErrorCallback(tx, res) {
var errorInfo = {};
errorInfo[kony.sync.errorInfoTransactionID] = tx;
errorInfo[kony.sync.errorInfoDatabaseError] = res;
sync.log.error("SQLite Error : ", res);
kony.sync.errorObject = kony.sync.getErrorTable(kony.sync.errorCodeSQLStatement, kony.sync.getErrorMessage(kony.sync.errorCodeSQLStatement), errorInfo);
// kony.sync.verifyAndCallClosure(errorCallback, kony.sync.getErrorTable(kony.sync.errorCodeSQLStatement, kony.sync.getErrorMessage(kony.sync.errorCodeSQLStatement), errorInfo));
if (rollback === false) {
return false;
} else {
return true;
}
}
};
kony.sync.callTransactionError = function(isError, errorcallback){
sync.log.trace("Entering kony.sync.callTransactionError ");
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getTransactionError(isError));
};
kony.sync.validateWhereClause = function(wcs){
sync.log.trace("Entering kony.sync.validateWhereClause ");
if(!kony.sync.enableORMValidations){
return wcs;
}
if(kony.sync.isNull(wcs)){
return "";
}
wcs = kony.sync.getString(wcs);
wcs = kony.string.trim(wcs);
var twcs = kony.string.lower(wcs);
if(twcs !== ""){
// check if the where clause starts with a reserved keyword, else append "where" keyword
if(!kony.sync.startsWithKeyword(twcs)){
wcs = " where " + wcs;
}
}
return wcs;
};
//check whether the given data contains the key
kony.sync.contains = function(data, key){
sync.log.trace("Entering kony.sync.contains ");
//currently implementing for array only
for(var i in data){
if(data[i]===key){
return true;
}
}
return false;
};
kony.sync.createHash = function(hash, plaintext){
sync.log.trace("Entering kony.sync.createHash ");
return kony.crypto.createHash(hash, plaintext);
};
kony.sync.getChunkDownloadURL = function(){
sync.log.trace("Entering kony.sync.getChunkDownloadURL ");
var server = kony.sync.getServerURL();
return server + "downloadchunk";
};
kony.sync.getUploadBatchSize = function(){
sync.log.trace("Entering kony.sync.getUploadBatchSize ");
if (kony.sync.isValidNumberType(kony.sync.currentSyncConfigParams.uploadbatchsize)) {
return kony.sync.tonumber(kony.sync.currentSyncConfigParams.uploadbatchsize);
}
return 50; //default batch size
};
kony.sync.isValidJSTable = function (inputTable){
if (kony.sync.isNullOrUndefined(inputTable)) {
return false;
}
if (kony.type(inputTable) === "object" || kony.type(inputTable) === "Array") {
return true;
} else {
return false;
}
};
kony.sync.deleteMapKey = function(map, key){
sync.log.trace("Entering kony.sync.deleteMapKey ");
if(!kony.sync.isNull(map) && !kony.sync.isNull(key)){
delete map[key];
}
};
kony.sync.getServerDetailsHostName = function(response){
sync.log.trace("Entering kony.sync.getServerDetailsHostName ");
if(!kony.sync.isNullOrUndefined(response) && !kony.sync.isNullOrUndefined(response.d) && !kony.sync.isNullOrUndefined(response.d.server)){
return response.d.server.hostName;
}else{
return null;
}
};
kony.sync.getServerDetailsIpAddress = function(response){
sync.log.trace("Entering kony.sync.getServerDetailsIpAddress ");
if(!kony.sync.isNullOrUndefined(response) && !kony.sync.isNullOrUndefined(response.d) && !kony.sync.isNullOrUndefined(response.d.server)){
return response.d.server.ipAddress;
}else{
return null;
}
};
kony.sync.addServerDetails = function(returnParams, serverResponse){
if(!kony.sync.isNullOrUndefined(returnParams)){
returnParams[kony.sync.serverDetails] = {};
returnParams[kony.sync.serverDetails][kony.sync.hostName] = kony.sync.getServerDetailsHostName(serverResponse);
returnParams[kony.sync.serverDetails][kony.sync.ipAddress] = kony.sync.getServerDetailsIpAddress(serverResponse);
}
};
//This function gets connection
kony.sync.getConnectionOnly = function(dbName, displayName, errorCallback, moduleName) {
sync.log.trace("Entering kony.sync.getConnectionOnly ");
var estimatedDBSize = 5 * 1024 * 1024;
var connection = null;
var version = "1.0";
var exceptionObject = null;
function makeEncryptedConnection(){
if(kony.sync.deviceDBEncryptionKey===null){
connection = kony.db.openDatabaseSync(dbName, version, displayName, estimatedDBSize);
}
else{
sync.log.info("Opening encrypted connection", kony.sync.deviceDBEncryptionKey);
connection = kony.db.openDatabaseSync(dbName, version, displayName, estimatedDBSize, kony.sync.deviceDBEncryptionKey);
}
}
try{
//#ifdef KONYSYNC_ENCRYPTION_AVAILABLE
makeEncryptedConnection();
//#else
connection = kony.db.openDatabaseSync(dbName, version, displayName, estimatedDBSize);
//#endif
}catch(e){
connection = null;
exceptionObject = e;
}
if(connection === null){
if(kony.sync.isNullOrUndefined(moduleName)){
moduleName = "";
}else{
moduleName += ": ";
}
sync.log.fatal(moduleName + "Error in getting connection");
kony.sync.verifyAndCallClosure(errorCallback, kony.sync.getErrorTable(kony.sync.errorCodeDbConnection, kony.sync.getErrorMessage(kony.sync.errorCodeDbConnection), exceptionObject));
}
return connection;
};
kony.sync.createDBEncryptionKey = function(passPhrase){
sync.log.trace("Entering kony.sync.createDBEncryptionKey ");
if(kony.sync.deviceDBEncryptionKey===null && passPhrase!==null && passPhrase!==undefined && !kony.sync.isEmptyString(passPhrase)){
//#ifdef KONYSYNC_IOS
kony.sync.deviceDBEncryptionKey = ["PRAGMA key = '" + passPhrase + "'"];
//#endif
//#ifdef KONYSYNC_ANDROID
kony.sync.deviceDBEncryptionKey = passPhrase;
//#endif
//#ifdef KONYSYNC_WINDOWS
kony.sync.deviceDBEncryptionKey = passPhrase;
//#endif
}
};
kony.sync.isValidFunctionType = function (closure) {
sync.log.trace("Entering kony.sync.isValidFunctionType ");
return kony.type(closure) === "function";
};
kony.sync.getTransactionError = function(isError){
sync.log.trace("Entering kony.sync.getTransactionError ");
if (!isError) {
sync.log.error("Transaction error occurred : ", kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
return kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null);
}
else{
sync.log.error("Statement error occurred : ", kony.sync.errorObject);
return kony.sync.errorObject;
}
};
kony.sync.isNullOrUndefined = function(val){
if(val === null || val === undefined){
return true;
}else{
return false;
}
};
kony.sync.formOrderByClause = function(tablename, map){
sync.log.trace("Entering kony.sync.formOrderByClause function");
if(map !== null && map !== undefined){
var scope = kony.sync.scopes[kony.sync.scopes.syncTableScopeDic[tablename]];
var columns = scope.syncTableDic[tablename].ColumnsDic;
for (var k=0;k < map.length; k++){
var v = map[k];
if(!kony.sync.isValidJSTable(v)){
sync.log.warn("Ignoring the orderby entry " + v + " as it is not a valid js object");
delete map[k];
continue;
}
if(kony.sync.isNull(columns[v.key])){
sync.log.warn("Ignoring the orderby entry " + v.key + " for the SyncObject " + tablename + ". " + v.key + " is not defined as an attribute in SyncConfiguration.");
delete map[k];
}
}
//var valuestable = kony.sync.convertOrderByMapToValuesTable(map);
//return kony.sync.convertToValuesTableOrderByMap(map,valuestable);
return map;
}
};
//function to check if where clause starts with a SQLite reserved keyword
kony.sync.startsWithKeyword = function (wcs) {
var keywordTable = ["where ", "limit ", "group ", "order ", "join "];
for(var i = 0 ; i < keywordTable.length ; i++) {
if(kony.string.startsWith(wcs, keywordTable[i])){
return true;
}
}
return false;
};
kony.sync.getChannelName = function(){
var returnVal = "";
//#ifdef KONYSYNC_MOBILE
returnVal = "mobile";
//#endif
//#ifdef KONYSYNC_TAB
returnVal = "tablet";
//#endif
//#ifdef KONYSYNC_DESKTOP
returnVal = "desktop";
//#endif
return returnVal;
};
kony.sync.getPlatformName = function(){
var returnVal = "";
//#ifdef KONYSYNC_IOS
returnVal = "ios";
//#endif
//#ifdef KONYSYNC_WINDOWS
returnVal = "windows";
//#endif
//#ifdef KONYSYNC_ANDROID
returnVal = "android";
//#endif
//#ifdef KONYSYNC_J2ME
returnVal = "j2me";
//#endif
//#ifdef KONYSYNC_BB
returnVal = "blackberry";
//#endif
return returnVal;
};
kony.sync.getRelationshipsForTable = function(tablename) {
sync.log.trace("Entering kony.sync.getRelationshipsForTable for table "+tablename);
var scopename = kony.sync.scopes.syncTableScopeDic[tablename];
var scope = kony.sync.scopes[scopename];
var relationShips = scope.syncTableDic[tablename].Relationships;
return relationShips;
};
kony.sync.getChildRecords = function(tablename, valuesTable) {
sync.log.trace("Entering kony.sync.getChildRecords for table "+tablename);
var childRecords = [];
var relationShips = kony.sync.getRelationshipsForTable(tablename);
if(!kony.sync.isNullOrUndefined(relationShips) && relationShips.hasOwnProperty(kony.sync.oneToMany)) {
//remove the child record from the values and add it to child records.
for(var j = 0; j < relationShips[kony.sync.oneToMany].length; j++) {
var childRecord = {};
var relationshipTargetObject = relationShips[kony.sync.oneToMany][j][kony.sync.targetObject];
//if there exists relationship target object, and values has child object which is not a null value.
if(!kony.sync.isNullOrUndefined(relationshipTargetObject) && valuesTable.hasOwnProperty(relationshipTargetObject)
&& !kony.sync.isNullOrUndefined(valuesTable[relationshipTargetObject])) {
childRecord[relationshipTargetObject] = valuesTable[relationshipTargetObject];
childRecords.push(childRecord);
delete valuesTable[relationshipTargetObject];
}
}
}
return childRecords;
};
kony.sync.getParentRelationshipAttributes = function(childTable, parentTable) {
sync.log.trace("Enterting kony.sync.getParentRelationshipAttributes for child "+childTable+" and parent "+parentTable);
if(childTable && parentTable) {
var scopename = kony.sync.scopes.syncTableScopeDic[childTable];
var scope = kony.sync.scopes[scopename];
var relationShipMap = scope.syncTableDic[parentTable + kony.sync.parentRelationshipMap];
//if there exists relationship and there are relationship attributes, return them. else return null
if (!kony.sync.isNullOrUndefined(relationShipMap) && relationShipMap.hasOwnProperty(childTable)) {
return relationShipMap[childTable];
}
}
return null;
};
kony.sync.getPkTableFromJSON = function(valuesTable, tableName) {
sync.log.trace("Entering kony.sync.getPkTableFromJSON for valuesTbale "+JSON.stringify(valuesTable)+" and table "+tableName);
var pkTable = {};
if(valuesTable && tableName) {
var scopename = kony.sync.scopes.syncTableScopeDic[tableName];
var scope = kony.sync.scopes[scopename];
var pkColumns = scope.syncTableDic[tableName].Pk_Columns;
for (var pkCount = 0; pkCount < pkColumns.length; pkCount++) {
if (valuesTable.hasOwnProperty(pkColumns[pkCount])) {
pkTable[pkColumns[pkCount]] = valuesTable[pkColumns[pkCount]];
delete valuesTable[pkColumns[pkCount]];
} else {
//pkColumn field not found. error.
sync.log.error("pkcolumn field "+pkColumns[pkCount]+ " not found in "+JSON.stringify(valuesTable));
return false;
}
}
}
return pkTable;
};
kony.sync.queryTable = function(tx, tablename, selectClause, whereClause, limitOffset) {
sync.log.trace("Entering kony.sync.queryTable for table "+tablename+" and select clause "+
JSON.stringify(selectClause)+ " with where clause "+JSON.stringify(whereClause));
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, selectClause);
kony.sync.qb_from(query, tablename);
kony.sync.qb_where(query, whereClause);
if(!kony.sync.isNullOrUndefined(limitOffset)) {
kony.sync.qb_limitOffset(query, limitOffset, kony.sync.blobManager.ONDEMAND_FETCH_OFFSET);
}
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
sync.log.trace("Executing query ", query, " with params ", JSON.stringify(params));
var result_set = kony.sync.executeSql(tx, sql, params);
return result_set;
};
// **************** End KonySyncHelper.js*******************
// **************** Start KonySyncInit.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync)=== "undefined") {
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined") {
kony.sync.blobManager = {};
}
//Initializes the DB with Generated Scope
sync.init = function(on_sync_init_success, on_sync_init_error) {
if(kony.sync.isValidJSTable(on_sync_init_success)===true) {
//new style, user called as sync.init(config)
//upload binary listener..
if(!kony.sync.isNullOrUndefined(on_sync_init_success[kony.sync.onBinaryUploadFunction]) &&
kony.sync.isValidFunctionType(on_sync_init_success[kony.sync.onBinaryUploadFunction])) {
sync.log.trace("sync.init - registering upload binary listener..");
kony.sync.onBinaryUpload = on_sync_init_success[kony.sync.onBinaryUploadFunction];
}
//download binary listener.
if(!kony.sync.isNullOrUndefined(on_sync_init_success[kony.sync.onBinaryDownloadFunction]) &&
kony.sync.isValidFunctionType(on_sync_init_success[kony.sync.onBinaryDownloadFunction])) {
sync.log.trace("sync.init - registering download binary listener..");
kony.sync.onBinaryDownload = on_sync_init_success[kony.sync.onBinaryDownloadFunction];
}
on_sync_init_error = on_sync_init_success[kony.sync.onSyncInitErrorParam];
kony.sync.createDBEncryptionKey(on_sync_init_success[kony.sync.deviceDBEncryptionKeyParam]);
on_sync_init_success = on_sync_init_success[kony.sync.onSyncInitSuccessParam];
}
// Create the database from xml. It also contains the provisioning commands
var syncscopes = konysyncClientSyncConfig.ArrayOfSyncScope;
kony.sync.syncConfigurationDBName = konysyncClientSyncConfig.AppID;
var isError = false;
var dbExists = false;
function loadDatabase() {
sync.log.trace("Entering loadDatabase");
var createDB = false;
syncscopes.syncTableScopeDic = [];
syncscopes.syncScopeBlobInfoMap = {};
syncscopes.syncToDeviceMap = {};
syncscopes.syncScopeRelationAttributesMap = {};
var currentscope = null;
var currenttemptable = null;
sync.log.info("loading DB");
function dbValidationCompleted() {
sync.log.trace("Entering dbValidationCompleted");
loadSyncScope(0);
}
function loadDatabaseTransaction(tx) {
sync.log.trace("Entering loadDatabaseTransaction");
// this is to be uncommented when we have db for each scope
//for i, ddl in ipairs ( DDLCommands[currentscope[kony.sync.scopeName]] ) do
var DDLCommands = null;
if ((kony.sync.getBackEndDBType() === kony.sync.dbTypeSQLCE)) {
DDLCommands = konysyncSQLCEDDLCommands;
} else {
DDLCommands = konysyncSQLLiteDDLCommands;
}
if(!kony.sync.isNullOrUndefined(DDLCommands)){
for (var i = 0; i < DDLCommands.length; i++) {
var ddl = DDLCommands[i];
sync.log.debug("ddl :" + ddl);
if(kony.sync.executeSql(tx, ddl)===false){
isError = true;
return;
}
}
}
if(kony.sync.initializeScopeSettings(tx)===false){
isError = true;
return;
}
if(kony.sync.setPragmaSize(tx)===false){
isError = true;
return;
}
}
function dbexistsErrorCallback() {
sync.log.trace("Entering dbexistsErrorCallback");
//Create DB
createDB = true;
sync.log.info("creating DB");
var conn = kony.sync.getConnectionOnly(currentscope[kony.sync.scopeDataSource], currentscope[kony.sync.scopeDataSource], on_sync_init_error);
if(conn!==null){
kony.sync.startTransaction(conn, loadDatabaseTransaction, dbValidationCompleted, initTransactionError);
}
}
function dbexistsSuccessCallback() {
sync.log.trace("Entering dbexistsSuccessCallback");
loadSyncScope(0);
}
//for a given table getting the reverseRelationships information
//for a child table getting the relationship data from a parent where child is targetobject
function getParentRelationships(currentscope,synctable){
parentRelationshipMap = {};
scopeTables = currentscope.ScopeTables;
if(!kony.sync.isNullOrUndefined(scope.ScopeTables)){
tables_length = scopeTables.length;
for(var i=0;i<tables_length;i++){
var currentTable = scopeTables[i];
var RelationshipAttributes = [];
if(!kony.sync.isNullOrUndefined(currentTable.Relationships.OneToMany)){
relationships_OneToMany = currentTable.Relationships.OneToMany;
OneToMany_length = relationships_OneToMany.length;
for(var j=0;j<OneToMany_length;j++){
//var attributeMap = {};
currentRelationShip = relationships_OneToMany[j];
if(currentRelationShip.TargetObject === synctable.Name){
relationshipAttributes = currentRelationShip.RelationshipAttributes;
relationshipAttributes_length = relationshipAttributes.length;
for(var k = 0 ;k<relationshipAttributes_length;k++){
attributes ={}
attributes["ParentObject_Attribute"] = relationshipAttributes[k].SourceObject_Attribute;
attributes["ChildObject_Attribute"] = relationshipAttributes[k].TargetObject_Attribute;
RelationshipAttributes.push(attributes)
}
}
}
}
if(RelationshipAttributes.length != 0){
parentRelationshipMap[currentTable.Name] = RelationshipAttributes;
}
}
}
return parentRelationshipMap;
}
var j = 0;
kony.sync.scopeDict = {};
if(!kony.sync.isNullOrUndefined(syncscopes)){
for (var i = 0; i < syncscopes.length; i++) {
var scope = syncscopes[i];
kony.sync.scopeDict[syncscopes[i].ScopeName] = scope;
currentscope = scope;
syncscopes[i] = scope;
scope.Index = i;
scope.syncTableDic = [];
scope.reverseRelationships = {};
// create helper dictionaries
if(!kony.sync.isNullOrUndefined(scope.ScopeTables)){
for (var k = 0; k < scope.ScopeTables.length; k++) {
var syncTable = scope.ScopeTables[k];
scope.syncTableDic[syncTable.Name] = syncTable;
scope.syncTableDic[syncTable.Name + kony.sync.historyTableName] = syncTable;
scope.syncTableDic[syncTable.Name + kony.sync.parentRelationshipMap] = getParentRelationships(scope,syncTable);
//reverse relationship mapping
if(!kony.sync.isNullOrUndefined(syncTable.Relationships.ManyToOne)){
for (j = 0; j < syncTable.Relationships.ManyToOne.length; j++) {
var rTable = syncTable.Relationships.ManyToOne[j].TargetObject;
if(kony.sync.isNullOrUndefined(scope.reverseRelationships[rTable])){
scope.reverseRelationships[rTable] = [];
}
if(!kony.sync.isNullOrUndefined(syncTable.Relationships.ManyToOne[j].RelationshipAttributes)) {
var relationshipAttributes = syncTable.Relationships.ManyToOne[j].RelationshipAttributes;
var attributeMap = {};
attributeMap.RelationshipAttributes = [];
attributeMap.TargetObject = syncTable.Name;
for (var iter = 0; iter < relationshipAttributes.length; iter++) {
var attributes = {};
attributes["SourceObject_Attribute"] = relationshipAttributes[iter].TargetObject_Attribute;
attributes["TargetObject_Attribute"] = relationshipAttributes[iter].SourceObject_Attribute;
attributeMap.RelationshipAttributes.push(attributes);
};
scope.reverseRelationships[rTable].push(attributeMap);
}
else
{
scope.reverseRelationships[rTable].push({ SourceObject_Attribute: syncTable.Relationships.ManyToOne[j].TargetObject_Attribute,
TargetObject: syncTable.Name,
TargetObject_Attribute: syncTable.Relationships.ManyToOne[j].SourceObject_Attribute
});
}
}
}
syncscopes.syncTableScopeDic[syncTable.Name] = scope.ScopeName;
syncscopes.syncTableScopeDic[syncTable.Name + kony.sync.historyTableName] = scope.ScopeName;
syncTable.ColumnsDic = [];
if(!kony.sync.isNullOrUndefined(syncTable.Columns)){
for (j = 0; j < syncTable.Columns.length; j++) {
var syncColumn = syncTable.Columns[j];
syncTable.ColumnsDic[syncColumn.Name] = syncColumn;
if(syncColumn.type === kony.sync.blob) {
if(kony.sync.isNullOrUndefined(syncscopes.syncScopeBlobInfoMap[syncTable.Name])) {
syncscopes.syncScopeBlobInfoMap[syncTable.Name] = {};
syncscopes.syncScopeBlobInfoMap[syncTable.Name][kony.sync.columns] = [];
}
syncscopes.syncScopeBlobInfoMap[syncTable.Name][kony.sync.columns].push(syncColumn.Name);
//in case of ifrecordvalue type, map the synctodevicefield.
if(syncColumn.hasOwnProperty(kony.sync.binaryPolicy) &&
syncColumn[kony.sync.binaryPolicy] === kony.sync.ifRecordValue) {
syncscopes.syncToDeviceMap[syncTable.Name + syncColumn.Name] = syncColumn[kony.sync.syncToDeviceField];
}
}
}
}
currenttemptable = syncTable.Name;
}
}
//Note This change will be undone once we have 1 DB for each scope.
sync.log.info("*************" + "\n",scope);
sync.log.info("\n" + "*************");
}
}
kony.sync.scopes = syncscopes;
kony.sync.scopes.scopecount = syncscopes.length;
/*removing check for existence of 1st table as 1st table may change for dynamic schema changes
kony.sync.single_execute_sql(currentscope[kony.sync.scopeDataSource], sqlcheckfordb + " LIMIT 1", null, dbexistsSuccessCallback, dbexistsErrorCallback);*/
if(dbExists){
dbexistsSuccessCallback();
}else{
dbexistsErrorCallback();
}
}
//Check If DB is created or not
function loadSyncScope(scopeindex) {
sync.log.trace("Entering loadSyncScope");
var addmetainfo = false;
var scope = kony.sync.scopes[scopeindex];
//Add scopes to MetaInfo table if not created and Initialize kony.sync.currentSyncScopesState table.
function loadSyncScopeTransaction(tx) {
sync.log.trace("Entering loadSyncScopeTransaction");
var query = null;
var query_compile = null;
var sql = null;
var params = null;
// check whether scope exists in metainfo after schema upgrade
sql = "select * from " + kony.sync.metaTableName + " where scopename = '" + scope.ScopeName + "'";
var resultSet = kony.sync.executeSql(tx, sql, null);
if(resultSet===false){
isError = true;
return;
}
if(resultSet.rows.length === 0){
//the scope does not exist in the metainfo table and so has to be added
addmetainfo = true;
}
if (addmetainfo) {
query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, {
id: "" + scopeindex,
filtervalue: "no filter",
scopename: scope.ScopeName,
versionnumber: 0,
lastserversynccontext: "",
lastserveruploadsynccontext: "",
replaysequencenumber: 0,
lastgeneratedid: -1
});
kony.sync.qb_insert(query, kony.sync.metaTableName);
//local sql = "insert into "..kony.sync.metaTableName.." (id,scopename,versionnumber,lastserversynccontext,replaysequencenumber,lastgeneratedid) values ('"..id.."','"..scope.ScopeName.."','0','','0','-1')"
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
}
kony.sync.currentSyncScopesState[scope.ScopeName] = 0;
} else {
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.metaTableSyncVersionCloumn]);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key: kony.sync.metaTableScopeColumn,
value: scope.ScopeName
}]);
//local sql = "select "..kony.sync.metaTableSyncVersionCloumn.." from "..kony.sync.metaTableName.." where "..kony.sync.metaTableScopeColumn.."='"..scope.ScopeName.."'";
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params);
if(resultset !== false && resultset.rows.length > 0){
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
if (!kony.sync.isNullOrUndefined(rowItem[kony.sync.metaTableSyncVersionCloumn])) {
kony.sync.currentSyncScopesState[scope.ScopeName] = rowItem[kony.sync.metaTableSyncVersionCloumn];
} else {
kony.sync.isResetInProgress = false;
isError = true;
}
}
else {
kony.sync.isResetInProgress = false;
isError = true;
}
}
//Check for Sync Version 5.5.6
if(kony.sync.checkForUpdate556to559Schema(tx) === false){
isError = true;
}
//Check for Sync Version 5.5.9
if(kony.sync.checkForUpdate559to560Schema(tx) === false){
isError = true;
}
}
function loadSyncScopeSuccess() {
sync.log.trace("Entering loadSyncScopeSuccess");
//schema changed
if(kony.sync.configVersion !== konysyncClientSyncConfig.Version){
kony.sync.schemaUpgradeNeeded = true;
//kony.sync.verifyAndCallClosure(on_sync_init_error, kony.sync.getSchemaUpgradeNeededError());
//return;
}
if(isError === true){
kony.sync.verifyAndCallClosure(on_sync_init_error, kony.sync.getScopeLoadingFailed());
}
if (scopeindex !== kony.sync.scopes.length - 1) {
loadSyncScope(scopeindex + 1);
} else {
checkForStaleScope(checkForStaleScopeCallback);
}
}
function checkForStaleScopeCallback(){
kony.sync.isResetInProgress = false;
//before initializing the thread, perform a clean up job to remove stale records.
if(typeof(binary) !== "undefined" && typeof(binary.util) !== "undefined" && !kony.sync.isCleanUpJobCompleted) {
sync.log.trace("checkForStaleScopeCallback -> Initializing binary stats");
kony.sync.initBinaryStats();
sync.log.trace("checkForStaleScopeCallback -> trigger clean up job.");
kony.sync.blobManager.performCleanUp(function(isError){
sync.log.trace("performCleanUp callback isError "+isError);
if(!isError) {
syncInitComplete();
} else {
//error occurred in performCleanup.
kony.sync.verifyAndCallClosure(on_sync_init_error, kony.sync.errorObject);
kony.sync.errorObject = null;
}
});
} else {
sync.log.trace("checkForStaleScopeCallback -> Do not trigger clean up job.");
syncInitComplete();
}
}
function syncInitComplete() {
sync.log.trace("syncInitComplete...");
kony.sync.syncInitialized = true;
//init the onDemand polling thread
if(typeof(binary) !== "undefined" && typeof(binary.util) !== "undefined") {
binary.util.binaryThreadInit(
kony.sync.blobManager.prepareJobs,
kony.sync.blobManager.getPreparedJobs,
kony.sync.blobManager.onDemandUniversalSuccessCallback,
kony.sync.blobManager.onDemandUniversalErrorCallback);
binary.util.createBlobsDir();
}
//init the binaryNotifier map
kony.sync.blobManager.binaryNotifierMap = {};
kony.sync.verifyAndCallClosure(on_sync_init_success);
}
function checkForStaleScope(callback){
var connection = kony.sync.getConnectionOnly(kony.sync.scopes[0][kony.sync.scopeDataSource], kony.sync.scopes[0][kony.sync.scopeDataSource], on_sync_init_error);
if(connection!==null){
kony.sync.startTransaction(connection, transactionCallback, transactionSuccessCallback, initTransactionError);
}
function transactionCallback(tx){
//Create ScopeMap
var scopeNames = "";
for(var i=0;i<kony.sync.scopes.length;i++){
if(i!==0){
scopeNames +=",";
}
scopeNames += "'" + kony.sync.scopes[i].ScopeName + "'";
}
var sql = "delete from " + kony.sync.metaTableName + " where " + kony.sync.metaTableScopeColumn + " not in (" + scopeNames + ")";
if(kony.sync.executeSql(tx, sql, null)===false){
isError = true;
}
}
function transactionSuccessCallback(){
callback();
}
}
var scopename = scope.ScopeName;
syncscopes[scopename] = scope;
var connection = kony.sync.getConnectionOnly(scope[kony.sync.scopeDataSource], scope[kony.sync.scopeDataSource], on_sync_init_error);
if(connection!==null){
kony.sync.startTransaction(connection, loadSyncScopeTransaction, loadSyncScopeSuccess, initTransactionError);
}
}
function generateClientDeviceID() {
sync.log.trace("Entering generateClientDeviceID");
function createTable() {
sync.log.trace("Entering createTable");
var sqltable = "create table " + kony.sync.syncConfigurationTableName + " (" +
kony.sync.syncConfigurationColumnDeviceIDName + " nvarchar(4000)," +
kony.sync.syncConfigurationColumnInstanceIDName + " nvarchar(4000)," +
kony.sync.syncConfigurationColumnVersion + " nvarchar(4000)," +
kony.sync.syncConfigurationColumnSchemaUpgradeContext + " nvarchar(4000))";
kony.sync.single_execute_sql(kony.sync.syncConfigurationDBName, sqltable, null, createDeviceID, on_sync_init_error);
}
function createDeviceID() {
sync.log.trace("Entering createDeviceID");
kony.sync.deviceId = "";
kony.sync.instanceId = "";
var settable = [];
settable[kony.sync.syncConfigurationColumnDeviceIDName] = kony.sync.deviceId;
settable[kony.sync.syncConfigurationColumnInstanceIDName] = kony.sync.instanceId;
kony.sync.configVersion = konysyncClientSyncConfig.Version;
settable[kony.sync.syncConfigurationColumnVersion] = kony.sync.configVersion;
var query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, settable);
kony.sync.qb_insert(query, kony.sync.syncConfigurationTableName);
var query_compile = kony.sync.qb_compile(query);
var sqlinsert = query_compile[0];
var params = query_compile[1];
kony.sync.single_execute_sql(kony.sync.syncConfigurationDBName, sqlinsert, params, loadDatabase, on_sync_init_error);
}
function setDeviceID(configRow) {
dbExists = true;
sync.log.trace("Entering setDeviceID");
kony.sync.deviceId = configRow[kony.sync.syncConfigurationColumnDeviceIDName];
kony.sync.instanceId = configRow[kony.sync.syncConfigurationColumnInstanceIDName];
kony.sync.configVersion = configRow[kony.sync.syncConfigurationColumnVersion];
loadDatabase();
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, kony.sync.syncConfigurationTableName);
kony.sync.single_execute_sql(kony.sync.syncConfigurationDBName, "select * from " + kony.sync.syncConfigurationTableName+" LIMIT 1", null, setDeviceID, createTable);
}
function initTransactionError(){
sync.log.trace("Entering initTransactionError");
kony.sync.callTransactionError(isError, on_sync_init_error);
}
generateClientDeviceID();
};
sync.reset = function(successcallback, errorcallback) {
if(kony.sync.isResetInProgress){
sync.log.warn("Reset already in progress...");
return;
}
if(kony.sync.isValidJSTable(successcallback)===true){
//new style, user called as sync.reset(config)
errorcallback = successcallback[kony.sync.onSyncResetErrorParam];
kony.sync.createDBEncryptionKey(successcallback[kony.sync.deviceDBEncryptionKeyParam]);
successcallback = successcallback[kony.sync.onSyncResetSuccessParam];
}
kony.sync.isResetInProgress = true;
kony.sync.schemaUpgradeNeeded = false;
kony.sync.syncConfigurationDBName = konysyncClientSyncConfig.AppID;
var dbList = [];
kony.table.insert(dbList, {
dbname: kony.sync.syncConfigurationDBName,
tableList: [kony.sync.syncConfigurationTableName, kony.sync.chunkMetaTableName, kony.sync.chunkTableName, kony.sync.metaTableName, kony.sync.pendingUploadTableName, "konysyncDIAGNOSTICS", "konysyncBLOBSTOREMANAGER"]
});
if(konysyncClientSyncConfig.ArrayOfSyncScope !== null && konysyncClientSyncConfig.ArrayOfSyncScope !== undefined){
for (var i = 0; i < konysyncClientSyncConfig.ArrayOfSyncScope.length; i++) {
var v = konysyncClientSyncConfig.ArrayOfSyncScope[i];
var tab = [];
for (var k in v.ScopeTables) {
var w = v.ScopeTables[k];
kony.table.insert(tab, w.Name);
kony.table.insert(tab, w.Name + kony.sync.historyTableName);
kony.table.insert(tab, w.Name + kony.sync.originalTableName);
}
/*if ((i === 1)) {
kony.table.insert(tab, kony.sync.metaTableName);
kony.table.insert(tab, "konysyncDIAGNOSTICS");
}*/
kony.table.insert(dbList, {
dbname: v.ScopeDatabaseName,
tableList: tab
});
}
}
kony.sync.syncDropDatabase(dbList, successcallback, errorcallback);
};
sync.rollbackPendingLocalChanges = function(successcallback, errorcallback) {
if(!kony.sync.isSyncInitialized(errorcallback)){
return;
}
kony.sync.rollbackCurrentScope = null;
kony.sync.konySyncRollBackPendingChanges(null, null, null, successcallback, errorcallback, true, 0);
};
sync.getPendingAcknowledgement = function(successcallback, errorcallback) {
if(!kony.sync.isSyncInitialized(errorcallback)){
return;
}
kony.sync.pendingAckIndex = 0;
kony.sync.pendingAckResult = {};
var currentScope = kony.sync.scopes[0];
var dbname = currentScope[kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback);
kony.sync.pendingAckCount = 0;
var isError = false;
function konysyncPendingAck_transaction(tx) {
sync.log.trace("Entering konysyncPendingAck_transaction");
function single_transaction_callback_local(sql, params, tbname) {
sync.log.trace("Entering single_transaction_callback_local");
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet===false){
isError = true;
return false;
}
var tableData = [];
var num_records = resultSet.rows.length;
for (var j = 0; j <= num_records - 1; j++) {
var record = kony.db.sqlResultsetRowItem(tx, resultSet, j);
kony.table.insert(tableData, record);
}
if ((num_records > 0)) {
kony.sync.pendingAckCount = kony.sync.pendingAckCount + num_records;
//table.insert(kony.sync.pendingAckResult,tableData);
kony.sync.pendingAckResult[tbname] = {};
kony.sync.pendingAckResult[tbname].count = num_records;
kony.sync.pendingAckResult[tbname].data = tableData;
}
}
if(!kony.sync.isNullOrUndefined(currentScope.ScopeTables)){
for (var i = 0; i < currentScope.ScopeTables.length; i++) {
var syncTable = currentScope.ScopeTables[i];
var tbname = syncTable.Name;
var currentversion = kony.sync.getCurrentVersionNumber(tbname);
var sql = "select * from " + tbname + " WHERE " + kony.sync.mainTableChangeTypeColumn + " is not null AND " + kony.sync.mainTableChangeTypeColumn + " <> -1 AND " + kony.sync.mainTableSyncVersionColumn + " <> " + currentversion + " AND " + kony.sync.mainTableChangeTypeColumn + " NOT LIKE '9%'";
if(single_transaction_callback_local(sql, null, tbname)===false){
return;
}
}
}
}
function konysyncPendingAck_transactionSucessCallback() {
sync.log.trace("Entering konysyncPendingAck_transactionSucessCallback");
sync.log.info("Get Pending Acknowledgement Count = ", kony.sync.pendingAckCount);
sync.log.info("Get Pending Acknowledgement = ", kony.sync.pendingAckResult);
if ((kony.sync.pendingAckIndex === kony.sync.scopes.scopecount - 1)) {
var konysyncPendingAckDic = {};
konysyncPendingAckDic.totalCount = kony.sync.pendingAckCount;
konysyncPendingAckDic.totalData = kony.sync.pendingAckResult;
kony.sync.verifyAndCallClosure(successcallback, konysyncPendingAckDic);
} else {
kony.sync.pendingAckIndex = kony.sync.pendingAckIndex + 1;
currentScope = kony.sync.scopes[kony.sync.pendingAckIndex];
dbname = currentScope[kony.sync.scopeDataSource];
dbconnection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback);
if (dbconnection !== null){
kony.sync.startTransaction(dbconnection, konysyncPendingAck_transaction, konysyncPendingAck_transactionSucessCallback, konysyncPendingAck_transactionErrorCallback, "Get Pending Acknowledgement");
}
}
}
function konysyncPendingAck_transactionErrorCallback() {
sync.log.trace("Entering konysyncPendingAck_transactionErrorCallback");
kony.sync.callTransactionError(isError, errorcallback);
}
if(dbconnection!==null){
kony.sync.startTransaction(dbconnection, konysyncPendingAck_transaction, konysyncPendingAck_transactionSucessCallback, konysyncPendingAck_transactionErrorCallback, "Get Pending Acknowledgement");
}
};
sync.getPendingUpload = function(successcallback, errorcallback) {
if(!kony.sync.isSyncInitialized(errorcallback)){
return;
}
kony.sync.pendingUploadIndex = 0;
kony.sync.pendingUploadResult = {};
var currentScope = kony.sync.scopes[0];
var dbname = currentScope[kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback);
kony.sync.pendingUploadCount = 0;
var isError = false;
function konysyncPendingUpload_transaction(tx) {
sync.log.trace("Entering konysyncPendingUpload_transaction");
function single_transaction_callback_local(sql, params, tbname) {
sync.log.trace("Entering single_transaction_callback_local");
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet===false){
isError = false;
return false;
}
var tableData = [];
var num_records = resultSet.rows.length;
for (var j = 0; j <= num_records - 1; j++) {
var record = kony.db.sqlResultsetRowItem(tx, resultSet, j);
kony.table.insert(tableData, record);
}
if ((num_records > 0)) {
kony.sync.pendingUploadCount = kony.sync.pendingUploadCount + num_records;
kony.sync.pendingUploadResult[tbname] = {};
kony.sync.pendingUploadResult[tbname].count = num_records;
kony.sync.pendingUploadResult[tbname].data = tableData;
}
}
if(!kony.sync.isNullOrUndefined(currentScope.ScopeTables)){
for (var i = 0; i < currentScope.ScopeTables.length; i++) {
var syncTable = currentScope.ScopeTables[i];
var tbname = syncTable.Name;
var columnsDic = currentScope.syncTableDic[tbname].Columns;
var columns = "";
for (var j = 0; j < columnsDic.length; j++) {
if(j==0){
columns = columns + columnsDic[j].Name;
} else {
columns = columns + ", " + columnsDic[j].Name;
}
}
var currentversion = kony.sync.getCurrentVersionNumber(tbname);
var sql = "select "+ columns +" from " + tbname + kony.sync.historyTableName + " WHERE " + kony.sync.mainTableChangeTypeColumn + " is not null AND " + kony.sync.mainTableChangeTypeColumn + " <> -1 AND " + kony.sync.mainTableSyncVersionColumn + " = " + currentversion + " AND " + kony.sync.mainTableChangeTypeColumn + " NOT LIKE '9%'";
if(single_transaction_callback_local(sql, null, tbname)===false){
return;
}
}
}
}
function konysyncPendingUpload_transactionSucessCallback() {
sync.log.trace("Entering konysyncPendingUpload_transactionSucessCallback");
sync.log.info("Pending Uploads Count = ", kony.sync.pendingUploadCount);
sync.log.info("Pending Uploads = ", kony.sync.pendingUploadResult);
if ((kony.sync.pendingUploadIndex === kony.sync.scopes.scopecount - 1)) {
var konysyncPendingUploadDic = {};
konysyncPendingUploadDic.totalCount = kony.sync.pendingUploadCount;
konysyncPendingUploadDic.totalData = kony.sync.pendingUploadResult;
kony.sync.verifyAndCallClosure(successcallback, konysyncPendingUploadDic);
} else {
kony.sync.pendingUploadIndex = kony.sync.pendingUploadIndex + 1;
currentScope = kony.sync.scopes[kony.sync.pendingUploadIndex];
dbname = currentScope[kony.sync.scopeDataSource];
dbconnection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback);
if(dbconnection !== null){
kony.sync.startTransaction(dbconnection, konysyncPendingUpload_transaction, konysyncPendingUpload_transactionSucessCallback, transactionErrorCallback, "Get Pending Upload");
}
}
}
function transactionErrorCallback() {
sync.log.trace("Entering transactionErrorCallback");
kony.sync.callTransactionError(isError, errorcallback);
}
if(dbconnection !== null){
kony.sync.startTransaction(dbconnection, konysyncPendingUpload_transaction, konysyncPendingUpload_transactionSucessCallback, transactionErrorCallback, "Get Pending Upload");
}
};
sync.getDeferredUpload = function(successcallback, errorcallback) {
if(!kony.sync.isSyncInitialized(errorcallback)){
return;
}
kony.sync.deferredUploadIndex = 0;
kony.sync.deferredUploadResult = {};
var currentScope = kony.sync.scopes[0];
var dbname = currentScope[kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback);
kony.sync.deferredUploadCount = 0;
var isError = false;
function konysyncDeferredUpload_transaction(tx) {
sync.log.trace("Entering konysyncDeferredUpload_transaction");
function single_transaction_callback_local(sql, params, tbname) {
sync.log.trace("Entering single_transaction_callback_local");
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet===false){
isError = true;
return false;
}
var tableData = [];
var num_records = resultSet.rows.length;
for (var j = 0; j <= num_records - 1; j++) {
var record = kony.db.sqlResultsetRowItem(tx, resultSet, j);
kony.table.insert(tableData, record);
}
if ((num_records > 0)) {
kony.sync.deferredUploadCount = kony.sync.deferredUploadCount + num_records;
kony.sync.deferredUploadResult[tbname] = {};
kony.sync.deferredUploadResult[tbname].count = num_records;
kony.sync.deferredUploadResult[tbname].data = tableData;
}
}
if(!kony.sync.isNullOrUndefined(currentScope.ScopeTables)){
for (var i = 0; i < currentScope.ScopeTables.length; i++) {
var syncTable = currentScope.ScopeTables[i];
var tbname = syncTable.Name;
var sql = "select * from " + tbname + " WHERE " + kony.sync.mainTableChangeTypeColumn + " is not null AND " + kony.sync.mainTableChangeTypeColumn + " <> -1 AND " + kony.sync.mainTableChangeTypeColumn + " LIKE '9%'";
if(single_transaction_callback_local(sql, null, tbname)===false){
return;
}
}
}
}
function konysyncDeferredUpload_transactionSucessCallback() {
sync.log.trace("Entering konysyncDeferredUpload_transactionSucessCallback");
sync.log.info("Deferred Uploads Count = ", kony.sync.deferredUploadCount);
sync.log.info("Deferred Uploads = ", kony.sync.deferredUploadResult);
if ((kony.sync.deferredUploadIndex === kony.sync.scopes.scopecount - 1)) {
var konysyncDeferredUploadDic = {};
konysyncDeferredUploadDic.totalCount = kony.sync.deferredUploadCount;
konysyncDeferredUploadDic.totalData = kony.sync.deferredUploadResult;
kony.sync.verifyAndCallClosure(successcallback, konysyncDeferredUploadDic);
} else {
kony.sync.deferredUploadIndex = kony.sync.deferredUploadIndex + 1;
currentScope = kony.sync.scopes[kony.sync.deferredUploadIndex];
dbname = currentScope[kony.sync.scopeDataSource];
dbconnection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback);
if (dbconnection !== null){
kony.sync.startTransaction(dbconnection, konysyncDeferredUpload_transaction, konysyncDeferredUpload_transactionSucessCallback, transactionErrorCallback, "Get Deferred Upload");
}
}
}
function transactionErrorCallback() {
sync.log.trace("Entering transactionErrorCallback");
kony.sync.callTransactionError(isError, errorcallback);
}
if (dbconnection !== null){
kony.sync.startTransaction(dbconnection, konysyncDeferredUpload_transaction, konysyncDeferredUpload_transactionSucessCallback, transactionErrorCallback, "Get Deferred Upload");
}
};
sync.getAllPendingUploadInstances = function(retrieveOnlyCount, successcallback, errorcallback) {
sync.log.trace("Entering sync.getAllPendingUploadInstances");
if(!kony.sync.isSyncInitialized(errorcallback)){
return;
}
var pendingUploadResult = {};
pendingUploadResult.totalCount = 0;
var dbname = kony.sync.scopes[0][kony.sync.scopeDataSource];
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback);
if(dbconnection !== null){
kony.db.transaction(dbconnection, pendingUploadTransaction, pendingUploadTransactionErrorCallback, pendingUploadTransactionSucessCallback);
}
var isError = false;
function pendingUploadTransaction(tx){
sync.log.trace("Entering sync.getAllPendingUploadInstances->pendingUploadTransaction");
for(var i=0; i < kony.sync.scopes.length; i++){
var currentScope = kony.sync.scopes[i];
var scopeName = currentScope[kony.sync.scopeName];
pendingUploadResult[scopeName] = {};
pendingUploadResult[scopeName].count = 0;
/*get syncversion from metatable*/
var syncversion = 0;
var query = kony.sync.qb_createQuery() ;
kony.sync.qb_select(query, [kony.sync.metaTableSyncVersionCloumn]);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key: kony.sync.metaTableScopeColumn,
value: scopeName
}, {
key: kony.sync.metaTableFilterValue,
value: "no filter"
}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params);
if(resultset===false){
isError = true;
return;
}
var row = kony.db.sqlResultsetRowItem(tx, resultset, 0);
syncversion = row[kony.sync.metaTableSyncVersionCloumn];
for (var j = 0; !kony.sync.isNull(currentScope.ScopeTables) && j < currentScope.ScopeTables.length; j++) {
var syncTable = currentScope.ScopeTables[j];
//not using query builder to speedup time
if(retrieveOnlyCount!==true){
sql = "select * from " + syncTable.Name + kony.sync.historyTableName + " where " + kony.sync.historyTableChangeTypeColumn + " NOT LIKE '9%' AND " +
kony.sync.historyTableSyncVersionColumn + " = " + syncversion;
}
else{
sql = "select count(*) from " + syncTable.Name + kony.sync.historyTableName + " where " + kony.sync.historyTableChangeTypeColumn + " NOT LIKE '9%' AND " +
kony.sync.historyTableSyncVersionColumn + " = " + syncversion;
}
resultset = kony.sync.executeSql(tx, sql, null);
if(resultset === false){
isError = true;
return;
}
pendingUploadResult[scopeName][syncTable.Name] = {};
if(retrieveOnlyCount!==true){
pendingUploadResult[scopeName][syncTable.Name].count = resultset.rows.length;
pendingUploadResult[scopeName][syncTable.Name].data = [];
for (var k = 0; k < resultset.rows.length; k++) {
pendingUploadResult[scopeName][syncTable.Name].data[k] = kony.db.sqlResultsetRowItem(tx, resultset, k);
}
}
else{
var rowCount = kony.db.sqlResultsetRowItem(tx, resultset, 0);
pendingUploadResult[scopeName][syncTable.Name].count = rowCount["count(*)"];
}
pendingUploadResult[scopeName].count += pendingUploadResult[scopeName][syncTable.Name].count;
pendingUploadResult.totalCount += pendingUploadResult[scopeName][syncTable.Name].count;
}
}
}
function pendingUploadTransactionErrorCallback(){
sync.log.trace("Entering sync.getAllPendingUploadInstances->pendingUploadTransactionErrorCallback");
kony.sync.verifyAndCallClosure(errorcallback);
}
function pendingUploadTransactionSucessCallback(){
sync.log.trace("Entering sync.getAllPendingUploadInstances->pendingUploadTransactionSucessCallback");
sync.log.info("getAllPendingUploadInstances success", pendingUploadResult);
kony.sync.verifyAndCallClosure(successcallback, pendingUploadResult);
}
};
kony.sync.checkForUpdate556to559Schema = function(tx){
var sql = "select count(*) from " + kony.sync.chunkTableName;
var resultSet = kony.sync.executeSql(tx, sql, null,null,false);
if(resultSet === false){
//Alter scripts for 5.5.6 to 5.5.9 DB Update
kony.sync.DDL556to559Update = [
"ALTER TABLE " + kony.sync.metaTableName + " ADD COLUMN " + kony.sync.metaTableUploadSyncTimeColumn + " nvarchar(1000)",
"CREATE TABLE " + kony.sync.pendingUploadTableName + " (" + kony.sync.metaTableScopeColumn + " nvarchar(100) not null," + kony.sync.pendingUploadTableUploadRequest + " text," + kony.sync.objectLevelInfo + " text," + kony.sync.pendingUploadTableInsertCount + " int," + kony.sync.pendingUploadTableUpdateCount + " int," + kony.sync.pendingUploadTableDeleteCount + " int," + kony.sync.pendingUploadTableBatchInsertCount + " int," + kony.sync.pendingUploadTableBatchUpdateCount + " int," + kony.sync.pendingUploadTableBatchDeleteCount + " int," + kony.sync.pendingUploadTableUploadLimit + " int,primary key (" + kony.sync.metaTableScopeColumn + "))",
"CREATE TABLE " + kony.sync.chunkTableName + " (" + kony.sync.chunkTableChunkId + " int not null," + kony.sync.chunkTablePayloadId + " nvarchar(50) not null," + kony.sync.metaTableScopeColumn + " nvarchar(100) not null," + kony.sync.chunkTableChunkData + " text," + kony.sync.chunkTableTimeStamp + " nvarchar(50),primary key (" + kony.sync.chunkTableChunkId + ", " + kony.sync.chunkTablePayloadId + ", " + kony.sync.metaTableScopeColumn + "))",
"CREATE TABLE " + kony.sync.chunkMetaTableName + " (" + kony.sync.chunkTablePayloadId + " nvarchar(50) not null," + kony.sync.metaTableScopeColumn + " nvarchar(100) not null," + kony.sync.metaTableChunkAck + " int," + kony.sync.metaTableChunkSize + " int," + kony.sync.metaTableChunkCount + " int," + kony.sync.metaTableChunkHashSum + " nvarchar(35)," + kony.sync.metaTableChunkDiscarded + " int,primary key (" + kony.sync.chunkTablePayloadId + ", "+ kony.sync.metaTableScopeColumn + "))"
];
}
return kony.sync.executeQueriesInTransaction(tx, kony.sync.DDL556to559Update);
};
kony.sync.checkForUpdate559to560Schema = function(tx){
var sql = "select count(" + kony.sync.metaTableSchemaUpgradeSyncTimeColumn + ") from " + kony.sync.metaTableName;
var resultSet = kony.sync.executeSql(tx, sql, null,null,false);
if(resultSet === false){
//Alter scripts for 5.5.9 to 5.6.0 DB Update
kony.sync.configVersion = konysyncClientSyncConfig.Version;
kony.sync.DDL559to560Update = [
"ALTER TABLE " + kony.sync.syncConfigurationTableName + " ADD COLUMN " + kony.sync.syncConfigurationColumnSchemaUpgradeContext + " nvarchar(4000)",
"ALTER TABLE " + kony.sync.syncConfigurationTableName + " ADD COLUMN " + kony.sync.syncConfigurationColumnVersion + " nvarchar(4000)",
"ALTER TABLE " + kony.sync.metaTableName + " ADD COLUMN " + kony.sync.metaTableSchemaUpgradeSyncTimeColumn + " nvarchar(1000)",
"UPDATE " + kony.sync.syncConfigurationTableName + " SET " + kony.sync.syncConfigurationColumnVersion + " = '" + konysyncClientSyncConfig.Version + "' where rowid = 1"
];
}
return kony.sync.executeQueriesInTransaction(tx, kony.sync.DDL559to560Update);
};
/**
* Method is used to fetch the records whose binary operation has failed
* @param isDownload {boolean} true for download/ false for upload
* @param tablename {String} tablename to filter binary records by tablename.
* @param columnname {String} column name to filter binary records by binary column.
* @param successCallback
* @param errorCallback
*/
sync.getFailedBinaryRecords = function(isDownload, tablename, columnname, successCallback, errorCallback) {
sync.log.trace("Entering kony.sync.single_insert_execute-> main function");
var isError = false;
var statusResponse = [];
function single_transaction_success_callback() {
if(!isError) {
sync.log.trace("kony.sync.getFailedBinaryRecords - single_transaction_success_callback...");
kony.sync.verifyAndCallClosure(successCallback, statusResponse);
} else {
kony.sync.verifyAndCallClosure(errorCallback, kony.sync.errorObject);
}
}
function single_transaction_failure_callback() {
sync.log.trace("kony.sync.getFailedBinaryRecords - single_transaction_error_callback...");
kony.sync.verifyAndCallClosure(errorCallback, kony.sync.errorObject);
}
function single_transaction_callback(tx) {
sync.log.trace("kony.sync.getFailedBinaryRecords - single_transaction_callback...");
var selectClause = [kony.sync.blobManager.id, kony.sync.blobManager.tableName, kony.sync.blobManager.columnName];
var whereClause = [];
var requiredState = kony.sync.blobManager.DOWNLOAD_FAILED;
if(!isDownload) {
requiredState = kony.sync.blobManager.UPLOAD_FAILED;
}
kony.table.insert(whereClause, {
key:kony.sync.blobManager.state,
value:requiredState,
optype:"EQ",
comptype:"AND"}
);
//if tablename is passed.. add it to the where clause..
if(!kony.sync.isNullOrUndefined(tablename)) {
kony.table.insert(whereClause, {
key:kony.sync.blobManager.tableName,
value:tablename,
optype:"EQ",
comptype:"AND"}
);
//if column name is passed, add it to the whereclause..
if(!kony.sync.isNullOrUndefined(columnname)) {
kony.table.insert(whereClause, {
key:kony.sync.blobManager.columnName,
value:columnname,
optype:"EQ",
comptype:"AND"}
);
}
}
var resultset = kony.sync.queryTable(tx, kony.sync.blobStoreManagerTable, selectClause, whereClause);
if(resultset) {
for(var k = 0; k < resultset.rows.length; k++) {
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, k);
var binaryColumnName = kony.sync.binaryMetaColumnPrefix+rowItem[kony.sync.blobManager.columnName];
var tbname = rowItem[kony.sync.blobManager.tableName];
var pkColumns = kony.sync.currentScope.syncTableDic[tbname].Pk_Columns;
var blobWhereClause = [{
key: binaryColumnName,
value: rowItem[kony.sync.blobManager.id]
}];
var parentResultSet = kony.sync.queryTable(tx, tbname, pkColumns, blobWhereClause);
if(!parentResultSet) {
return;
}
for(var rowCount = 0; rowCount < parentResultSet.rows.length; rowCount++) {
var parentRowItem = kony.db.sqlResultsetRowItem(tx, parentResultSet, rowCount);
var response = {};
for(var pkCount in pkColumns) {
var pkTable = {};
pkTable[pkColumns[pkCount]] = parentRowItem[pkColumns[pkCount]];
}
response.primaryKeys = pkTable;
response.tableName = tbname;
response.binaryColumn = rowItem[kony.sync.blobManager.columnName];
statusResponse.push(response);
}
}
}
}
var dbname = kony.sync.getDBName();
var connection = kony.sync.getConnectionOnly(dbname, dbname, errorCallback, "fetch binary failed records..");
if(connection !== null){
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback, single_transaction_failure_callback);
}
};
/**
* Method is used to fetch status of the binary records of given table.
* @param tbname - name of the table.
* @param columnName - name of the binary column
* @param pks {JSON} - Primary keys values for the record.
* @param successCallback - callback called upon success.
* @param errorCallback - callback called upon error.
*/
sync.getStatusForBinary = function(tbname, columnName, pks, successCallback, errorCallback) {
function single_transaction_callback(tx) {
sync.log.trace("Entering sync.getStatusForBinary -> single_transaction_callback");
if(kony.sync.isNullOrUndefined(pks)) {
//null pk values are received.
var error = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidPksGiven,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidPksGiven, pks)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
return;
}
var scopename = kony.sync.scopes.syncTableScopeDic[tbname];
var scope = kony.sync.scopes[scopename];
var pkColumns = scope.syncTableDic[tbname].Pk_Columns;
pks = kony.sync.validatePkTable(pkColumns, pks);
var statusResponse = {};
if(!kony.sync.isNullOrUndefined(pks)) {
var blobRef = kony.sync.getBlobRef(tx, tbname, columnName, pks, errorCallback);
statusResponse.primaryKeys = pks;
if (blobRef === kony.sync.blobRefNotDefined || blobRef === kony.sync.blobRefNotFound) {
statusResponse.statusCode = 0;
statusResponse.statusMessage = "Binary record not downloaded";
} else {
//blob ref exists. query the blob store manager.
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobRef, errorCallback);
if (blobMeta !== null && blobMeta !== false) {
statusResponse.statusCode = blobMeta[kony.sync.blobManager.state];
statusResponse.statusMessage = kony.sync.blobManager.states[statusResponse.statusCode];
}
}
sync.log.trace("status response for the get status request ", statusResponse);
kony.sync.verifyAndCallClosure(successCallback, statusResponse);
} else {
//error invalid pks.
var error = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidPksGiven,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidPksGiven, tbname)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
function single_transaction_success_callback() {
sync.log.trace("Entering kony.sync.getStatusForBinary->single_transaction_success_callback");
}
function single_transaction_error_callback() {
sync.log.error("Entering kony.sync.getStatusForBinary->single_transaction_error_callback");
}
sync.log.trace("Entering kony.sync.single_binary_select_status_execute-> main function");
if(kony.sync.isValidFunctionType(successCallback) && kony.sync.isValidFunctionType(errorCallback)) {
if(columnName === undefined || typeof(columnName) !== "string" || tbname === undefined ||
typeof(tbname) !== "string") {
var error = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidColumnParams,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidColumnParams)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
return;
}
var downloadPolicy = kony.sync.getDownloadPolicy(tbname, columnName);
sync.log.trace("download policy for the column "+tbname+"."+columnName+ " is "+downloadPolicy);
if(downloadPolicy !== kony.sync.notSupported) {
var dbname = kony.sync.getDBName();
var connection = kony.sync.getConnectionOnly(dbname, dbname, errorCallback, "fetch status for binary records..");
if(connection !== null){
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback, single_transaction_error_callback);
}
} else {
var error = kony.sync.getErrorTable(
kony.sync.errorCodeDownloadPolicyNotSupported,
kony.sync.getErrorMessage(kony.sync.errorCodeDownloadPolicyNotSupported, tbname+"."+columnName)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
};
/**
* Method is used to fetch Base64 string for a given record.
* @param tbname {String} - tablename
* @param columnName {String} - name of the binary column
* @param pks {JSON} - Primary keys values for the record.
* @param config {JSON} (optional) - config properties for the binary download. includes {"forceDownload": true/false}
* @param successCallback
* @param errorCallback
*/
sync.getBinaryBase64 = function(tbname, columnName, pks, config, successCallback, errorCallback) {
sync.log.trace("Entering sync.getBinaryBase64....");
var dbname = kony.sync.getDBName();
kony.sync.single_binary_select_base64_execute(dbname, tbname, columnName, pks, config, successCallback, errorCallback);
};
/**
* Method is used to fetch binary file for a given record
* @param tbname {String} - tablename
* @param columnName {String} - name of the binary column
* @param pks {JSON} - Primary keys values for the record.
* @param config {JSON} (optional) - config properties for the binary download. includes {"forceDownload": true/false}
* @param successCallback
* @param errorCallback
*/
sync.getBinaryFilepath = function(tbname, columnName, pks, config, successCallback, errorCallback) {
sync.log.trace("Entering sync.getBinaryFilepath....");
var dbname = kony.sync.getDBName();
kony.sync.single_binary_select_file_execute(dbname, tbname, columnName, pks, config, successCallback, errorCallback);
};
// **************** End KonySyncInit.js*******************
// **************** Start KonySyncLogger.js*******************
if (typeof(kony.sync) === "undefined") {
kony.sync = {};
}
if (typeof(kony.sync.log) === "undefined") {
kony.sync.log = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
sync.log = {};
//TRACE(6) > DEBUG(5) > INFO(4) > WARN(3) > ERROR(2) > FATAL(1) > NONE(0)
kony.sync.log.NONE = {
value : 0,
name : "none",
code : "NONE"
};
kony.sync.log.FATAL = {
value : 1,
name : "fatal",
code : "FATAL"
};
kony.sync.log.ERROR = {
value : 2,
name : "error",
code : "ERROR"
};
kony.sync.log.WARN = {
value : 3,
name : "warn",
code : "WARN"
};
kony.sync.log.INFO = {
value : 4,
name : "info",
code : "INFO"
};
kony.sync.log.DEBUG = {
value : 5,
name : "debug",
code : "DEBUG"
};
kony.sync.log.TRACE = {
value : 6,
name : "trace",
code : "TRACE"
};
//Global to maintain current loglevel
kony.sync.currentLogLevel = kony.sync.log.ERROR;
sync.log.trace = function (msg, params) {
kony.sync.logger(kony.sync.log.TRACE, msg, params);
};
sync.log.debug = function (msg, params) {
kony.sync.logger(kony.sync.log.DEBUG, msg, params);
};
sync.log.info = function (msg, params) {
kony.sync.logger(kony.sync.log.INFO, msg, params);
};
sync.log.warn = function (msg, params) {
kony.sync.logger(kony.sync.log.WARN, msg, params);
};
sync.log.error = function (msg, params) {
kony.sync.logger(kony.sync.log.ERROR, msg, params);
};
sync.log.fatal = function (msg, params) {
kony.sync.logger(kony.sync.log.FATAL, msg, params);
};
kony.sync.logger = function (logLevel, msg, params) {
if (logLevel.value <= kony.sync.currentLogLevel.value) {
params = (typeof(params) === "undefined") ? "" : params;
//Stringify object
if (kony.sync.isValidJSTable(params)) {
params = JSON.stringify(params, null, " ");
}
var date = new Date().toLocaleDateString();
var time = new Date().toLocaleTimeString();
var level = logLevel.code;
var formattedMessage = "[KonySync][" + level + "][" + date + "][" + time + "] : " + msg + " " + params;
kony.print(formattedMessage);
}
};
sync.log.isDebugEnabled = function () {
return kony.sync.currentLogLevel.value >= kony.sync.log.DEBUG.value;
};
sync.log.isTraceEnabled = function () {
return kony.sync.currentLogLevel.value >= kony.sync.log.TRACE.value;
};
sync.log.isInfoEnabled = function () {
return kony.sync.currentLogLevel.value >= kony.sync.log.INFO.value;
};
sync.log.isWarnEnabled = function () {
return kony.sync.currentLogLevel.value >= kony.sync.log.WARN.value;
};
sync.log.isFatalEnabled = function () {
return kony.sync.currentLogLevel.value >= kony.sync.log.FATAL.value;
};
sync.log.isErrorEnabled = function () {
return kony.sync.currentLogLevel.value >= kony.sync.log.ERROR.value;
};
sync.log.isNoneEnabled = function () {
return kony.sync.currentLogLevel.value === kony.sync.log.NONE.value;
};
sync.log.setLogLevel = function (level, logSuccessCallback, logFailureCallback) {
switch (level) {
case kony.sync.log.NONE:
kony.sync.currentLogLevel = kony.sync.log.NONE;
break;
case kony.sync.log.TRACE:
kony.sync.currentLogLevel = kony.sync.log.TRACE;
break;
case kony.sync.log.INFO:
kony.sync.currentLogLevel = kony.sync.log.INFO;
break;
case kony.sync.log.WARN:
kony.sync.currentLogLevel = kony.sync.log.WARN;
break;
case kony.sync.log.ERROR:
kony.sync.currentLogLevel = kony.sync.log.ERROR;
break;
case kony.sync.log.FATAL:
kony.sync.currentLogLevel = kony.sync.log.FATAL;
break;
case kony.sync.log.DEBUG:
kony.sync.currentLogLevel = kony.sync.log.DEBUG;
break;
default :
sync.log.error("Failed in setting log level "+ level);
kony.sync.verifyAndCallClosure(logFailureCallback, "Failed in setting log level " + level);
return;
}
sync.log.info("Log Level successfully set to " + kony.sync.currentLogLevel.name);
kony.sync.verifyAndCallClosure(logSuccessCallback, "Log Level successfully set to " + kony.sync.currentLogLevel.name);
};
sync.log.getCurrentLogLevel = function () {
return kony.sync.currentLogLevel;
};
// **************** End KonySyncLogger.js*******************
// **************** Start KonySyncMetadata.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync)=== "undefined"){
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined") {
kony.sync.blobManager = {};
}
// gets the time when dbname was last syced
kony.sync.getLastSynctime = function (scopename, dbname, scallback) {
sync.log.trace("Entering kony.sync.getLastSynctime");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}, {
key : kony.sync.metaTableFilterValue,
value : "no filter"
}
]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
kony.sync.single_select_execute(dbname, sql, params, scallback, errorCallback);
function errorCallback(res){
sync.log.error("error occurred while getting timestamp since last sync", res);
kony.sync.onDownloadCompletion(true, res);
}
};
// gets the time when dbname was last syced
kony.sync.getLastSynctimeForUpload = function (scopename, dbname, scallback){
sync.log.trace("Entering kony.sync.getLastSynctimeForUpload ");
function callback(rows) {
var lastSyncTime = -1;
var result = "";
for (var i = 0; i < rows.length; i++) {
var v = rows[i];
if (v[kony.sync.metaTableSyncTimeColumn] !== "") {
var str = v[kony.sync.metaTableSyncTimeColumn];
var temp = kony.sync.tonumber(str.split(",")[1]);
if ((lastSyncTime === -1)) {
lastSyncTime = temp;
result = str;
} else if ((temp < lastSyncTime)) {
lastSyncTime = temp;
result = str;
}
}
sync.log.info("Last TimeStamp since Upload :", lastSyncTime);
}
var resulttable = [];
if ((lastSyncTime === -1)) {
resulttable[kony.sync.metaTableSyncTimeColumn] = "";
scallback([resulttable]);
} else {
resulttable[kony.sync.metaTableSyncTimeColumn] = result;
scallback([resulttable]);
}
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.metaTableSyncTimeColumn]);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}
]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
kony.sync.single_select_execute(dbname, sql, params, callback, errorCallback);
function errorCallback(res){
sync.log.error("error occurred while getting timestamp since last upload", res);
kony.sync.onUploadCompletion(true, res);
}
};
// gets the time when dbname was last synced
kony.sync.getLastSynctimeFilter1 = function (scopename, filter, dbname, scallback) {
sync.log.trace("Entering kony.sync.getLastSynctimeFilter ");
function isDataPresent(result) {
sync.log.info("last sync time in filter :", result);
function getscopeindex(resultcount) {
function calscallback() {
var table = {};
table[kony.sync.metaTableSyncTimeColumn] = "";
scallback([table]);
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, {
id : resultcount.length + 1,
filtervalue : filter,
scopename : scopename,
versionnumber : 0,
lastserversynccontext : "",
replaysequencenumber : 0,
lastgeneratedid : -1
});
kony.sync.qb_insert(query, kony.sync.metaTableName);
var query_compile2 = kony.sync.qb_compile(query);
var sql2 = query_compile2[0];
var params2 = query_compile2[1];
kony.sync.single_select_execute(dbname, sql2, params2, calscallback, errorCallback);
}
if (result.length === 1) {
scallback(result);
} else {
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, kony.sync.metaTableName);
var query_compile3 = kony.sync.qb_compile(query);
var sql3 = query_compile3[0];
var params3 = query_compile3[1];
kony.sync.single_select_execute(dbname, sql3, params3, getscopeindex, errorCallback);
}
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.metaTableSyncTimeColumn]);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}, {
key : kony.sync.metaTableFilterValue,
value : filter
}
]);
var query_compile1 = kony.sync.qb_compile(query);
var sql1 = query_compile1[0];
var params1 = query_compile1[1];
kony.sync.single_select_execute(dbname, sql1, params1, isDataPresent, errorCallback);
function errorCallback(res){
sync.log.error("error occurred while getting time-stamp since last upload for filter", res);
kony.sync.onDownloadCompletion(true, res);
}
};
/* gets the time when scopename with filter was last synced */
kony.sync.getLastSynctimeFilter = function (scopename, filter, dbname, callback) {
sync.log.trace("Entering kony.sync.getLastSynctimeFilter ");
var connection = kony.sync.getConnectionOnly(dbname, dbname, transactionErrorCallback);
var isError = false;
var result = [];
if(connection!==null){
kony.db.transaction(connection, transactionCallback, transactionErrorCallback, transactionSuccessCallback);
}
function transactionCallback(tx){
sync.log.trace("Entering kony.sync.getLastSynctimeFilter->transactionCallback");
//search for row with filter
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.metaTableSyncTimeColumn]);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}, {
key : kony.sync.metaTableFilterValue,
value : filter
}
]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if (resultSet === false) {
isError = true;
return;
}
if(resultSet.rows.length >= 1){
result[0] = kony.db.sqlResultsetRowItem(tx, resultSet, 0);
}
else{ //if not found, insert it
//get the count of rows in metainfo
resultSet = kony.sync.executeSql(tx, "select * from " + kony.sync.metaTableName, null);
if (resultSet === false) {
isError = true;
return;
}
//insert the filter
query = kony.sync.qb_createQuery();
kony.sync.qb_set(query, {
id : resultSet.rows.length + 1,
filtervalue : filter,
scopename : scopename,
versionnumber : 0,
lastserversynccontext : "",
lastserveruploadsynccontext : "",
replaysequencenumber : 0,
lastgeneratedid : -1
});
kony.sync.qb_insert(query, kony.sync.metaTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
resultSet = kony.sync.executeSql(tx, sql, params);
if (resultSet === false) {
isError = true;
return;
}
var table = {};
table[kony.sync.metaTableSyncTimeColumn] = "";
result[0] = table;
}
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.getLastSynctimeFilter->transactionSuccessCallback");
callback(result);
}
function transactionErrorCallback(){
sync.log.trace("Entering kony.sync.getLastSynctimeFilter->transactionErrorCallback");
kony.sync.onDownloadCompletion(true, kony.sync.getTransactionError(isError));
}
};
// Update the meta tables with last sync time
kony.sync.setLastSyncTime = function (tx, scopename, time, tickcount) {
sync.log.trace("Entering kony.sync.setLastSyncTime ");
var settable = [];
if(kony.sync.schemaUpgradeDownloadPending){
settable[kony.sync.metaTableSchemaUpgradeSyncTimeColumn] = tickcount;
}else{
settable[kony.sync.metaTableSyncTimeColumn] = tickcount;
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, kony.sync.metaTableName);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}, {
key : kony.sync.metaTableFilterValue,
value : "no filter"
}
]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
};
// Update the meta tables with last sync time
kony.sync.setLastSyncTimeFilter = function (tx, scopename, filter, time, tickcount) {
sync.log.trace("Entering kony.sync.setLastSyncTimeFilter ");
var settable = [];
if(kony.sync.schemaUpgradeDownloadPending){
settable[kony.sync.metaTableSchemaUpgradeSyncTimeColumn] = tickcount;
}else{
settable[kony.sync.metaTableSyncTimeColumn] = tickcount;
}
//settable[kony.sync.metaTableFilterValue] = filter;
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, kony.sync.metaTableName);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}, {
key : kony.sync.metaTableFilterValue,
value : filter
}
]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
};
//function getseqnumber (connection,scopename)
kony.sync.getseqnumber = function (connection, scopename) {
sync.log.trace("Entering kony.sync.getseqnumber ");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.metaTableSyncVersionCloumn]);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}
]);
//local sql = "select "..kony.sync.metaTableSyncVersionCloumn.." from "..kony.sync.metaTableName.." where "..kony.sync.metaTableScopeColumn.." = '"..scopename.."'";
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(connection, sql, params);
if (resultset === false){
return false;
}
var rowItem = kony.db.sqlResultsetRowItem(connection, resultset, 0);
return rowItem;
};
kony.sync.setSeqnumber = function(scopename, dsname, uploaded, callback) {
sync.log.trace("Entering kony.sync.setSeqnumber ");
var isStatementError = false;
function transactionCallback(tx){
var settable = [];
settable[kony.sync.metaTableSyncVersionCloumn] = uploaded;
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, kony.sync.metaTableName);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, [{
key: kony.sync.metaTableScopeColumn,
value: scopename
}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isStatementError = true;
}
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.setSeqnumber->transactionSuccessCallback");
callback();
}
function transactionErrorCallback(){
sync.log.trace("Entering kony.sync.setSeqnumber->transactionErrorCallback");
sync.log.error("Error occurred while setting sequence number");
if (!isStatementError) {
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
}
else{
kony.sync.syncUploadFailed(kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
var connection = kony.sync.getConnectionOnly(dsname, dsname, transactionErrorCallback);
if(connection!==null){
kony.db.transaction(connection, transactionCallback, transactionErrorCallback, transactionSuccessCallback);
}
};
kony.sync.getSyncOrder = function (scopename, tx) {
sync.log.trace("Entering kony.sync.getSyncOrder ");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}
]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params);
if (resultset !== false) {
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
sync.log.debug("sync order value" + rowItem);
if(!kony.sync.isNullOrUndefined(rowItem[kony.sync.metaTableSyncOrderCloumn])) {
return kony.sync.tonumber(rowItem[kony.sync.metaTableSyncOrderCloumn]);
} else {
return null;
}
} else {
return false;
}
};
kony.sync.clearSyncHistory = function (dbname, tablename) {
sync.log.trace("Entering kony.sync.clearSyncHistory ");
var sql = "delete from " + tablename + kony.sync.historyTableName;
var wcs = " where konysyncchangetype NOT LIKE '9%'";
var testsql = sql + wcs;
kony.sync.single_execute_sql(dbname, testsql, null, null);
};
kony.sync.clearSyncOriginal = function (dbname, tbname) {
sync.log.trace("Entering kony.sync.clearSyncOriginal ");
var sql = "delete from " + tbname + kony.sync.originalTableName;
kony.sync.single_execute_sql(dbname, sql, null, null);
};
kony.sync.clearDataForCOE = function(tx, scopename, tablename, wcs, newwcs, changeType, pkset, seqNo, values, isError) {
sync.log.trace("Entering kony.sync.clearDataForCOE ");
if (kony.sync.isNullOrUndefined(pkset) && isError) {
return false;
}
var whereClause = kony.sync.CreateCopy(wcs);
var query = null;
var query_compile = null;
var sql = null;
var params = null;
//hashSum also needs to be updated to avoid conflicts.
var hashSum = values[kony.sync.historyTableHashSumColumn];
//update the binary to UPLOAD ACCEPTED.
//for onDemandColumns,
var onDemandColumns = kony.sync.getBinaryColumnsByPolicy(tablename, kony.sync.onDemand);
sync.log.trace("onDemandColumns for " + tablename + " are " + JSON.stringify(onDemandColumns));
var pkTable = {};
var binaryColumns = kony.sync.getBinaryColumns(tablename);
for(var j = 0; j < wcs.length; j++) {
pkTable[wcs[j].key] = wcs[j].value;
}
if(!kony.sync.isNullOrUndefined(binaryColumns)) {
for (var j = 0; j < binaryColumns.length; j++) {
if(kony.sync.getDownloadPolicy(tablename, binaryColumns[j]) !== kony.sync.inline) {
var blobRef = kony.sync.getBlobRef(tx, tablename, binaryColumns[j], pkTable, updateBlobStatusCallback);
sync.log.trace("blobRef for pkTable " + JSON.stringify(pkTable) + " is " + blobRef);
if (blobRef !== kony.sync.blobRefNotFound && blobRef !== kony.sync.blobRefNotDefined) {
//fetch the current state of the blob before upload_accepting.
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobRef, updateBlobStatusCallback);
if (!kony.sync.isNullOrUndefined(blobMeta) && blobMeta !== false) {
//if the blob entry is in valid state then accept the binary for upload.
if (blobMeta[kony.sync.blobManager.state] === kony.sync.blobManager.NO_OPERATION) {
sync.log.trace("marking the blob entry for UPLOAD for blob " + JSON.stringify(blobMeta));
var valuesTable = {};
valuesTable[kony.sync.blobManager.state] = kony.sync.blobManager.UPLOAD_ACCEPTED;
var results = kony.sync.blobManager.updateBlobManager(tx, blobRef, valuesTable, updateBlobStatusCallback);
if (results === null || results === false) {
return 0;
}
//increment total number of upload jobs..
kony.sync.incrementTotalJobs(false);
sync.log.trace("updated the state of the blob entry to UPLOAD_ACCEPTED");
} else {
sync.log.error("binary file not in a valid state to get picked for upload. ");
return 0;
}
} else {
return 0;
}
}
//invoke the notifier..
kony.sync.invokeBinaryNotifiers(false);
}
}
}
//in case I got client pk from server
if (!kony.sync.isNullOrUndefined(pkset)) {
//update original table pk with new pk from server
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tablename + kony.sync.originalTableName);
kony.sync.qb_set(query, pkset);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if (kony.sync.executeSql(tx, sql, params) === false) {
return 0;
}
//update main table pk with new pk from server
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tablename);
kony.sync.qb_set(query, pkset);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if (kony.sync.executeSql(tx, sql, params) === false) {
return 0;
}
//update history table pk with new pk from server
pkset[kony.sync.historyTableHashSumColumn] = hashSum;
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tablename + kony.sync.historyTableName);
kony.sync.qb_set(query, pkset);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if (kony.sync.executeSql(tx, sql, params) === false) {
return 0;
}
if (isError) {
return false;
}
kony.sync.serverInsertAckCount = kony.sync.serverInsertAckCount + 1;
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInsertedAck] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsInsertedAck] + 1;
whereClause = kony.sync.CreateCopy(newwcs);
} else if (changeType === "update") {
//update history table hashSum for pending records
if (!kony.sync.isNullOrUndefined(hashSum)) {
var updateSet = {};
updateSet[kony.sync.historyTableHashSumColumn] = hashSum;
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tablename + kony.sync.historyTableName);
kony.sync.qb_set(query, updateSet);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if (kony.sync.executeSql(tx, sql, params) === false) {
return 0;
}
}
/*TODO: non-autogenerated insert ack is currently considered as update ack*/
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdatedAck] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsUpdatedAck] + 1;
kony.sync.serverUpdateAckCount = kony.sync.serverUpdateAckCount + 1;
} else if (changeType === "delete") {
kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDeletedAck] = kony.sync.objectLevelInfoMap[tablename][kony.sync.numberOfRowsDeletedAck] + 1;
kony.sync.serverDeleteAckCount = kony.sync.serverDeleteAckCount + 1;
}
//TODO - throw error.
function updateBlobStatusCallback(err) {
sync.log.error("error in blobStoreManager update. --> clearDataForCOE " + JSON.stringify(err));
}
if (kony.sync.clearHistoryTable(tx, tablename, whereClause, seqNo) === false) {
return 0;
}
return kony.sync.clearMainTableForRemoveAfterUpload(tx, scopename, tablename, whereClause);
};
kony.sync.clearMainTableForRemoveAfterUpload = function (tx, scopename, tablename, wcs) {
sync.log.trace("Entering kony.sync.clearMainTableForRemoveAfterUpload ");
var whereClause = kony.sync.CreateCopy(wcs);
var removeAfterUpload = kony.sync.checkForDeleteAfterUpload(tablename,scopename);
//Get records to be deleted from history table;
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tablename + kony.sync.historyTableName);
kony.sync.qb_where(query, whereClause);
kony.sync.qb_distinct(query);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet === false){
return 0;
}
//don't remove from main and original tables if there is pending records in history table
if(resultSet.rows.length!==0){
return false;
}
//remove from original table
if(kony.sync.clearOriginalTable(tx,tablename,wcs)===false){
return 0;
}
if(removeAfterUpload){
if(kony.sync.isNullOrUndefined(whereClause)){
whereClause = [];
}
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, tablename);
kony.sync.qb_where(query, wcs);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return 0;
}
return true;
} else {
return false;
}
};
kony.sync.clearHistoryTable = function (tx, tablename, wcs, seqNo) {
sync.log.trace("Entering kony.sync.clearHistoryTable ");
var whereClause = kony.sync.CreateCopy(wcs);
if(kony.sync.isNullOrUndefined(whereClause)){
whereClause = [];
}
if (!kony.sync.isNullOrUndefined(seqNo)) {
kony.table.insert(whereClause, {
key : kony.sync.historyTableReplaySequenceColumn,
value : seqNo,
optype : "LT_EQ"
});
}
kony.table.insert(whereClause, {
key : kony.sync.historyTableChangeTypeColumn,
value : "9%",
optype : "NOT LIKE"
});
var query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, tablename + kony.sync.historyTableName);
kony.sync.qb_where(query, whereClause);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
};
kony.sync.getRecordsTobeDeletedFromHistoryTable = function(tx, tablename, seqNo){
sync.log.trace("Entering kony.sync.getRecordsTobeDeletedFromHistoryTable ");
var whereClause = [];
var records = false;
kony.table.insert(whereClause,{
key: kony.sync.historyTableReplaySequenceColumn,
value: seqNo,
optype: "LT_EQ"
});
//Get PK columns
var pkColumns = kony.sync.currentScope.syncTableDic[tablename].Pk_Columns;
//Get records to be deleted from history table;
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, pkColumns);
kony.sync.qb_from(query, tablename + kony.sync.historyTableName);
kony.sync.qb_where(query, whereClause);
kony.sync.qb_distinct(query);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet !== false){
records = [];
var i = 0;
for(;i<resultSet.rows.length;i++){
records.push(kony.db.sqlResultsetRowItem(tx, resultSet, i));
}
return records;
}
else{
return false;
}
};
kony.sync.clearOriginalTable = function(tx, tablename, wcs, seqNo){
sync.log.trace("Entering kony.sync.clearOriginalTable ");
var whereClause = kony.sync.CreateCopy(wcs);
var query = null;
var query_compile = null;
var sql = null;
var params = null;
if(!kony.sync.isNull(seqNo)){
whereClause = [];
kony.table.insert(whereClause,{
key: kony.sync.historyTableReplaySequenceColumn,
value: seqNo,
optype: "LT_EQ"
});
//Get PK columns
var pkColumns = kony.sync.currentScope.syncTableDic[tablename].Pk_Columns;
//Get records to be deleted from history table;
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, pkColumns);
kony.sync.qb_from(query, tablename + kony.sync.historyTableName);
kony.sync.qb_where(query, whereClause);
kony.sync.qb_distinct(query);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet === false){
return false;
}
var rowItem = null;
var i = 0;
var j = 0;
var originaltbname = tablename + kony.sync.originalTableName;
for(;i<resultSet.rows.length;i++){
rowItem = kony.db.sqlResultsetRowItem(tx, resultSet, i);
whereClause = [];
for (j = 0; j < pkColumns.length; j++) {
kony.table.insert(whereClause,{
key: pkColumns[j],
value: rowItem[pkColumns[j]],
optype: "EQ"
});
}
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, originaltbname);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
}
return true;
}
else{
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, tablename + kony.sync.originalTableName);
if(!kony.sync.isNull(whereClause)){
kony.sync.qb_where(query, whereClause);
}
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
}
};
//calls resets sync order for a scope if all the history tables are empty
kony.sync.updateSyncOrderForScope = function (callback) {
sync.log.trace("Entering kony.sync.updateSyncOrderForScope ");
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var scopename = kony.sync.currentScope[kony.sync.scopeName];
var isError = false;
var sql = null;
var params = null;
var query = null;
var query_compile = null;
kony.sync.getConnection(dbname, dbname, myTransactionCallBack, clear_success, clear_fail);
function myTransactionCallBack(tx) {
var recordcount = 0;
var versionNo = kony.sync.getseqnumber(tx, scopename);
if(!kony.sync.isNullOrUndefined(kony.sync.currentScope.ScopeTables)){
for (var i = 0; i < kony.sync.currentScope.ScopeTables.length; i++) {
var syncTable = kony.sync.currentScope.ScopeTables[i];
if (kony.sync.isNullOrUndefined(syncTable)){
continue;
}
var tbname = syncTable.Name;
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tbname + kony.sync.historyTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if (resultSet !== false) {
var num_records = resultSet.rows.length;
recordcount = recordcount + num_records;
if (num_records > 0) {
var versionMap = {};
versionMap[kony.sync.historyTableSyncVersionColumn] = versionNo.versionnumber;
var whereClause = [];
kony.table.insert(whereClause, {
key : kony.sync.historyTableChangeTypeColumn,
value : "9%",
optype : "NOT LIKE"
});
query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tbname + kony.sync.historyTableName);
kony.sync.qb_set(query, versionMap);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
return;
}
}
}
else{
isError = true;
return;
}
}
}
if (recordcount === 0) {
if(kony.sync.updateSyncOrder(tx, scopename)===false){
isError = true;
return;
}
}
}
function clear_fail() {
//kony.sync.downloadFailed(isError);
if(isError){
callback(kony.sync.errorCodeSQLStatement);
}
else{
callback(kony.sync.errorCodeTransaction);
}
}
function clear_success() {
if (callback != null){
callback(0);
}
}
};
//resets sync order for a scope
kony.sync.updateSyncOrder = function (tx, scopename) {
sync.log.trace("Entering kony.sync.updateSyncOrder ");
var settable = {};
settable[kony.sync.metaTableSyncOrderCloumn] = 0;
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, kony.sync.metaTableName);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}
]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
};
kony.sync.clearSyncOrder = function(dbname, limit, serverblob, deleteLastUploadRequest, callback) {
sync.log.trace("Entering kony.sync.clearSyncOrder ");
var recordcount = 0;
var isError = false;
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, clear_fail);
if (dbconnection !== null){
kony.db.transaction(dbconnection, clear_transaction, clear_fail, clear_success);
}
function clear_transaction(tx){
var resultSet = null;
var query_compile = null;
var sql = null;
var params = null;
//updating sync version for all records going in next batch
if(kony.sync.updateSyncOrderForUploadBatching(tx, limit)===false){
isError = true;
return;
}
//updating upload timestamp
if(kony.sync.setLastSyncUploadContext(tx, kony.sync.currentScope[kony.sync.scopeName], serverblob)===false){
isError = true;
return;
}
//delete last upload request
if(kony.sync.deleteLastUploadRequest(tx, kony.sync.currentScope[kony.sync.scopeName])===false){
isError = true;
return;
}
//Just returning from here, as this is getting handled in clearDataForCOE function, below code is redundant
return;
if(kony.sync.isUploadErrorPolicyCOE(kony.sync.currentScope)){
return;
}
if(!kony.sync.isNullOrUndefined(kony.sync.currentScope.ScopeTables)){
for (var i = 0; i < kony.sync.currentScope.ScopeTables.length; i++) {
var syncTable = kony.sync.currentScope.ScopeTables[i];
if(kony.sync.isNullOrUndefined(syncTable)){
continue;
}
var tbname = syncTable.Name;
//get whether table is marked for removeAfterUpload
var removeAfterUpload = kony.sync.checkForDeleteAfterUpload(tbname, kony.sync.currentScope[kony.sync.scopeName]);
//get Records To be deleted From History Table
var records = kony.sync.getRecordsTobeDeletedFromHistoryTable(tx, tbname, limit);
if(records===false){
isError = true;
return;
}
//clearing history table
if(kony.sync.clearHistoryTable(tx, tbname, null, limit)===false){
isError = true;
return;
}
var pkColumns = kony.sync.currentScope.syncTableDic[tbname].Pk_Columns;
for(var k in records){
//preparing where clause
var whereClause = [];
for (var j = 0; j < pkColumns.length; j++){
kony.table.insert(whereClause,{
key: pkColumns[j],
value: records[k][pkColumns[j]],
optype: "EQ"
});
}
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tbname + kony.sync.historyTableName);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet===false){
isError = true;
return;
}
//delete records from original and main tables if there is no pending record in history table
if(resultSet.rows.length===0){
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, tbname + kony.sync.originalTableName);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
return;
}
//remove value if table is marked for removeAfterUpload
if(removeAfterUpload){
query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, tbname);
kony.sync.qb_where(query, whereClause);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
isError = true;
return;
}
}
}
}
//currently disabling removeafterupload for P scope
//kony.sync.clearMainTableForRemoveAfterUpload(tx, scopename, tbname, null);
//couting deferred uploads
sql = "select * from " + tbname + kony.sync.historyTableName;
resultSet = kony.sync.executeSql(tx, sql, null);
if(resultSet===false){
isError = true;
return;
}
var num_records = resultSet.rows.length;
recordcount = recordcount + num_records;
}
}
if (recordcount === 0) {
if(kony.sync.updateSyncOrder(tx, kony.sync.currentScope[kony.sync.scopeName])===false){
isError = true;
}
}
}
function clear_success(){
sync.log.trace("Entering kony.sync.clearsyncorder->clear_success");
callback();
}
function clear_fail(){
sync.log.trace("Entering kony.sync.clearsyncorder->clear_fail");
if (!isError){
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
}
else{
kony.sync.syncUploadFailed(kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
};
kony.sync.setSyncOrder = function (scopename, syncorder, tx, errorCallback) {
sync.log.trace("Entering kony.sync.setSyncOrder ");
var settable = [];
settable[kony.sync.metaTableSyncOrderCloumn] = syncorder;
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, kony.sync.metaTableName);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}
]);
//local sql = "update ".. kony.sync.metaTableName.." set "..kony.sync.metaTableSyncOrderCloumn.."="..syncorder .." where "..kony.sync.metaTableScopeColumn.." = '".. scopename .."'";
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
sync.log.debug("setting sync order", sql);
return kony.sync.executeSql(tx, sql, params, errorCallback);
};
kony.sync.getLastGeneratedID = function (scopename, tx, errorCallback) {
sync.log.trace("Entering kony.sync.getLastGeneratedID ");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.metaTableLastGeneratedId]);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}
]);
//local sql = "select "..kony.sync.metaTableLastGeneratedId.." from "..kony.sync.metaTableName.." where "..kony.sync.metaTableScopeColumn.." = '"..scopename.."'";
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
sync.log.debug("getting lastgeneratedid", sql);
var resultset = kony.sync.executeSql(tx, sql, params, errorCallback);
if (resultset === false) {
return false;
}
sync.log.debug("result", resultset);
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
sync.log.debug("rowItem", rowItem);
if (!kony.sync.isNullOrUndefined(rowItem[kony.sync.metaTableLastGeneratedId])) {
return rowItem[kony.sync.metaTableLastGeneratedId];
} else {
//It should never come here
sync.log.fatal("Last Generated ID is null");
return false;
}
};
kony.sync.setLastGeneratedID = function (scopename, lastgeneratedid, tx, errorCallback) {
sync.log.trace("Entering kony.sync.setLastGeneratedID ");
var settable = [];
settable[kony.sync.metaTableLastGeneratedId] = lastgeneratedid;
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, kony.sync.metaTableName);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, [{
key : kony.sync.metaTableScopeColumn,
value : scopename
}
]);
//local sql = "update ".. kony.sync.metaTableName.." set "..kony.sync.metaTableLastGeneratedId.."="..lastgeneratedid .." where "..kony.sync.metaTableScopeColumn.." = '".. scopename .."'";
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
sync.log.debug("setting sync order", sql);
return kony.sync.executeSql(tx, sql, params, errorCallback);
};
// **************** End KonySyncMetadata.js*******************
// **************** Start KonySyncORMAPI.js*******************
if (typeof(kony.sync) === "undefined") {
kony.sync = {};
}
if (typeof(sync) === "undefined") {
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined"){
kony.sync.blobManager = {};
}
kony.sync.updateByPK = function (tbname, dbname, relationshipMap, pks, valuestable, successcallback, errorcallback, markForUpload, wcs) {
sync.log.trace("Entering kony.sync.updateByPK -> main function");
var isSuccess = true;
var pkNotFound = false;
var isRefIntegrityError = false;
var isMarkForuploadInvalid = false ;
var updateResult = null;
var errObject = null;
var twcs = [];
twcs = kony.sync.CreateCopy(wcs);
function single_execute_sql_transaction(tx) {
sync.log.trace("Entering kony.sync.updateByPK -> single_execute_sql_transaction ");
var record = "";
if(kony.sync.enableORMValidations){
record = kony.sync.getOriginalRow(tx, tbname, wcs, errorcallback);
if(record===false){
isSuccess = false;
return;
}
}
if (null !== record || !kony.sync.enableORMValidations) {
errObject = kony.sync.checkIntegrityinTransaction(tx, relationshipMap);
if (errObject === false) {
isSuccess = false;
return;
} else if (errObject !== true) {
isSuccess = false;
isRefIntegrityError = true;
kony.sync.rollbackTransaction(tx);
return;
} else {
var blobMap = {};
if(!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname])
&& !kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns])) {
var binaryColumns = kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns];
for(var i=0; i<binaryColumns.length; i++){
if(!kony.sync.isNullOrUndefined(valuestable[binaryColumns[i]]) && valuestable[binaryColumns[i]].length > 0)
blobMap[binaryColumns[i]] = valuestable[binaryColumns[i]];
delete valuestable[binaryColumns[i]];
}
}
updateResult = kony.sync.update(tx, tbname, valuestable, wcs, markForUpload, errorcallback);
if (updateResult === false) {
isSuccess = false;
} else if (updateResult === kony.sync.errorCodeInvalidMarkForUploadValue){
isMarkForuploadInvalid = true;
isSuccess = false;
} else {
if(Object.keys(blobMap).length > 0) {
var blobStoreIndices = kony.sync.blobstore_update(tx, tbname, blobMap, wcs, false, errorcallback);
if(!kony.sync.isNullOrUndefined(blobStoreIndices)){
if(Object.keys(blobStoreIndices).length > 0) {
var results = kony.sync.blobManager.updateParentWithBlobReference(tx, tbname, blobStoreIndices, wcs, errorcallback);
if(results === false || results === null) {
isSuccess = false;
}
}
} else {
isSuccess = false;
}
}
}
}
} else {
pkNotFound = true;
}
}
function single_transactionErrorCallback() {
sync.log.error("Entering kony.sync.updatebyPK->single_transactionErrorCallback ");
if (isSuccess){
kony.sync.showTransactionError(errorcallback);
} else if(isRefIntegrityError === true){
kony.sync.verifyAndCallClosure(errorcallback, errObject);
} else {
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
function single_execute_sql_transactionSucessCallback() {
sync.log.trace("Entering kony.sync.updateByPK->single_execute_sql_transactionSucessCallback -> isSuccess -> " + isSuccess);
if(pkNotFound === true){
kony.sync.pkNotFoundErrCallback(errorcallback,tbname);
return;
} else if(isMarkForuploadInvalid){
errorcallback(kony.sync.getErrorTable(kony.sync.errorCodeInvalidMarkForUploadValue, kony.sync.getErrorMessage(kony.sync.errorCodeInvalidMarkForUploadValue, tbname)));
} else if(isSuccess === false){
kony.sync.pkNotFoundErrCallback(errorcallback,tbname);
return;
} else {
kony.sync.verifyAndCallClosure(successcallback, {
rowsupdated : 1
});
}
}
try {
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback);
if (dbconnection !== null) {
kony.sync.startTransaction(dbconnection, single_execute_sql_transaction, single_execute_sql_transactionSucessCallback, single_transactionErrorCallback, "Single Execute");
}
} catch (e) {
sync.log.error("Unknown error occurred during update", e);
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(kony.sync.errorUnknown, kony.sync.getErrorMessage(kony.sync.errorUnknown, "Rollback", e), null));
}
};
kony.sync.checkForFalseUpdateInTransaction = function (tx, dbname, tbname, twcs, markForUpload, errorcallback) {
sync.log.trace("Entering kony.sync.checkForFalseUpdate ");
if (kony.sync.getUploadStatus(markForUpload)){
return true;
} else {
kony.table.insert(twcs, {
key : kony.sync.historyTableChangeTypeColumn,
value : "90",
optype : "EQ",
comptype : "AND"
});
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, [kony.sync.historyTableChangeTypeColumn]);
kony.sync.qb_from(query, tbname + "_history");
kony.sync.qb_where(query, twcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params, errorcallback);
if ((resultSet !== false)) {
var num_records = resultSet.rows.length;
if (num_records !== 0) {
sync.log.error("Record does not exist on server, mark it for upload before updating/deleting it");
return kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(kony.sync.errorCodeMarkForUpload, kony.sync.getErrorMessage(kony.sync.errorCodeMarkForUpload), null));
}
} else {
return false;
}
return true;
}
};
// **************** End KonySyncORMAPI.js*******************
// **************** Start konySyncQueryBuilder.js*******************
//-------------------------Sample Query Table for reference----------------------------
//sqlquery={
// ["schemaname"] = "",
// ["tablename"]= "",
// ["operationtype"] = "" { Insert, Select, Update, Delete, Custom },
// ["orderbyclause"]="",
// ["topclause"]="",
// ["isPurge"]=true/false This condition will make insert statement to insert ignore.
// ["purgeValues"] = "";
// multiple conditions
// ["conditions"]={
// {
// ["key"]=""
// ["value"]=""
// ["optype"]="" { EQ, NOT_EQ, GT, GT_EQ, LT, LT_EQ, LIKE, JOIN }
// ["comptype"]="" { AND, OR }
// ["binary"]="" {true,false}
// },
// {
// ["key"]=""
// ["value"]=""
// ["optype"]=""
// ["value"]=""
// }
// },
// ["fields"]={
// "c1","c2","c3"
// },
// ["colvals"]={
// {
// ["key"]="cname"
// ["value"]="vname"
// },
// {
// ["key"]="cname"
// ["value"]="vname"
// }
// }
//}
//function qb_createQuery()
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
kony.sync.qb_createQuery = function() {
sync.log.trace("Entering kony.sync.qb_createQuery ");
return {
topclause: "",
distinctclause: "",
orderbyclause: "",
colvals: [],
conditions: [],
paramindex: 0
};
};
kony.sync.qb_where = function(query, conditions) {
sync.log.trace("Entering kony.sync.qb_where ");
if(kony.sync.isNullOrUndefined(conditions)){
return;
}
for (var i = 0; i < conditions.length; i++) {
var cond = conditions[i];
var condition = [];
if (kony.sync.isNullOrUndefined(cond.optype)) {
cond.optype = "EQ";
}
if (kony.sync.isNullOrUndefined(cond.comptype)) {
cond.comptype = "AND";
}
condition.key = cond.key;
condition.optype = cond.optype;
condition.value = cond.value;
condition.comptype = cond.comptype;
condition.openbrace = cond.openbrace;
condition.closebrace = cond.closebrace;
kony.table.insert(query.conditions, condition);
}
};
kony.sync.qb_insert = function(query, tablename) {
sync.log.trace("Entering kony.sync.qb_insert ");
query.operationtype = "insert";
query.tablename = tablename;
};
kony.sync.qb_purgeInsert = function(query, tablename, values){
sync.log.trace("Entering kony.sync.qb_purgeInsert ");
query.operationtype = "insert";
query.tablename = tablename;
query.isPurge = true;
if(kony.sync.isNullOrUndefined(kony.sync.queryStore[tablename+"purgeInsert"])){
kony.sync.qb_set(query, values);
}else{
query.purgeValues = values;
}
};
kony.sync.qb_delete = function(query, tablename) {
sync.log.trace("Entering kony.sync.qb_delete ");
query.operationtype = "delete";
query.tablename = tablename;
};
kony.sync.qb_update = function(query, tablename) {
sync.log.trace("Entering kony.sync.qb_update ");
query.operationtype = "update";
query.tablename = tablename;
};
kony.sync.qb_select = function(query, fields) {
sync.log.trace("Entering kony.sync.qb_select ");
query.operationtype = "select";
query.fields = fields;
};
kony.sync.qb_from = function(query, tablename) {
sync.log.trace("Entering kony.sync.qb_from ");
query.tablename = tablename;
};
kony.sync.qb_set = function(query, tabcolval) {
sync.log.trace("Entering kony.sync.qb_set ");
for (var key in tabcolval) {
var value = tabcolval[key];
if(!kony.sync.isNullOrUndefined(value)) {
var colval = [];
colval.key = key;
colval.value = value;
kony.table.insert(query.colvals, colval);
}
}
};
kony.sync.qb_top = function(query, topno) {
sync.log.trace("Entering kony.sync.qb_top ");
query.topclause = " Top " + topno + " ";
};
kony.sync.qb_orderBy = function(query,orderByMap) {
sync.log.trace("Entering kony.sync.qb_orderBy ");
var orderByClause = "";
if(!kony.sync.isNullOrUndefined(orderByMap)){
orderByClause = " order by ";
var j=0;
for(var i in orderByMap){
if(j===0) {
orderByClause = orderByClause+ " \"" + orderByMap[i].key +"\"";
j++;
}
else {
orderByClause = orderByClause+",\""+ orderByMap[i].key + "\"";
}
if(orderByMap[i].sortType === "desc"){
orderByClause = orderByClause + " desc";
}
}
}
query.orderbyclause = orderByClause;
};
kony.sync.qb_distinct = function(query) {
query.distinctclause = " distinct ";
};
kony.sync.qb_orderby1 = function(query, colname, isasec) {
sync.log.trace("Entering kony.sync.qb_orderby1 ");
if ((isasec)) {
query.orderbyclause = " order by \"" + colname + "\"";
} else {
query.orderbyclause = " order by \"" + colname + "\" desc ";
}
};
kony.sync.qb_createParam = function(pkey, query, pval, params) {
sync.log.trace("Entering kony.sync.qb_createParam ");
if ((kony.sync.getBackEndDBType() === kony.sync.dbTypeSQLLite)) {
kony.table.insert(params, pval);
return "?";
} else if ((kony.sync.getBackEndDBType() === kony.sync.dbTypeSQLCE)) {
query.paramindex = query.paramindex + 1;
var param = "@" + pkey + query.paramindex;
params[param] = pval;
return param;
}
};
kony.sync.qb_getupdatedfields = function(query) {
sync.log.trace("Entering kony.sync.qb_getupdatedfields ");
var updateStr = "";
for (var i=0; i < query.colvals; i++) {
var v = query.colvals[i];
if(i === 0){
updateStr = " set ";
}
if(v.value === "nil") {
updateStr = updateStr + " \"" + v.key + "\"=" + "null";
} else {
updateStr = updateStr + " \"" + v.key + "\"=" + "'" + v.value + "'";
}
if (i < query.colvals.length-1) {
updateStr = updateStr + ",";
}
}
return updateStr;
};
kony.sync.qb_getparamupdatedfields = function(query) {
sync.log.trace("Entering kony.sync.qb_getparamupdatedfields ");
var updateStr = "";
var params = [];
for (var i=0; i<query.colvals.length; i++) {
var v = query.colvals[i];
if(i === 0){
updateStr = " set ";
}
if ((v.value === "nil")) {
updateStr = updateStr + " \"" + v.key + "\"=" + "null";
} else {
var param = kony.sync.qb_createParam(v.key, query, v.value, params);
updateStr = updateStr + " \"" + v.key + "\"=" + param;
}
if (i < query.colvals.length - 1) {
updateStr = updateStr + ",";
}
}
return [updateStr, params];
};
kony.sync.qb_getfieldstring = function(query) {
sync.log.trace("Entering kony.sync.qb_getfieldstring ");
var retstr = "";
if (!kony.sync.isNullOrUndefined(query.fields)) {
for (var i = 0; i< query.fields.length; i++) {
var field = query.fields[i];
retstr = retstr + field;
if(query.fields.length - 1 !== i) {
retstr = retstr + ",";
}
}
return retstr;
} else {
return "*";
}
};
kony.sync.qb_getoperatorString = function(optype, isnull) {
sync.log.trace("Entering kony.sync.qb_getoperatorString ");
if ((optype === "EQ")) {
if ((isnull)) {
return " is ";
} else {
return " = ";
}
} else if ((optype === "NOT_EQ")) {
if ((isnull)) {
return " is not ";
} else {
if ((kony.sync.getBackEndDBType() === kony.sync.dbTypeSQLCE)) {
return " !== ";
} else if ((kony.sync.getBackEndDBType() === kony.sync.dbTypeSQLLite)) {
return " <> ";
}
}
} else if ((optype === "GT")) {
return " > ";
} else if ((optype === "GT_EQ")) {
return " >= ";
} else if ((optype === "LT")) {
return " < ";
} else if ((optype === "LT_EQ")) {
return " <= ";
} else if ((optype === "LIKE")) {
return " LIKE ";
} else if ((optype === "NOT LIKE")) {
return " NOT LIKE ";
} else {
return "";
}
return "MARS";
};
kony.sync.qb_getcompstring = function(comptype) {
sync.log.trace("Entering kony.sync.qb_getcompstring ");
if ((comptype === "AND")) {
return " AND ";
} else if ((comptype === "OR")) {
return " OR ";
} else {
return "";
}
};
kony.sync.qb_getwhereclause = function(query) {
sync.log.trace("Entering kony.sync.qb_getwhereclause ");
var retstr = "";
if (!kony.sync.isNullOrUndefined(query.conditions)) {
for (var i = 0; i < query.conditions.length; i++) {
var condition = query.conditions[i];
if (i === 0) {
retstr = " WHERE ";
}
var conditionString = "";
if ((condition.value === "nil")) {
conditionString = "\"" + condition.key + "\" " + kony.sync.qb_getoperatorString(condition.optype, true) + "null";
} else {
conditionString = "\"" + condition.key + "\" " + kony.sync.qb_getoperatorString(condition.optype, false) + "'" + condition.value + "' ";
}
if(condition.openbrace === true){
conditionString = " ( " + conditionString;
}
if(condition.closebrace === true){
conditionString = conditionString + ")";
}
retstr = retstr + conditionString;
if (i !== query.conditions.length - 1) {
retstr = retstr + kony.sync.qb_getcompstring(condition.comptype);
}
}
}
return retstr;
};
kony.sync.qb_getparamwhereclause = function(query) {
sync.log.trace("Entering kony.sync.qb_getparamwhereclause ");
var retstr = "";
var params = [];
if (!kony.sync.isNullOrUndefined(query.conditions)) {
for (var i = 0; i < query.conditions.length; i++) {
var condition = query.conditions[i];
if (i === 0) {
retstr = " WHERE ";
}
var conditionString = "";
if ((condition.value === "nil")) {
conditionString = condition.key + kony.sync.qb_getoperatorString(condition.optype, true) + "null";
} else {
var param = kony.sync.qb_createParam(condition.key, query, condition.value, params);
conditionString = condition.key + kony.sync.qb_getoperatorString(condition.optype, false) + param;
}
if(condition.openbrace === true){
conditionString = " ( " + conditionString;
}
if(condition.closebrace === true){
conditionString = conditionString + ")";
}
retstr = retstr + conditionString;
if (i !== query.conditions.length - 1) {
retstr = retstr + kony.sync.qb_getcompstring(condition.comptype);
}
}
}
return [retstr, params];
};
kony.sync.qb_getinsertcolums = function(query) {
sync.log.trace("Entering kony.sync.qb_getinsertcolums ");
var retstr = "(";
var numCols = query.colvals.length;
var count = 0;
if(numCols === 0) {
return "";
}
if(!kony.sync.isNullOrUndefined(query.colvals)){
for (var i = 0; i < query.colvals.length; i++) {
var colval = query.colvals[i];
count = count + 1;
retstr = retstr + "\"" + colval.key + "\"";
if ((count !== numCols)) {
retstr = retstr + ",";
}
}
}
retstr = retstr + ")";
return retstr;
};
kony.sync.qb_getinsertvalues = function(query) {
sync.log.trace("Entering kony.sync.qb_getinsertvalues ");
var retstr = "(";
var numCols = query.colvals.length;
if (numCols === 0) {
return "";
}
if(!kony.sync.isNullOrUndefined(query.colvals)){
for (var i = 0; i < query.colvals.length; i++) {
var colval = query.colvals[i];
var value = "";
if ((colval === "nil")) {
value = "NULL";
} else {
value = "'" + colval.value + "'";
}
retstr = retstr + value;
if ((i !== numCols)) {
retstr = retstr + ",";
}
}
}
retstr = retstr + ")";
return retstr;
};
kony.sync.qb_getparaminsertvalues = function(query) {
sync.log.trace("Entering kony.sync.qb_getparaminsertvalues ");
var retstr = "(";
var params = [];
var numCols = query.colvals.length;
if (numCols === 0) {
return "";
}
if(!kony.sync.isNullOrUndefined(query.colvals)){
for (var i = 0; i < query.colvals.length; i++) {
var colval = query.colvals[i];
var value = "";
if ((colval === "nil")) {
value = "NULL";
} else {
var param = kony.sync.qb_createParam(colval.key, query, colval.value, params);
value = param;
}
retstr = retstr + value;
if (i !== numCols - 1) {
retstr = retstr + ",";
}
}
}
retstr = retstr + ")";
return [retstr, params];
};
kony.sync.qb_gettablename = function(query) {
sync.log.trace("Entering kony.sync.qb_gettablename ");
return query.tablename;
};
//lmit and offset for select
kony.sync.qb_limitOffset = function(query, limit, offset){
if(!kony.sync.isNullOrUndefined(limit)){
if(kony.sync.isNullOrUndefined(offset)){
offset = 0;
}
if ((kony.sync.getBackEndDBType() === kony.sync.dbTypeSQLLite)) {
query.limit = limit;
query.offset = offset;
}
}
};
kony.sync.qb_compile = function(query) {
sync.log.trace("Entering kony.sync.qb_compile ");
var params = null;
var sql = null;
var wctable = null;
var wc = null;
var ret = null;
if ((kony.sync.isParameter)) {
ret = "";
if ((query.operationtype === "insert")) {
var insertstring = "insert into ";
if(query.isPurge === true){
if(!kony.sync.isNullOrUndefined(kony.sync.queryStore[query.tablename+"purgeInsert"])){
return [kony.sync.queryStore[query.tablename+"purgeInsert"], query.purgeValues];
}
//#ifdef android
insertstring = "insert into ";
//#else
//#ifdef tabrcandroid
insertstring = "insert into ";
//#else
insertstring = "insert or ignore into ";
//#endif
//#endif
}
var itable = kony.sync.qb_getparaminsertvalues(query);
var iv = itable[0];
params = itable[1];
sql = insertstring + "\"" + kony.sync.qb_gettablename(query) + "\"" + kony.sync.qb_getinsertcolums(query) + " values " + iv;
if(query.isPurge === true){
kony.sync.queryStore[query.tablename+"purgeInsert"] = sql;
}
return [sql, params];
}else if ((query.operationtype === "select")) {
wctable = kony.sync.qb_getparamwhereclause(query);
wc = wctable[0];
params = wctable[1];
sql = "select " + query.distinctclause + query.topclause + kony.sync.qb_getfieldstring(query) + " from \"" + kony.sync.qb_gettablename(query) + "\"" + wc + query.orderbyclause;
if(!kony.sync.isNullOrUndefined(query.limit)){
sql += " limit " + query.limit + " offset " + query.offset;
}
return [sql, params];
} else if ((query.operationtype === "update")) {
wctable = kony.sync.qb_getparamwhereclause(query);
wc = wctable[0];
var wparams = wctable[1];
var uftable = kony.sync.qb_getparamupdatedfields(query);
var uf = uftable[0];
var uparams = uftable[1];
sql = "Update \"" + kony.sync.qb_gettablename(query) + "\" " + uf + " " + wc;
for (var i = 0; i < wparams.length; i++) {
uparams.push(wparams[i]);
}
params = uparams;
//kony.sync.syncPrint("update sql : " + sql);
//kony.sync.syncPrint("update params : " + params);
return [sql, params];
} else if ((query.operationtype === "delete")) {
wctable = kony.sync.qb_getparamwhereclause(query);
wc = wctable[0];
params = wctable[1];
sql = "delete from \"" + kony.sync.qb_gettablename(query) + "\" " + wc;
return [sql, params];
}
} else {
ret = "";
if ((query.operationtype === "select")) {
sql = "select " + query.distinctclause + query.topclause + kony.sync.qb_getfieldstring(query) +
" from \"" + kony.sync.qb_gettablename(query) + "\"" + kony.sync.qb_getwhereclause(query) + query.orderbyclause;
return sql;
} else if ((query.operationtype === "update")) {
return "Update \"" + kony.sync.qb_gettablename(query) +
"\" " + kony.sync.qb_getupdatedfields(query) +
" " + kony.sync.qb_getwhereclause(query);
} else if ((query.operationtype === "insert")) {
return "insert into \"" + kony.sync.qb_gettablename(query) + "\"" +
kony.sync.qb_getinsertcolums(query) + " values " + kony.sync.qb_getinsertvalues(query);
} else if ((query.operationtype === "delete")) {
return "delete from \"" + kony.sync.qb_gettablename(query) + "\" " + kony.sync.qb_getwhereclause(query);
}
}
};
// **************** End konySyncQueryBuilder.js*******************
// **************** Start konySyncQueryProvider.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
kony.sync.single_execute_sql = function (dsname, sqlstatement, params, result_successcallback, result_errorcallback) {
sync.log.trace("Entering kony.sync.single_execute_sql-> main function");
var single_execute_sql_result = null;
var dbname = dsname;
var isError = false;
function single_execute_sql_transaction(tx) {
sync.log.trace("Entering single_execute_sql_transaction");
var resultset = kony.sync.executeSql(tx, sqlstatement, params, result_errorcallback);
if (resultset !== false) {
if ( !(kony.sync.isNullOrUndefined(resultset.rows)) && resultset.rows.length > 0) {
single_execute_sql_result = kony.db.sqlResultsetRowItem(tx, resultset, 0);
}
} else {
isError = true;
}
}
function single_execute_sql_transactionSucessCallback() {
sync.log.trace("Entering kony.sync.single_execute_sql->single_execute_sql_transactionSucessCallback");
if (!isError) {
kony.sync.verifyAndCallClosure(result_successcallback, single_execute_sql_result);
}
}
function single_execute_sql_transactionErrorCallback() {
sync.log.error("Entering kony.sync.single_execute_sql->single_execute_sql_transactionErrorCallback");
if (!isError) {
kony.sync.verifyAndCallClosure(result_errorcallback, kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
}
else{
kony.sync.verifyAndCallClosure(result_errorcallback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname,result_errorcallback);
if(dbconnection!==null){
kony.sync.startTransaction(dbconnection, single_execute_sql_transaction, single_execute_sql_transactionSucessCallback, single_execute_sql_transactionErrorCallback, "Single Execute");
}
};
kony.sync.single_select_execute = function (dsname, sql, params, success_callback, error_callback) {
sync.log.trace("Entering kony.sync.single_select_execute ");
var callback_result = [];
var dbname = dsname;
var isError = false;
function single_transaction_success_callback() {
sync.log.trace("Entering kony.sync.single_select_execute->single_transaction_success_callback");
if (!isError) {
kony.sync.verifyAndCallClosure(success_callback, callback_result);
}
}
function single_transaction_error_callback() {
sync.log.error("Entering kony.sync.single_select_execute->single_transaction_error_callback");
if (!isError) {
kony.sync.showTransactionError(error_callback);
}else{
sync.log.error("Entering kony.sync.single_select_execute->single_transaction_error_callback :", kony.sync.errorObject);
kony.sync.verifyAndCallClosure(error_callback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
function single_transaction_callback(tx) {
sync.log.trace("Entering kony.sync.single_select_execute->single_transaction_callback");
var resultSet = kony.sync.executeSql(tx, sql, params, error_callback);
if (resultSet !== false) {
if ((kony.sync.is_SQL_select(sql))) {
var num_records = resultSet.rows.length;
sync.log.debug("Single Select no of records:", num_records);
for (var i = 0; i <= num_records - 1; i++) {
var record = kony.db.sqlResultsetRowItem(tx, resultSet, i);
kony.table.insert(callback_result, record);
}
}
} else {
isError = true;
}
}
var connection = kony.sync.getConnectionOnly(dbname, dbname, error_callback);
if(connection !== null){
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback, single_transaction_error_callback);
}
};
kony.sync.single_binary_select_ondemand_execute = function(dsname, tbname, columnName, pks, config,
blobType, successCallback, errorCallback){
var response = {};
function single_transaction_success_callback() {
sync.log.trace("Entering kony.sync.single_select_execute_binary_onDemand->single_select_binary_transaction_success");
}
function single_transaction_error_callback() {
sync.log.error("Entering kony.sync.single_select_execute_binary_onDemand->single_select_binary_transaction_failed");
}
function single_transaction_callback(tx) {
var scopename = kony.sync.scopes.syncTableScopeDic[tbname];
var scope = kony.sync.scopes[scopename];
var pkColumns = scope.syncTableDic[tbname].Pk_Columns;
//validate whether we get all pks in the pk table.
pks = kony.sync.validatePkTable(pkColumns, pks);
sync.log.trace("after validation pks are "+JSON.stringify(pks));
if(!kony.sync.isNullOrUndefined(pks)) {
var blobRef = kony.sync.getBlobRef(tx, tbname, columnName, pks ,errorCallback);
sync.log.trace(kony.sync.binaryMetaColumnPrefix+columnName+" value is "+blobRef);
if(!kony.sync.isNullOrUndefined(blobRef)) {
if (blobRef === kony.sync.blobRefNotFound) {
//blobref is not found.
sync.log.trace("blobref not found. ");
response.pkTable = pks;
if(blobType === kony.sync.BlobType.BASE64) {
response.base64 = null;
} else {
response.filePath = null;
}
kony.sync.verifyAndCallClosure(successCallback, response);
}
else {
//check if there is any context info.
var blobContext = kony.sync.getBlobContext(tx, tbname, columnName, pks ,errorCallback);
if (blobRef === kony.sync.blobRefNotDefined) {
if(blobContext !== kony.sync.blobRefNotDefined) {
//trigger download..
sync.log.trace("blobref not defined. triggering download");
kony.sync.blobManager.getBlobOnDemand(tx, kony.sync.blobRefNotDefined, blobType, tbname,
columnName, config, pks, successCallback, errorCallback);
} else {
sync.log.info("no context available for download.");
response.pkTable = pks;
if(blobType === kony.sync.BlobType.BASE64) {
response.base64 = null;
} else {
response.filePath = null;
}
kony.sync.verifyAndCallClosure(successCallback, response);
}
}
else {
//fetch from blob store manager.
sync.log.trace("blobref defined. fetching from blobStoreManager table");
kony.sync.blobManager.getBlobOnDemand(tx, blobRef, blobType, tbname,
columnName, config, pks, successCallback, errorCallback);
}
}
}
} else {
//error invalid pks.
var error = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidPksGiven,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidPksGiven, tbname)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
var connection = kony.sync.getConnectionOnly(dsname, dsname, errorCallback);
if(connection !== null){
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback,
single_transaction_error_callback);
}
};
kony.sync.single_binary_select_inline_execute = function(dsname, tbname, columnName, pks, config, blobType,
successCallback, errorCallback) {
var response = {};
function single_transaction_success_callback() {
sync.log.trace("Entering kony.sync.single_select_execute_binary_onDemand->single_select_binary_transaction_success");
}
function single_transaction_error_callback() {
sync.log.error("Entering kony.sync.single_select_execute_binary_onDemand->single_select_binary_transaction_failed");
}
function single_transaction_callback(tx) {
var scopename = kony.sync.scopes.syncTableScopeDic[tbname];
var scope = kony.sync.scopes[scopename];
var pkColumns = scope.syncTableDic[tbname].Pk_Columns;
//validate whether we get all pks in the pk table.
pks = kony.sync.validatePkTable(pkColumns, pks);
if(!kony.sync.isNullOrUndefined(pks)) {
var blobRef = kony.sync.getBlobRef(tx, tbname, columnName, pks, errorCallback);
if(!kony.sync.isNullOrUndefined(blobRef)) {
if (blobRef === -1) {
//No record exists with given pks.
response.pkTable = pks;
if(blobType === kony.sync.BlobType.BASE64) {
response.base64 = null;
} else {
response.filePath = null;
}
kony.sync.verifyAndCallClosure(successCallback, response);
} else {
//fetch from blob store manager.
kony.sync.blobManager.getBlobInline(tx, blobRef, blobType, tbname,
columnName, config, pks, successCallback, errorCallback);
}
} else {
//blob doesn't exist for given record.
response.pkTable = pks;
if(blobType === kony.sync.BlobType.BASE64) {
response.base64 = null;
} else {
response.filePath = null;
}
kony.sync.verifyAndCallClosure(successCallback, response);
}
} else {
//error invalid pks.
var error = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidPksGiven,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidPksGiven, tbname)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
if(kony.sync.isBinaryColumn(tbname, columnName) !== -1) {
var connection = kony.sync.getConnectionOnly(dsname, dsname, errorCallback);
if(connection !== null){
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback, single_transaction_error_callback);
}
} else {
//not a binary column. return empty object.
sync.log.warn("Request column is not a binary column. Empty response is sent");
kony.sync.verifyAndCallClosure(successCallback, response);
}
};
kony.sync.single_binary_select_execute = function(dsname, tbname, columnName, pks, config, blobType,
successCallback, errorCallback) {
if(kony.sync.isValidFunctionType(successCallback) && kony.sync.isValidFunctionType(errorCallback)) {
if(columnName === undefined || typeof(columnName) !== "string" || tbname === undefined ||
typeof(tbname) !== "string") {
var error = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidColumnParams,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidColumnParams)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
return;
}
var downloadPolicy = kony.sync.getDownloadPolicy(tbname, columnName);
sync.log.trace("download policy for the column "+tbname+"."+columnName+ " is "+downloadPolicy);
if(downloadPolicy !== kony.sync.notSupported) {
if(downloadPolicy !== kony.sync.inline) {
kony.sync.single_binary_select_ondemand_execute(dsname, tbname, columnName, pks,
config, blobType, successCallback, errorCallback);
} else {
//call inline base64 fetch.
kony.sync.single_binary_select_inline_execute(dsname, tbname, columnName, pks,
config, blobType, successCallback, errorCallback);
}
} else {
var error = kony.sync.getErrorTable(
kony.sync.errorCodeDownloadPolicyNotSupported,
kony.sync.getErrorMessage(kony.sync.errorCodeDownloadPolicyNotSupported, tbname+"."+columnName)
);
kony.sync.verifyAndCallClosure(errorCallback, error);
}
}
};
kony.sync.single_binary_select_base64_execute = function(dsname, tbname, columnName, pks, config,
successCallback, errorCallback){
sync.log.trace("Entering kony.sync.single_binary_select_base64_execute-> main function");
kony.sync.single_binary_select_execute(dsname, tbname, columnName, pks, config, kony.sync.BlobType.BASE64,
successCallback, errorCallback);
};
kony.sync.single_binary_select_file_execute = function(dsname, tbname, columnName, pks, config,
successCallback, errorCallback){
sync.log.trace("Entering kony.sync.single_binary_select_file_execute-> main function");
kony.sync.single_binary_select_execute(dsname, tbname, columnName, pks, config, kony.sync.BlobType.FILE,
successCallback, errorCallback);
};
/**
* API is used to fetch stats of binary.. (state, status, error, lastUpdatedTimeStamp)
* @param tbname
* @param columnName
* @param wc
* @param successCallback
* @param errorCallback
*/
kony.sync.insert_execute = function(tx, tbname, values, childRecordsArray ,error_callback, markForUpload, response) {
var callback_result;
sync.log.trace("Entering kony.sync.insert_execute");
//remove the binary values.
var blobMap = {};
if(!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname]) &&
!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns])) {
var binaryColumns = kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns];
for (var i = 0; i < binaryColumns.length; i++) {
if (!kony.sync.isNullOrUndefined(values[binaryColumns[i]]) && values[binaryColumns[i]].length > 0)
blobMap[binaryColumns[i]] = values[binaryColumns[i]];
delete values[binaryColumns[i]];
//keeping the blob ref as NULL.
values[kony.sync.binaryMetaColumnPrefix + binaryColumns[i]] = kony.sync.blobRefNotDefined;
}
}
sync.log.trace("removed blob values from the record "+JSON.stringify(values));
//check if pk_columns for autogenerated - false do not have not null values.
var tableinfo = kony.sync.getTableInfo(tbname);
if(kony.sync.isNullOrUndefined(tableinfo)) {
//invalid table name sent.
sync.log.error("invalid table name sent for insert operation "+tbname);
kony.sync.errorObject = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidTableName,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidTableName, tbname)
);
return false;
}
if(!kony.sync.isNullOrUndefined(tableinfo.Pk_Columns)) {
for (var j = 0; j < tableinfo.Pk_Columns.length; j++) {
var pkKey = tableinfo.Pk_Columns[j];
if(tableinfo.ColumnsDic[pkKey].Autogenerated === "false" && kony.sync.isNullOrUndefined(values[pkKey])) {
//received null for a non auto-generated pk.
sync.log.error("received null for pk column "+pkKey);
kony.sync.errorObject = kony.sync.getErrorTable(
kony.sync.errorCodeNullPrimaryKeyValue,
kony.sync.getErrorMessage(kony.sync.errorCodeNullPrimaryKeyValue, pkKey)
);
return false;
}
}
}
//CallBack_result contains AutoGenerated PK in hash ({id = value})
callback_result = kony.sync.insert(tx, tbname, values, error_callback, markForUpload);
if(response.hasOwnProperty(tbname)) {
//it is a child record. update the array.
response[tbname].push(callback_result);
} else {
response = callback_result;
}
if (callback_result === false || kony.sync.isNullOrUndefined(callback_result)) {
sync.log.error("error in inserting record into "+tbname);
return false;
} else {
sync.log.trace("inserted into "+tbname+" with result "+JSON.stringify(callback_result));
//if insert is successful create rows in blobstore manager for the binary columns.
if(Object.keys(blobMap).length > 0) {
var blobStoreIndices = kony.sync.blobstore_insert(tx, tbname, blobMap, error_callback);
sync.log.trace("inserted blobMap into the blobStoreManager. response is "+JSON.stringify(blobStoreIndices));
if(blobStoreIndices && Object.keys(blobStoreIndices).length > 0) {
//update the parent table with blob references.
var wcs = [];
for (var key in callback_result) {
var wc = {};
wc.key = key;
wc.value = callback_result[key];
wcs.push(wc);
}
var resultset = kony.sync.blobManager.updateParentWithBlobReference(tx, tbname, blobStoreIndices, wcs, error_callback);
sync.log.trace("updating the blob reference in the table " + tbname);
if (resultset === false || kony.sync.isNullOrUndefined(resultset)) {
sync.log.error("error in updating table " + tbname + " with blob references..");
return false;
}
} else{
sync.log.error("error in inserting blob data ");
return false;
}
}
}
//check for child records.
if(childRecordsArray.length > 0) {
sync.log.trace("There are child records... Inserting them");
for(var k = 0; k < childRecordsArray.length; k++) {
var childRecordObject = childRecordsArray[k];
//child records are json objects with childTable name as key.
for(var table in childRecordObject) {
if(!response.hasOwnProperty(table)) {
response[table] = [];
}
//child records are expected to be arary.
sync.log.trace("inserting child record in table "+table);
if(childRecordObject[table] instanceof Array) {
for (var childRecordsCount = 0; childRecordsCount < childRecordObject[table].length; childRecordsCount++) {
//before inserting child records, first remove the nested child records
var childRecordToBeInserted = childRecordObject[table][childRecordsCount];
var nestedChildRecords = kony.sync.getChildRecords(table, childRecordToBeInserted);
sync.log.trace("child records for "+table+" are "+JSON.stringify(nestedChildRecords));
//getting the relationship attributes
var parentRelationAttributes = kony.sync.getParentRelationshipAttributes(tbname, table);
sync.log.trace("parentRelationAttributes for "+tbname+" and "+table+" are "+JSON.stringify(parentRelationAttributes));
//adding the values from the generated primary keys.
if(!kony.sync.isNullOrUndefined(parentRelationAttributes)) {
for (var count in parentRelationAttributes) {
var relationAttribute = parentRelationAttributes[count];
//check if callback has mapping source attribute
if (callback_result.hasOwnProperty(relationAttribute[kony.sync.sourceAttribute]) && !kony.sync.isNullOrUndefined(callback_result[relationAttribute[kony.sync.sourceAttribute]])) {
childRecordToBeInserted[relationAttribute[kony.sync.targetAttribute]] = callback_result[relationAttribute[kony.sync.sourceAttribute]];
} else if (values.hasOwnProperty(relationAttribute[kony.sync.sourceAttribute]) && !kony.sync.isNullOrUndefined(values[relationAttribute[kony.sync.sourceAttribute]])) {
childRecordToBeInserted[relationAttribute[kony.sync.targetAttribute]] = values[relationAttribute[kony.sync.sourceAttribute]];
} else {
//no mapping source attribute found.
kony.sync.errorObject = kony.sync.getErrorTable(
kony.sync.errorCodeParentMappingAttributeNotFound,
kony.sync.getErrorMessage(kony.sync.errorCodeParentMappingAttributeNotFound, relationAttribute[kony.sync.sourceAttribute])
);
sync.log.error("no mapping source attribute found from values sent.." + tbname);
return false;
}
}
}
var childResponse = {};
var childRecordInsertResult = kony.sync.insert_execute(tx, table, childRecordToBeInserted, nestedChildRecords, error_callback, markForUpload, childResponse);
if (childRecordInsertResult === false || kony.sync.isNullOrUndefined(childRecordInsertResult)) {
sync.log.error("error in inserting record "+JSON.stringify(childRecordToBeInserted));
return false;
}
if(response.hasOwnProperty(table)) {
response[table].push(childRecordInsertResult);
}
sync.log.trace("after inserting record in "+table+" response is "+JSON.stringify(childRecordInsertResult));
}
} else {
kony.sync.errorObject = kony.sync.getErrorTable(
kony.sync.errorCodeChildObjectShouldBeArray,
kony.sync.getErrorMessage(kony.sync.errorCodeChildObjectShouldBeArray)
);
sync.log.error("improper format for sending child objects. ");
return false;
}
}
}
}
sync.log.trace("callback_result returning for table "+tbname+ " is "+JSON.stringify(callback_result));
return callback_result;
};
kony.sync.update_execute = function(tx, tbname, values, childRecordsArray, wc, isBatch, markForUpload, primaryKey , error_callback) {
var callback_result;
var blobMap = {};
if(!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname]) &&
!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns])) {
var binaryColumns = kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns];
for (var i = 0; i < binaryColumns.length; i++) {
if(!kony.sync.isNullOrUndefined(values[binaryColumns[i]]) && values[binaryColumns[i]].length > 0)
blobMap[binaryColumns[i]] = values[binaryColumns[i]];
delete values[binaryColumns[i]];
}
}
if (isBatch === true) {
callback_result = kony.sync.updateBatch(tx, tbname, values, wc, markForUpload, primaryKey);
} else {
callback_result = kony.sync.update(tx, tbname, values, wc, markForUpload);
}
if(callback_result===false || kony.sync.isNullOrUndefined(callback_result)){
return false;
} else {
if(Object.keys(blobMap).length > 0){
var blobStoreIndices = kony.sync.blobstore_update(tx, tbname, blobMap, wc, isBatch, error_callback);
if(blobStoreIndices && Object.keys(blobStoreIndices).length > 0) {
var results = kony.sync.blobManager.updateParentWithBlobReference(tx, tbname, blobStoreIndices, wc, error_callback);
if (results === false || results === null) {
sync.log.error("error in updating parent table with blob reference..");
return false;
}
} else{
sync.log.error("Null returned from blobstore_update.");
return false;
}
}
//check for the child records.
if(childRecordsArray.length > 0) {
for(var k = 0; k < childRecordsArray.length; k++){
var childRecordObject = childRecordsArray[k];
for(var table in childRecordObject) {
sync.log.trace("updating child record in table "+table);
if(childRecordObject[table] instanceof Array) {
for (var childRecordsCount = 0; childRecordsCount < childRecordObject[table].length; childRecordsCount++) {
//first remove nested childrecords from the values table.
var childRecordToBeUpdated = childRecordObject[table][childRecordsCount];
var nestedChildRecords = kony.sync.getChildRecords(table, childRecordToBeUpdated);
sync.log.trace("child records for "+table+" are "+JSON.stringify(nestedChildRecords));
//get pkTable from the childRecord.
var pkTable = kony.sync.getPkTableFromJSON(childRecordToBeUpdated, table);
sync.log.trace("pkTable for the table "+table+" is "+JSON.stringify(pkTable));
if(pkTable && Object.keys(pkTable).length > 0) {
//create a whereclause from pkTable.
var whereClause = [];
for(var key in pkTable) {
if(!kony.sync.isNullOrUndefined(pkTable[key])) {
var child_wc = {};
child_wc.key = key;
child_wc.value = pkTable[key];
child_wc.comptype = "AND";
whereClause.push(child_wc);
} else {
//null send as pkValue. throw error
sync.log.error("received null for pk column "+pkTable[key]);
kony.sync.errorObject = kony.sync.getErrorTable(
kony.sync.errorCodeNullPrimaryKeyValue,
kony.sync.getErrorMessage(kony.sync.errorCodeNullPrimaryKeyValue, pkTable[key])
);
return false;
}
}
if(whereClause.length > 0) {
var childRecordUpdateResult = kony.sync.update_execute(tx, table, childRecordToBeUpdated,
nestedChildRecords, whereClause, isBatch, markForUpload, primaryKey, error_callback);
if (childRecordUpdateResult === false || kony.sync.isNullOrUndefined(childRecordUpdateResult)) {
sync.log.error("error in updating record " + JSON.stringify(childRecordUpdateResult));
return false;
}
sync.log.trace("after updating record in "+table+" response is "+JSON.stringify(childRecordUpdateResult));
}
} else {
kony.sync.errorObject = kony.sync.getErrorTable(
kony.sync.errorCodeInvalidPksGiven,
kony.sync.getErrorMessage(kony.sync.errorCodeInvalidPksGiven, table)
);
sync.log.error("invalid pks send for update of record in "+table);
return false;
}
}
} else {
sync.log.error("improper format for sending child objects. ");
kony.sync.errorObject = kony.sync.getErrorTable(
kony.sync.errorCodeChildObjectShouldBeArray,
kony.sync.getErrorMessage(kony.sync.errorCodeChildObjectShouldBeArray)
);
return false;
}
}
}
}
}
return callback_result;
};
kony.sync.single_insert_execute = function (dsname, tbname, values, success_callback, error_callback, markForUpload) {
sync.log.trace("Entering kony.sync.single_insert_execute-> main function");
var callback_result = [];
var dbname = dsname;
function single_transaction_success_callback() {
sync.log.trace("Entering kony.sync.single_insert_execute->single_transaction_success_callback");
if (callback_result) {
kony.sync.verifyAndCallClosure(success_callback, callback_result);
}
}
function single_transaction_failure_callback() {
sync.log.error("Entering kony.sync.single_insert_execute->single_transaction_failure_callback");
sync.log.error("Entering kony.sync.single_insert_execute->single_transaction_failure_callback : ", kony.sync.errorObject);
kony.sync.verifyAndCallClosure(error_callback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
function single_transaction_callback(tx) {
//from the values table, remove the child table records if exists.
var childRecordsArray = kony.sync.getChildRecords(tbname, values);
var response = {};
callback_result = kony.sync.insert_execute(tx, tbname, values, childRecordsArray, error_callback, markForUpload, response);
if(kony.sync.isNullOrUndefined(callback_result) || callback_result === false) {
sync.log.error("single_insert_execute -> single_transaction_callback rolling back changes");
try {
kony.sync.rollbackTransaction(tx);
} catch(err) {
sync.log.error("single_insert_execute - error in rollbackTransaction ", err);
}
}
sync.log.info("response from insert operation "+JSON.stringify(callback_result));
}
var connection = kony.sync.getConnectionOnly(dbname, dbname, error_callback);
if(connection !== null){
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback, single_transaction_failure_callback);
}
};
kony.sync.single_update_execute = function (dsname, tbname, values, wc, success_callback, error_callback, isBatch, markForUpload, primaryKey) {
sync.log.trace("Entering kony.sync.single_update_execute ");
var callback_result = {};
var dbname = dsname;
function single_transaction_success_callback() {
sync.log.trace("Entering kony.sync.single_update_execute->single_transaction_success_callback ");
kony.sync.verifyAndCallClosure(success_callback, callback_result);
}
function single_transaction_error_callback() {
sync.log.error("Entering kony.sync.single_update_execute->single_transaction_error_callback");
sync.log.error("Entering kony.sync.single_update_execute->single_transaction_error_callback :", kony.sync.errorObject);
kony.sync.verifyAndCallClosure(error_callback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
function single_transaction_callback(tx){
sync.log.trace("Entering kony.sync.single_update_execute->single_transaction_callback");
//from the values table, remove the child table records if exists.
var childRecordsArray = kony.sync.getChildRecords(tbname, values);
//(tx, tbname, values,childRecordsArray, wc, isBatch, markForUpload, primaryKey , error_callback)
callback_result = kony.sync.update_execute(tx, tbname, values, childRecordsArray, wc, isBatch, markForUpload, primaryKey, error_callback);
if(kony.sync.isNullOrUndefined(callback_result) || callback_result === false) {
sync.log.error("single_update_execute -> single_transaction_callback rolling back changes");
try {
kony.sync.rollbackTransaction(tx);
} catch(err) {
sync.log.error("single_insert_execute - error in rollbackTransaction ", err);
}
}
sync.log.info("response from update operation "+JSON.stringify(callback_result));
}
var connection = kony.sync.getConnectionOnly(dbname, dbname, error_callback, "Single Update Execute");
if(connection !== null){
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback, single_transaction_error_callback, "Single Update Execute");
}
};
kony.sync.delete_execute = function(tx, tbname, wc, isBatch, isLocal, markForUpload, error_callback) {
//get records satisfying given where clause for tbname.
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tbname);
kony.sync.qb_where(query, wc);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var result_set = kony.sync.executeSql(tx, sql, params, error_callback);
if(result_set !== null && result_set!== false) {
//get child relationships for the tbname.
var relationships = kony.sync.getRelationshipsForTable(tbname);
sync.log.trace("delete_execute relationships for tbname "+tbname+" are "+JSON.stringify(relationships));
if (!kony.sync.isNullOrUndefined(relationships) && !kony.sync.isNullOrUndefined(relationships[kony.sync.oneToMany])) {
sync.log.trace("tbname "+tbname+" has oneToMany relationships");
var oneToManyRelationships = relationships[kony.sync.oneToMany];
for (var j = 0; j < oneToManyRelationships.length; j++) {
//get the target object and delete.
var relationshipTargetObject = oneToManyRelationships[j][kony.sync.targetObject];
sync.log.trace("target object on oneToMany relation for "+tbname+" is "+relationshipTargetObject);
//fetch the source-target mapping for the one-many relation.
var parentRelationAttributes = kony.sync.getParentRelationshipAttributes(tbname, relationshipTargetObject);
sync.log.trace("parentRelationAttributes for "+tbname+" and "+relationshipTargetObject+" are "+JSON.stringify(parentRelationAttributes));
//parse through the result_Set and create where clause for the childs to get deleted.
if(parentRelationAttributes) {
for (var k = 0; k < result_set.rows.length; k++) {
//creating a where clause to delete childs as well.
var whereClause = [];
for (var count in parentRelationAttributes) {
var relationAttribute = parentRelationAttributes[count];
var rowItem = kony.db.sqlResultsetRowItem(tx, result_set, k);
if (!kony.sync.isNullOrUndefined(rowItem[relationAttribute[kony.sync.sourceAttribute]])) {
var child_wc = {};
child_wc.key = relationAttribute[kony.sync.targetAttribute];
child_wc.value = rowItem[relationAttribute[kony.sync.sourceAttribute]];
whereClause.push(child_wc);
}
}
sync.log.trace("whereClause for deleting in tbname " + relationshipTargetObject + " is " + JSON.stringify(whereClause));
//delete the child first before deleting the parent.
if (whereClause.length > 0) {
var childRecordDeleteResult = kony.sync.delete_execute(tx, relationshipTargetObject, whereClause, isBatch, isLocal, markForUpload, error_callback);
if (childRecordDeleteResult === null || childRecordDeleteResult === false) {
return false;
}
} else {
//no child records to delete..
sync.log.trace("For table " + tbname + " no child records to delete...");
}
}
}
}
}
//delete the record once, childs are deleted.
var callback_result;
var isBlobDeleted = kony.sync.blobstore_delete(tx, tbname, wc, isBatch, function(err){
sync.log.error("kony.sync.delete_exeucte - error in deleting blob values for the table "+tbname);
});
sync.log.trace("kony.sync.delete_execute - result from blobstore_delete is "+isBlobDeleted);
if(isBlobDeleted) {
if (isBatch === true) {
callback_result = kony.sync.deleteBatch(tx, tbname, wc, isLocal, markForUpload, error_callback);
} else {
callback_result = kony.sync.remove(tx, tbname, wc, isLocal, markForUpload, error_callback);
}
}
if(callback_result===false){
sync.log.error("kony.sync.delete_execute - error in deletion of records in tbname "+tbname);
return false;
}
return callback_result;
}
sync.log.error("kony.sync.delete_execute - error in sql select operation on the table "+tbname);
return false;
};
kony.sync.single_delete_execute = function (dsname, tbname, wc, success_callback, error_callback, isBatch, isLocal, markForUpload) {
sync.log.trace("Entering kony.sync.single_delete_execute-> main function");
var callback_result = [];
var dbname = dsname;
var isError = false;
function single_transaction_success_callback() {
sync.log.trace("Entering kony.sync.single_delete_execute->single_transaction_success_callback ");
kony.sync.verifyAndCallClosure(success_callback, callback_result);
}
function single_transaction_callback(tx) {
sync.log.trace("Entering kony.sync.single_delete_execute->single_transaction_callback");
callback_result = kony.sync.delete_execute(tx, tbname, wc, isBatch, isLocal, markForUpload, error_callback);
if(kony.sync.isNullOrUndefined(callback_result) || callback_result === false) {
sync.log.error("single_delete_execute -> single_transaction_callback rolling back changes");
try {
kony.sync.rollbackTransaction(tx);
} catch(err) {
sync.log.error("single_insert_execute - error in rollbackTransaction ", err);
}
}
sync.log.info("response from delete operation "+JSON.stringify(callback_result));
}
function single_transaction_error_callback() {
sync.log.error("Entering kony.sync.single_delete_execute->single_transaction_error_callback");
sync.log.error("Entering kony.sync.single_delete_execute->single_transaction_error_callback :", kony.sync.errorObject);
kony.sync.verifyAndCallClosure(error_callback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
var connection = kony.sync.getConnectionOnly(dbname, dbname, error_callback, "Single Delete Execute");
if(connection !== null){
kony.sync.startTransaction(connection, single_transaction_callback, single_transaction_success_callback, single_transaction_error_callback, "Single Delete Execute");
}
};
kony.sync.massInsert = function (dsname, tbname, valuesArray, successCallback, errorCallback, markForUpload) {
sync.log.trace("Entering kony.sync.massInsert-> main function");
var callbackResult = [];
var dbname = dsname;
function massInsertTransactionSuccessCallback() {
sync.log.trace("Entering kony.sync.massInsert->massInsertTransactionSuccessCallback");
kony.sync.verifyAndCallClosure(successCallback, callbackResult);
}
function massInsertTransactionErrorCallback() {
sync.log.error("Entering kony.sync.massInsert->massInsertTransactionErrorCallback");
kony.sync.verifyAndCallClosure(errorCallback, kony.sync.errorObject);
}
function massInsertTransactionCallback(tx) {
sync.log.trace("Entering kony.sync.massInsert->massInsertTransactionCallback");
//CallBack_result contains AutoGenerated PK in hash ({id = value})
for (var i in valuesArray) {
callbackResult.push(kony.sync.insert(tx, tbname, valuesArray[i], null, markForUpload));
}
}
var connection = kony.sync.getConnectionOnly(dbname, dbname);
kony.sync.startTransaction(connection, massInsertTransactionCallback, massInsertTransactionSuccessCallback, massInsertTransactionErrorCallback);
};
kony.sync.massUpdate = function(dbname, tbname, inputArray, successCallback, errorCallback, markForUpload, primaryKey) {
sync.log.trace("Entering kony.sync.massUpdate");
var callbackResultTemp;
var callbackResult = 0;
var isError = false;
var connection = kony.sync.getConnectionOnly(dbname, dbname, errorCallback);
if(connection !== null){
kony.sync.startTransaction(connection, transactioncallback, transactionSuccessCallback, transactionErrorCallback);
}
function transactionSuccessCallback() {
sync.log.trace("Entering kony.sync.massUpdate-> transactionSuccessCallback");
if(!isError){
kony.sync.verifyAndCallClosure(successCallback, {rowsUpdated:callbackResult});
}
}
function transactioncallback(tx) {
sync.log.trace("Entering kony.sync.massUpdate-> transactioncallback");
for(var i in inputArray){
callbackResultTemp = kony.sync.updateBatch(tx, tbname, inputArray[i].changeSet, inputArray[i].whereClause, markForUpload, primaryKey);
if(callbackResultTemp === false){
isError = true;
return;
}
callbackResult += callbackResultTemp.rowsupdated;
}
}
function transactionErrorCallback() {
if (!isError) {
kony.sync.showTransactionError(errorCallback, "Sync Mass Update");
}else{
sync.log.error("Entering kony.sync.massUpdate->transactionErrorCallback :", kony.sync.errorObject);
kony.sync.verifyAndCallClosure(errorCallback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
};
/*This method will open a transaction and then executes the array of queries*/
kony.sync.executeQueries = function(queries, callback){
sync.log.trace("Entering kony.sync.executeQueries");
if(kony.sync.isNullOrUndefined(queries)){
kony.sync.verifyAndCallClosure(callback, true);
return;
}
var dbname = kony.sync.scopes[0][kony.sync.scopeDataSource];
var connection = kony.sync.getConnectionOnly(dbname, dbname);
var isError = false;
if(connection !== null){
kony.sync.startTransaction(connection, transactioncallback, transactionSuccessCallback, transactionErrorCallback);
}
function transactioncallback(tx){
for(var i=0; i<queries.length; i++){
if(kony.sync.executeSql(tx, queries[i], null)===false){
isError = true;
return;
}
}
}
function transactionSuccessCallback(){
kony.sync.verifyAndCallClosure(callback, false);
}
function transactionErrorCallback(){
kony.sync.verifyAndCallClosure(callback, true, kony.sync.getTransactionError(isError));
}
};
/*This method will execute the array of queries provided the transaction is already open*/
kony.sync.executeQueriesInTransaction = function(tx, queries){
sync.log.trace("Entering kony.sync.executeQueriesInTransaction");
if(kony.sync.isNullOrUndefined(queries)){
return true;
}
for(var i=0; i<queries.length; i++){
if(kony.sync.executeSql(tx, queries[i], null)===false){
return false;
}
}
return true;
};
//this API is for developers who want to execute custom sql SELECT queries
sync.executeSelectQuery = function (query, successcallback, errorcallback) {
sync.log.trace("Entering sync.executeSelectQuery -> main function");
var dbname = kony.sync.scopes[0][kony.sync.scopeDataSource];
var connection = kony.sync.getConnectionOnly(dbname, dbname);
var resultItems = [];
var isError = false;
if (connection !== null) {
kony.sync.startTransaction(connection, executeSelectQueryTransactionCallback, executeSelectQuerySuccessCallback, executeSelectQueryErrorCallback);
}
function executeSelectQueryTransactionCallback(tx) {
sync.log.trace("Entering sync.executeSelectQuery -> transaction callback");
var resultSet = kony.sync.executeSql(tx, query, null);
if (resultSet === false) {
isError = true;
return;
}
for (var i = 0; i < resultSet.rows.length; i++) {
resultItems[i] = kony.db.sqlResultsetRowItem(tx, resultSet, i);
}
}
function executeSelectQuerySuccessCallback() {
sync.log.trace("Entering sync.executeSelectQuery -> success callback");
kony.sync.verifyAndCallClosure(successcallback, resultItems);
}
function executeSelectQueryErrorCallback() {
sync.log.trace("Entering sync.executeSelectQuery -> error callback");
kony.sync.callTransactionError(isError, errorcallback);
}
};
// **************** End konySyncQueryProvider.js*******************
// **************** End konySyncQueryProvider.js*******************
// **************** Start KonySyncReset.js*******************
if (typeof(kony.sync) === "undefined") {
kony.sync = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
kony.sync.scopeReset = function (scopename, successcallback, failurecallback) {
sync.log.trace("Entering kony.sync.scopeReset->main function");
var currentScope = kony.sync.scopes[scopename];
var dbname = kony.sync.getDBName();
var isStatementError = false;
var exceptionMessage = null;
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, failurecallback);
if(dbconnection!==null){
kony.sync.startTransaction(dbconnection, ScopeResetTransaction, ScopeResetSuccess, ScopeResetFailure);
}
function ScopeResetTransaction(tx) {
sync.log.trace("Entering kony.sync.scopeReset->transaction function");
try{
if(!kony.sync.isNullOrUndefined(currentScope.ScopeTables)){
for (var i = 0; i < currentScope.ScopeTables.length; i++) {
var syncTable = currentScope.ScopeTables[i];
var tbname = syncTable.Name;
if (!kony.sync.deleteTable(tx, tbname)) {
isStatementError = true;
break;
}
}
}
}
catch(e){
exceptionMessage = e;
throw("");
}
if (!kony.sync.resetMetaTableForScope(tx, scopename)) {
isStatementError = true;
}
}
function ScopeResetSuccess() {
sync.log.trace("Entering kony.sync.scopeReset->success callback function");
kony.sync.verifyAndCallClosure(successcallback, "Scope Reset Successful");
}
function ScopeResetFailure() {
sync.log.error("Entering kony.sync.scopeReset->failure callback function");
if (isStatementError) {
kony.sync.verifyAndCallClosure(failurecallback, kony.sync.errorObject);
kony.sync.errorObject = null;
} else {
if(exceptionMessage !== null){
kony.sync.verifyAndCallClosure(failurecallback, kony.sync.getErrorTable(kony.sync.errorUnknown, kony.sync.getErrorMessage(kony.sync.errorUnknown,"Scope Reset",exceptionMessage),null));
}
else{
kony.sync.showTransactionError(failurecallback, "Scope Reset");
}
}
}
};
kony.sync.deleteTable = function (tx, tbname) {
sync.log.trace("Entering kony.sync.deleteTable function");
if (kony.sync.deleteTableHelper(tx, tbname + kony.sync.historyTableName) === false) {
return false;
}
if (kony.sync.deleteTableHelper(tx, tbname + kony.sync.originalTableName) === false) {
return false;
}
if (kony.sync.deleteTableHelper(tx, tbname) === false) {
return false;
}
return true;
};
kony.sync.deleteTableHelper = function (tx, tbname) {
sync.log.trace("Entering kony.sync.deleteTableHelper function");
var query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, tbname);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
};
kony.sync.resetMetaTableForScope = function (tx, scopeName) {
sync.log.trace("Entering kony.sync.resetMetaTableForScope function");
var query = kony.sync.qb_createQuery();
var wcs = [];
kony.sync.qb_set(query, {
versionnumber : 0,
lastserversynccontext : "",
replaysequencenumber : 0,
lastgeneratedid : -1
});
kony.table.insert(wcs, {
key : kony.sync.metaTableScopeColumn,
value : scopeName,
optype : "EQ"
});
kony.sync.qb_where(query, wcs);
kony.sync.qb_update(query, kony.sync.metaTableName);
//local sql = "insert into "..kony.sync.metaTableName.." (id,scopename,versionnumber,lastserversynccontext,replaysequencenumber,lastgeneratedid) values ('"..id.."','"..scope.ScopeName.."','0','','0','-1')"
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
return kony.sync.executeSql(tx, sql, params);
};
// **************** End KonySyncReset.js*******************
// **************** Start KonySyncRetryHelper.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync)=== "undefined"){
sync = {};
}
//Repetitively calls a service until number of attempts
kony.sync.retryServiceCall = function(url, result, infoObj, retryCount, callback, params){
sync.log.trace("Entering kony.sync.retryServiceCall");
sync.log.error("Error while hitting " + url + " : ", result);
sync.log.info("Retrying[" + retryCount + " retries left] ....");
if(kony.sync.isSyncStopped){
kony.sync.stopSyncSession();
return;
}
var params1 = kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onRetry], {"request":params, "errorResponse":result, "retryCount":(kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey]-retryCount)});
if(!kony.sync.isNull(params1)){
params = params1;
}
var retryWait = 1; //default retry time is 1 second
if (!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.retryWaitKey])) {
retryWait = kony.sync.tonumber(kony.sync.currentSyncConfigParams[kony.sync.retryWaitKey]);
}
if(!kony.sync.isAppInBackground){
kony.timer.schedule("syncRetryTimer", retryTimerCallback, retryWait, false);
}else{
retryTimerCallback();
}
function downloadNetworkCallbackStatus(status, callResult, info){
if(status === 400){
sync.log.trace("Entering kony.sync.retryServiceCall->downloadNetworkCallbackStatus");
//fallback when opstatus < 0
if(result.opstatus < 0){
sync.log.info("Got result.opstatus:" + result.opstatus + " and result.errcode:" + result.errcode + "setting errcode to opstatus");
result.opstatus = result.errcode;
}
if(retryCount > 0 && kony.sync.checkForRetryErrorCodes(callResult.opstatus)){
retryCount--;
kony.sync.retryServiceCall(url, callResult, info, retryCount, callback, params);
}
else{
callback(callResult, info, retryCount);
}
}else if(status === 300){
callback(kony.sync.getNetworkCancelError(),info,retryCount);
}
}
function retryTimerCallback() {
sync.log.trace("Entering kony.sync.retryServiceCall->retryTimerCallback");
kony.sync.invokeServiceAsync(url, params, downloadNetworkCallbackStatus, infoObj);
}
};
//Checks whether an error code is eligible for retry or not
kony.sync.checkForRetryErrorCodes = function(key){
sync.log.trace("Entering kony.sync.checkForRetryErrorCodes");
//#ifdef KONYSYNC_IOS
var deviceInfo = kony.os.deviceInfo();
if(deviceInfo.osversion < 7){
if(!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.retryErrorCodes])){
return kony.sync.contains(kony.sync.currentSyncConfigParams[kony.sync.retryErrorCodes], key);
}
else{
return kony.sync.contains([1000, 1013, 1014, 1015], key);
}
}else{
return key === 1012;
}
//#else
if(!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.retryErrorCodes])){
return kony.sync.contains(kony.sync.currentSyncConfigParams[kony.sync.retryErrorCodes], key);
}
else{
return kony.sync.contains([1000, 1013, 1014, 1015], key);
}
//#endif
};
kony.sync.eligibleForRetry = function(opstatus, info){
sync.log.trace("Entering kony.sync.eligibleForRetry");
return !kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey]) &&
info > 0 && kony.sync.checkForRetryErrorCodes(opstatus);
};
// **************** End KonySyncRetryHelper.js*******************
// **************** Start KonySyncRollBack.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
kony.sync.konySyncRollBackPendingChanges = function(tbname, dbname, wcs, successcallback, errorcallback, isGlobal, count) {
sync.log.trace("Entering kony.sync.konySyncRollBackPendingChanges-> main function");
var isSuccess = true;
var totalRows = 0;
var pkNotFound = false;
var isStatementError = false;
function single_execute_sql_transaction(tx) {
sync.log.trace("Entering kony.sync.konySyncRollBackPendingChanges->single_execute_sql_transaction ");
if (isGlobal === true) {
totalRows = kony.sync.konySyncRollBackGlobal(tx, errorcallback);
isSuccess = totalRows===false?false:true;
} else if (!kony.sync.isNullOrUndefined(wcs)) {
totalRows = kony.sync.konySyncRollBackRow(tx, tbname, wcs, errorcallback);
if(totalRows===null){
pkNotFound = true;
isSuccess = false;
}
else if(totalRows===false){
isStatementError = true;
isSuccess = false;
}
else{
isSuccess = true;
totalRows = 1;
}
} else {
totalRows = kony.sync.konySyncRollBackTable(tx, tbname, errorcallback);
isSuccess = totalRows===false?false:true;
}
}
function single_transactionErrorCallback(){
sync.log.error("Entering kony.sync.konySyncRollBackPendingChanges->single_transactionErrorCallback ");
if(isSuccess){
kony.sync.showTransactionError(errorcallback);
}else{
sync.log.error("Entering kony.sync.konySyncRollBackPendingChanges->single_transactionErrorCallback : ", kony.sync.errorObject);
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
function single_execute_sql_transactionSucessCallback() {
sync.log.trace("Entering kony.sync.konySyncRollBackPendingChanges->single_execute_sql_transactionSucessCallback ");
if(pkNotFound === true){
kony.sync.verifyAndCallClosure(errorcallback);
return;
}
if (isGlobal === true) {
if(kony.sync.isNull(count)){
count = 0;
}
count+=totalRows;
if (kony.sync.rollbackCurrentScope.Index === kony.sync.scopes.scopecount - 1) {
kony.sync.verifyAndCallClosure(successcallback,{rowsrolledback:count});
} else {
kony.sync.rollbackCurrentScope = kony.sync.scopes[kony.sync.rollbackCurrentScope.Index + 1];
kony.sync.konySyncRollBackPendingChanges(null, null, null, successcallback, errorcallback, true, count);
}
} else {
kony.sync.verifyAndCallClosure(successcallback,{rowsrolledback:totalRows});
}
}
try{
if (isGlobal === true) {
if (kony.sync.isNullOrUndefined(kony.sync.rollbackCurrentScope)) {
kony.sync.rollbackCurrentScope = kony.sync.scopes[0];
sync.log.info("RollBacking Global with Scope name : " + kony.sync.rollbackCurrentScope[kony.sync.scopeName] + " and with DBName : " + kony.sync.rollbackCurrentScope[kony.sync.scopeDataSource]);
}
dbname = kony.sync.rollbackCurrentScope[kony.sync.scopeDataSource];
}
var dbconnection = kony.sync.getConnectionOnly(dbname, dbname, errorcallback);
if(dbconnection !== null){
kony.sync.startTransaction(dbconnection, single_execute_sql_transaction, single_execute_sql_transactionSucessCallback, single_transactionErrorCallback, "Single Execute");
}
}
catch(e) {
sync.log.error("Unknown error occurred during rollback", e);
kony.sync.verifyAndCallClosure(errorcallback,kony.sync.getErrorTable(kony.sync.errorUnknown, kony.sync.getErrorMessage(kony.sync.errorUnknown,"Rollback",e),null));
}
};
kony.sync.konySyncRollBackTable = function(tx, tbname, errorcallback) {
sync.log.trace("Entering kony.sync.konySyncRollBackTable");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, tbname + kony.sync.originalTableName);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultset = kony.sync.executeSql(tx, sql, params, errorcallback);
if(resultset === false){
return false;
}
var num_records = resultset.rows.length;
sync.log.debug("Number of records to rollback in " + tbname + "=" + num_records);
for (var i = 0; i <= num_records - 1; i++) {
var record = kony.db.sqlResultsetRowItem(tx, resultset, i);
var tableinfo = kony.sync.getTableInfo(tbname);
var wcs = [];
if(!kony.sync.isNullOrUndefined(tableinfo.Pk_Columns)){
for (var j = 0; j < tableinfo.Pk_Columns.length; j++) {
var pk = tableinfo.Pk_Columns[j];
var wc = [];
wc.key = pk;
wc.value = record[pk];
kony.table.insert(wcs, wc);
}
}
sync.log.debug("Rollbacking Record with Primary Key :", wcs);
if(!kony.sync.konysyncRollBackOriginal(tx, tbname, record, wcs, errorcallback)){
return false;
}
}
return num_records;
};
kony.sync.konySyncRollBackGlobal = function(tx) {
sync.log.trace("Entering kony.sync.konySyncRollBackGlobal");
var noOfScopes = kony.sync.scopes.length;
for(var i=0; i<noOfScopes; i++) {
var scope = kony.sync.scopes[i];
var totalRows = 0;
if(!kony.sync.isNullOrUndefined(scope.ScopeTables)){
for (var j = 0; j < scope.ScopeTables.length; j++) {
var syncTable = scope.ScopeTables[j];
sync.log.debug("Rollbacking Table :" + syncTable.Name);
var rows = kony.sync.konySyncRollBackTable(tx, syncTable.Name);
if(rows===false){
return false;
}
else{
totalRows += rows;
}
}
}
}
return totalRows;
};
kony.sync.konySyncRollBackRow = function(tx, tbname, wcs, errorcallback) {
sync.log.trace("Entering kony.sync.konySyncRollBackRow");
var record = kony.sync.getOriginalRow(tx, tbname + kony.sync.originalTableName, wcs, errorcallback);
if (null !== record && false !== record) {
return kony.sync.konysyncRollBackOriginal(tx, tbname, record, wcs);
}else{
return record;
}
};
kony.sync.konysyncRollBackOriginal = function(tx, tbname, values, wcs, errorcallback) {
sync.log.trace("Entering kony.sync.konysyncRollBackOriginal");
var originalchangetype = values[kony.sync.originalTableChangeTypeColumn] + "";
//delete the blob reference if exists.
var isBlobDeleted = kony.sync.blobstore_delete(tx, tbname, wcs, false, function(err){
sync.log.error("kony.sync.konysyncRollBackOriginal - error in deleting blob values for the table "+tbname);
});
if (isBlobDeleted) {
//add NULL to blobref columns..
sync.log.trace("kony.sync.konysyncRollBackOriginal - adding NULL values to blob ref columns for table "+tbname);
if (!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname]) && !kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns])) {
var binaryColumns = kony.sync.scopes.syncScopeBlobInfoMap[tbname][kony.sync.columns];
sync.log.trace("binary columns for tbname " + tbname + " are " + JSON.stringify(binaryColumns));
for (var i = 0; i < binaryColumns.length; i++) {
values[kony.sync.binaryMetaColumnPrefix + binaryColumns[i]] = kony.sync.blobRefNotDefined;
}
}
if (kony.sync.isrowexists(tx, tbname, wcs)) {
sync.log.trace("kony.sync.konysyncRollBackOriginal isrowexists = true");
if ((originalchangetype === kony.sync.insertColStatus) || (originalchangetype === kony.sync.insertColStatusDI)) {
sync.log.trace("kony.sync.konysyncRollBackOriginal - original change type is insert for values ",values);
if (!kony.sync.removeEx(tx, tbname, wcs, null, errorcallback)) {
return false;
}
} else if ((originalchangetype === kony.sync.updateColStatus) || (originalchangetype === kony.sync.updateColStatusDU)) {
//Revert to original values.
sync.log.trace("kony.sync.konysyncRollBackOriginal - original change type is update for values ", values);
values[kony.sync.mainTableChangeTypeColumn] = "-1";
values[kony.sync.mainTableSyncVersionColumn] = values[kony.sync.originalTableSyncVersionColumn];
values[kony.sync.originalTableChangeTypeColumn] = null;
values[kony.sync.originalTableSyncVersionColumn] = null;
if (!kony.sync.updateEx(tx, tbname, values, wcs, errorcallback)) {
return false;
}
} else if ((originalchangetype === kony.sync.deleteColStatus) || (originalchangetype === kony.sync.deleteColStatusDD)) {
//delete the row which has been inserted/updated with old values.
sync.log.trace("kony.sync.konysyncRollBackOriginal - original change type is delete for values ",values);
if (!kony.sync.removeEx(tx, tbname, wcs, null, errorcallback)) {
return false;
}
//Insert the row which has been deleted with old values.
values[kony.sync.mainTableChangeTypeColumn] = "-1";
values[kony.sync.mainTableSyncVersionColumn] = values[kony.sync.originalTableSyncVersionColumn];
values[kony.sync.mainTableHashSumColumn] = values[kony.sync.originalTableHashSumColumn];
values[kony.sync.originalTableChangeTypeColumn] = null;
values[kony.sync.originalTableSyncVersionColumn] = null;
if (!kony.sync.insertEx(tx, tbname, values, wcs, errorcallback)) {
return false;
}
}
}
else {
/*if ((originalchangetype === kony.sync.insertColStatus)) {
//Need not handle this case. Because inserted record has been deleted. So, it is already rollbacked.
} else*/
sync.log.trace("kony.sync.konysyncRollBackOriginal - isrowexists false");
if ((originalchangetype === kony.sync.updateColStatus) || (originalchangetype === kony.sync.updateColStatusDU)) {
//Insert the row which has been updated and deleted with old values.
sync.log.trace("kony.sync.konysyncRollBackOriginal - original change type is update for values ",values);
values[kony.sync.mainTableChangeTypeColumn] = "-1";
values[kony.sync.mainTableSyncVersionColumn] = values[kony.sync.originalTableSyncVersionColumn];
values[kony.sync.originalTableChangeTypeColumn] = null;
values[kony.sync.originalTableSyncVersionColumn] = null;
//kony.sync.insertEx(tx, tbname, values);
if (!kony.sync.insertEx(tx, tbname, values, null, errorcallback)) {
return false;
}
} else if ((originalchangetype === kony.sync.deleteColStatus) || (originalchangetype === kony.sync.deleteColStatusDD)) {
//Insert the row which has been deleted with old values.
sync.log.trace("kony.sync.konysyncRollBackOriginal - original change type is delete for values ",values);
values[kony.sync.mainTableChangeTypeColumn] = "-1";
values[kony.sync.mainTableSyncVersionColumn] = values[kony.sync.originalTableSyncVersionColumn];
values[kony.sync.originalTableChangeTypeColumn] = null;
values[kony.sync.originalTableSyncVersionColumn] = null;
if (!kony.sync.insertEx(tx, tbname, values, null, errorcallback)) {
return false;
}
}
}
if (!kony.sync.konySyncRollBackDeleteRow(tx, tbname, wcs, errorcallback)) {
return false;
}
return true;
} else {
sync.log.error("kony.sync.konysyncRollBackOriginal error in deleting blob data for table "+tbname);
return false;
}
}
kony.sync.konySyncRollBackDeleteRow = function(tx, tbname, wcs,errorcallback) {
sync.log.trace("Entering kony.sync.konySyncRollBackDeleteRow");
sync.log.debug("Deleting States in Original Tables with Primary Key : ", wcs);
if(kony.sync.removeEx(tx, tbname + kony.sync.originalTableName, wcs, errorcallback)===false){
return false;
}
if(kony.sync.removeEx(tx, tbname + kony.sync.historyTableName, wcs, errorcallback)===false){
return false;
}
return true;
};
// **************** End KonySyncRollBack.js*******************
// **************** Start KonySyncSchemaUpgrade.js*******************
/* This methods calls upgrade schema service and executes the scripts" */
kony.sync.upgradeSchema = function (callback) {
sync.log.trace("Entering kony.sync.upgradeSchema ");
sync.log.info("Calling upgradeSchema service...");
var contextParams = {};
contextParams.oldApplicationVersion = kony.sync.configVersion;
contextParams.newApplicationVersion = konysyncClientSyncConfig.Version;
var schemaUpgrade = kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeRequiredKey], contextParams);
if(schemaUpgrade === kony.sync.onUpgradeActionUploadUpgrade){
kony.sync.omitDownload = true;
kony.sync.forceUploadUpgrade = true;
kony.sync.currentScope = null;
kony.sync.schemaUpgradeErrorObject = upgradeRequiredCallback;
kony.sync.syncStartSession();
}else{ //(schemaUpgrade === kony.sync.onUpgradeActionUpgrade) //default policy
upgradeRequiredCallback();
}
function upgradeRequiredCallback(){
kony.sync.callSchemaUpgradeService(schemaUpgradeCallback);
}
function schemaUpgradeCallback(serverResponse) {
if (!kony.sync.isNullOrUndefined(serverResponse.opstatus) && serverResponse.opstatus !== 0) {
sync.log.error("Schema Upgrade Response : ", serverResponse);
if (!kony.sync.isNullOrUndefined(serverResponse.d)) {
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeQueriesDownloadErrorKey], kony.sync.getServerError(
serverResponse.d));
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], kony.sync.getServerError(
serverResponse.d));
} else {
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeQueriesDownloadErrorKey], kony.sync.getServerError(serverResponse));
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], kony.sync.getServerError(serverResponse));
}
kony.sync.isSessionInProgress = false;
return;
}
else if(kony.sync.isNullOrUndefined(serverResponse.d)){
kony.sync.isSessionInProgress = false;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeQueriesDownloadErrorKey], kony.sync.getServerError(serverResponse));
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], kony.sync.getServerError(serverResponse));
return;
}
if (serverResponse.d.error === "true") {
sync.log.error("Schema Upgrade Response : ", serverResponse);
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeQueriesDownloadErrorKey], kony.sync.getServerError(
serverResponse.d));
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], kony.sync.getServerError(
serverResponse.d));
kony.sync.isSessionInProgress = false;
return;
}
kony.sync.addServerDetails(kony.sync.currentSyncReturnParams, serverResponse);
if(serverResponse.d.upgradeavailable === "false"){
callback(false);
return;
}
//fetch alter scripts
var queries = [];
if(!kony.sync.isNullOrUndefined(serverResponse.d.script)){
for (var i = 0; i < serverResponse.d.script.length; i++) {
queries.push(serverResponse.d.script[i].sql);
}
kony.sync.schemaUpgradeContext = serverResponse.d.upgradecontext;
}
kony.sync.currentSyncReturnParams.upgradeScripts = queries;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeQueriesDownloadSuccessKey], kony.sync.currentSyncReturnParams);
delete kony.sync.currentSyncReturnParams.upgradeScripts;
var myQueries = null;
myQueries = kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeQueriesExecutionStartKey], {
upgradeScripts : queries
});
if (!kony.sync.isNullOrUndefined(myQueries)) {
queries = myQueries;
}
kony.sync.executeUpdateSchemaQueries(queries, kony.sync.schemaUpgradeContext, executeQueriesCallback, serverResponse.d.newapplicationversion);
}
function executeQueriesCallback(isError, errorInfo) {
if (isError) {
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeQueriesExecutionErrorKey], errorInfo);
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], errorInfo);
} else {
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeQueriesExecutionSuccessKey]);
kony.sync.schemaUpgradeNeeded = false; //do not call schema upgrade service again
kony.sync.omitUpload = true; //only download
kony.sync.schemaUpgradeDownloadPending = true;
kony.sync.resetsyncsessionglobals();
callback(true);
}
}
};
/*This method will be called in case of server notifies schema upgrade*/
kony.sync.onSchemaUpgradeErrorFromServer = function (msg) {
/* var contextParams = {};
contextParams.oldVersion = msg.oldApplicationVersion;
contextParams.newVersion = msg.newApplicationVersion;
contextParams.isMandatory = msg.mandatoryupgrade;*/
var schemaUpgrade = kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeRequiredKey], msg);
if(schemaUpgrade === kony.sync.onUpgradeActionUploadAbort){
//Upload and then Abort Sync Process
kony.sync.omitDownload = true;
kony.sync.forceUpload = true;
kony.sync.resetsyncsessionglobals();
kony.sync.schemaUpgradeErrorObject = msg;
kony.sync.syncStartSession();
}else{ //(schemaUpgrade === kony.sync.onUpgradeActionAbort) --default policy
//Abort Sync Process
kony.sync.validateScopeSession(true, msg);
} /*else if (schemaUpgrade === kony.sync.onUpgradeActionContinue) {
//Upgrade first and then continue with normal Sync Process
//kony.sync.upgradeSchema(kony.sync.syncStartSession);
} else if (schemaUpgrade === kony.sync.onUpgradeActionContinueOnlyUpload) {
//Upload first, then upgrade and then continue with normal Sync Process
kony.sync.omitDownload = true;
kony.sync.schemaUpgradeNeeded = true;
kony.sync.validateScopeSession();
}*/
};
/*This method will execute upgrade scripts, syncconfig table with upgradecontext
and metainfo table with 0,0"*/
kony.sync.executeUpdateSchemaQueries = function (queries, upgradeContext, callback, appVersion) {
sync.log.trace("Entering kony.sync.executeUpdateSchemaQueries");
if (kony.sync.isNullOrUndefined(queries)) {
kony.sync.verifyAndCallClosure(callback, true);
return;
}
var dbname = kony.sync.scopes[0][kony.sync.scopeDataSource];
var connection = kony.sync.getConnectionOnly(dbname, dbname);
var isError = false;
if (connection !== null) {
kony.sync.startTransaction(connection, transactioncallback, transactionSuccessCallback, transactionErrorCallback);
}
function transactioncallback(tx) {
/*Execute alter scripts*/
if (kony.sync.executeQueriesInTransaction(tx, queries) === false) {
isError = true;
return;
}
/*update syncconfig table with upgradecontext*/
var sql = "update " + kony.sync.syncConfigurationTableName + " set " +
kony.sync.syncConfigurationColumnSchemaUpgradeContext + " = '" + upgradeContext + "'";
if (kony.sync.executeSql(tx, sql, null) === false) {
isError = true;
return;
}
/*upgrade schemaupgradesynccontext in metatable to "0,0" to indicate that download for new columns is pending*/
sql = "update " + kony.sync.metaTableName + " set " + kony.sync.metaTableSchemaUpgradeSyncTimeColumn + " = '0,0' where " + kony.sync.metaTableSyncTimeColumn + " <> '' and " + kony.sync.metaTableSyncTimeColumn + " is not null" ;
if (kony.sync.executeSql(tx, sql, null) === false) {
isError = true;
return;
}
}
function transactionSuccessCallback() {
kony.sync.configVersion = appVersion;
kony.sync.currentSyncConfigParams.appVersion = kony.sync.configVersion;
callback(false);
}
function transactionErrorCallback() {
callback(true, kony.sync.getTransactionError(isError));
}
};
/*This function marks download of data after schema upgrade complete for that particular scope*/
kony.sync.setSchemaUpgradeDownloadComplete = function (tx, scopename) {
if (kony.sync.schemaUpgradeDownloadPending) {
var sql = "update " + kony.sync.metaTableName + " set " + kony.sync.metaTableSchemaUpgradeSyncTimeColumn + " = '' where " + kony.sync.metaTableScopeColumn + " = '" + scopename + "'";
if (kony.sync.executeSql(tx, sql, null) === false) {
return false;
}
}
return true;
};
/*This method checks if download for schema upgrade is pending for any of the scopes*/
kony.sync.isDownloadPendingForSchemaUpgrade = function (callback) {
sync.log.trace("Entering kony.sync.isDownloadPendingForSchemaUpgrade");
var dbname = kony.sync.scopes[0][kony.sync.scopeDataSource];
var connection = kony.sync.getConnectionOnly(dbname, dbname);
var isError = false;
var pendingDownload = false;
if (connection !== null) {
kony.sync.startTransaction(connection, transactioncallback, transactionSuccessCallback, transactionErrorCallback);
}
function transactioncallback(tx) {
var sql = "select count(*) from " + kony.sync.metaTableName + " where " + kony.sync.metaTableSchemaUpgradeSyncTimeColumn + " = '0,0'";
var resultset = kony.sync.executeSql(tx, sql, null);
if (resultset === false) {
isError = true;
return;
}
var rowCount = kony.db.sqlResultsetRowItem(tx, resultset, 0);
if (rowCount["count(*)"] > 0) {
pendingDownload = true;
}
sql = "select * from " + kony.sync.syncConfigurationTableName;
resultset = kony.sync.executeSql(tx, sql, null);
if (resultset === false) {
isError = true;
return;
}
var rowitem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
kony.sync.schemaUpgradeContext = rowitem[kony.sync.syncConfigurationColumnSchemaUpgradeContext];
kony.sync.configVersion = rowitem[kony.sync.syncConfigurationColumnVersion];
}
function transactionSuccessCallback() {
callback(false, null, pendingDownload);
}
function transactionErrorCallback() {
kony.sync.verifyAndCallClosure(callback, true, kony.sync.getTransactionError(isError));
}
};
sync.performUpgrade = function (config) {
sync.log.trace("Entering kony.sync.performUpgrade");
if (kony.sync.validateSyncConfigParams("performUpgrade", config) === false) {
return;
}
kony.sync.verifyAndCallClosure(config[kony.sync.onPerformUpgradeStartKey]);
config[kony.sync.onSyncError] = config[kony.sync.onPerformUpgradeErrorKey];
config[kony.sync.onSyncSuccess] = config[kony.sync.onPerformUpgradeSuccessKey];
if (kony.sync.preProcessSyncConfig("performUpgrade", config, config[kony.sync.onSyncError]) === false) {
return;
}
kony.sync.isDownloadPendingForSchemaUpgrade(isDownloadPendingForSchemaUpgradeCallback);
function isDownloadPendingForSchemaUpgradeCallback(isError, errorObject, pending) {
if (isError) {
kony.sync.isSessionInProgress = false; // closing the session
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onSyncError], errorObject);
} else {
kony.sync.performOnlySchemaUpgrade = true;
if (pending) {
kony.sync.omitUpload = true; //only download
kony.sync.schemaUpgradeDownloadPending = true;
kony.sync.syncStartSession(); //download pending for already done schema upgrade
} else {
kony.sync.upgradeSchema(upgradeSchemaCallback); //download the scripts and upgrade
}
}
}
function upgradeSchemaCallback(upgrade){
if(upgrade){
kony.sync.syncStartSession(); //download initial data for new columns
}else{
kony.sync.isSessionInProgress = false; // closing the session
kony.sync.currentSyncReturnParams.upgradeRequired = false;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onPerformUpgradeSuccessKey], kony.sync.currentSyncReturnParams);
delete kony.sync.currentSyncReturnParams.upgradeRequired;
}
}
};
sync.isUpgradeRequired = function (config) {
sync.log.trace("Entering kony.sync.isUpgradeRequired");
if (kony.sync.validateSyncConfigParams("isUpgradeRequired", config) === false) {
return;
}
if (kony.sync.preProcessSyncConfig("isUpgradeRequired", config, config[kony.sync.onIsUpgradeRequiredErrorKey], false) === false) {
return;
}
kony.sync.areSyncConfigVersionDifferent(areSyncConfigVersionDifferentCallback);
function areSyncConfigVersionDifferentCallback(isError, errorObject, isDifferent) {
if (isError) {
kony.sync.verifyAndCallClosure(config[kony.sync.onIsUpgradeRequiredErrorKey], errorObject);
} else {
if (isDifferent) {
kony.sync.verifyAndCallClosure(config[kony.sync.onIsUpgradeRequiredSuccessKey], {
upgradeRequired : true
});
} else {
config[kony.sync.onUpgradeQueriesDownloadStartKey] = config[kony.sync.onIsUpgradeRequiredStartKey];
kony.sync.callSchemaUpgradeService(schemaUpgradeCallback, false);
}
}
}
function schemaUpgradeCallback(serverResponse) {
if (!kony.sync.isNullOrUndefined(serverResponse.opstatus) && serverResponse.opstatus !== 0) {
sync.log.error("Schema Upgrade Response : ", serverResponse);
if (!kony.sync.isNullOrUndefined(serverResponse.d)) {
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onIsUpgradeRequiredErrorKey], kony.sync.getServerError(
serverResponse.d));
} else {
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onIsUpgradeRequiredErrorKey], kony.sync.getServerError(serverResponse));
}
return;
}
else if(kony.sync.isNullOrUndefined(serverResponse.d)){
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onIsUpgradeRequiredErrorKey], kony.sync.getServerError(serverResponse));
return;
}
if (serverResponse.d.error === "true") {
sync.log.error("Schema Upgrade Response : ", serverResponse);
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onIsUpgradeRequiredErrorKey], kony.sync.getServerError(
serverResponse.d));
return;
}
var returnParams = {};
kony.sync.addServerDetails(returnParams, serverResponse);
returnParams.upgradeRequired = serverResponse.d.upgradeavailable === "true" ? true : false;
kony.sync.verifyAndCallClosure(config[kony.sync.onIsUpgradeRequiredSuccessKey], returnParams);
}
};
kony.sync.areSyncConfigVersionDifferent = function (callback) {
var dbname = kony.sync.scopes[0][kony.sync.scopeDataSource];
var connection = kony.sync.getConnectionOnly(dbname, dbname);
var isError = false;
var isDifferent = false;
if (connection !== null) {
kony.sync.startTransaction(connection, transactioncallback, transactionSuccessCallback, transactionErrorCallback);
}
function transactioncallback(tx) {
var sql = "select * from " + kony.sync.syncConfigurationTableName;
var resultset = kony.sync.executeSql(tx, sql, null);
if (resultset === false) {
isError = true;
return;
}
var dbSyncConfigVersion = kony.db.sqlResultsetRowItem(tx, resultset, 0)[kony.sync.syncConfigurationColumnVersion];
if (dbSyncConfigVersion !== konysyncClientSyncConfig.Version) {
isDifferent = true;
}
}
function transactionSuccessCallback() {
callback(false, null, isDifferent);
}
function transactionErrorCallback() {
callback(true, kony.sync.getTransactionError(isError));
}
};
kony.sync.isSchemaUpgradeTimeStampEmpty = function(val){
if(val==="" || val==="0,0" || kony.sync.isNullOrUndefined(val)){
return true;
}else{
return false;
}
};
// **************** End KonySyncSchemaUpgrade.js*******************
// **************** Start konySyncServiceProvider.js*******************
if (typeof(kony.sync) === "undefined") {
kony.sync = {};
}
if (typeof(sync) === "undefined") {
sync = {};
}
kony.sync.konyDownloadChanges = function(serverblob, scope, downloadNetworkCallback, isInitialized, schemaUpgradeServerblob) {
sync.log.trace("Entering kony.sync.konyDownloadChanges ");
if (kony.sync.isSyncStopped) {
kony.sync.stopSyncSession();
return;
}
var retries = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
function downloadNetworkCallbackStatus(status, result) {
if (status === 400) {
sync.log.trace("Entering kony.sync.konyDownloadChanges->downloadNetworkCallbackStatus");
//fallback when opstatus < 0
if(result.opstatus < 0){
sync.log.info("Got result.opstatus:" + result.opstatus + " and result.errcode:" + result.errcode + "setting errcode to opstatus");
result.opstatus = result.errcode;
}
if (kony.sync.eligibleForRetry(result.opstatus, retries)) {
retries--;
kony.sync.retryServiceCall(kony.sync.getDownloadURL(), result, null, retries, checkForChunking, params);
} else {
if (kony.sync.eligibleForChunking(result)) {
kony.sync.startChunking(kony.sync.getChunkDownloadURL(), params, result, downloadNetworkCallback);
} else {
kony.sync.setSessionID(result);
downloadNetworkCallback(result);
}
}
} else if (status === 300) {
downloadNetworkCallback(kony.sync.getNetworkCancelError());
}
}
function checkForChunking(result, info, retry) {
sync.log.trace("Entering kony.sync.konyDownloadChanges->checkForChunking");
retries = retry;
downloadNetworkCallbackStatus(400, result, info);
}
if (kony.sync.isNullOrUndefined(serverblob)) {
serverblob = "";
}
var params = {};
//check for pending chunks
kony.sync.checkForChunkingBeforeDownload(serverblob, normaldownloadCallback, downloadNetworkCallback, schemaUpgradeServerblob);
function normaldownloadCallback(payloadId) {
sync.log.trace("Entering kony.sync.konyDownloadChanges->normaldownloadCallback");
var jsonContext = null;
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncScopeFilter)) {
var scopejsonfilter = {
"d": {
Filters: kony.sync.currentSyncScopeFilter
}
};
jsonContext = JSON.stringify(scopejsonfilter);
}
if (isInitialized === false) {
kony.sync.downloadClientContext.InitialSync = "true";
} else {
delete kony.sync.downloadClientContext.InitialSync;
}
params.clientcontext = kony.sync.downloadClientContext;
kony.sync.commonServiceParams(params);
params.context = jsonContext;
params.enablebatching = "true";
params.batchsize = kony.sync.getBatchSize();
if (kony.sync.schemaUpgradeDownloadPending) {
params.tickcount = schemaUpgradeServerblob;
params.uppertickcount = serverblob;
if (!kony.sync.isNullOrUndefined(kony.sync.schemaUpgradeContext)) {
params.upgradecontext = kony.sync.schemaUpgradeContext;
}
} else {
params.tickcount = serverblob;
}
params.scopename = kony.sync.currentScope[kony.sync.scopeName];
params.strategy = kony.sync.currentScope[kony.sync.syncStrategy];
params.instanceid = kony.sync.getInstanceID();
params.clientid = kony.sync.getDeviceID();
params.appVersion = kony.sync.currentSyncConfigParams.appVersion;
params[kony.sync.chunkSizeKey] = kony.sync.getChunkSize();
//include payloadid if it is not null
if (!kony.sync.isNull(payloadId)) {
params.deletechunkpayloadid = payloadId;
}
if (!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey])) {
params.httpconfig = {
timeout: kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey]
};
}
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks]) &&
!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][kony.sync.currentScope[kony.sync.scopeName]])) {
params[kony.sync.sessionTaskUploadErrorPolicy] = kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][kony.sync.currentScope[kony.sync.scopeName]][kony.sync.sessionTaskUploadErrorPolicy];
}
var paramsToSend = null;
var currentSyncReturnParamsTemp = kony.sync.currentSyncReturnParams;
currentSyncReturnParamsTemp.downloadRequest = params;
kony.sync.deleteMapKey(currentSyncReturnParamsTemp, kony.sync.serverDetails);
if (kony.sync.globalIsDownloadStarted) {
paramsToSend = kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onDownloadStart], currentSyncReturnParamsTemp);
kony.sync.globalIsDownloadStarted = false;
if (!kony.sync.isNullOrUndefined(paramsToSend)) {
params = paramsToSend;
kony.sync.downloadClientContext = params.clientcontext;
}
}
currentSyncReturnParamsTemp.downloadRequest = params;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onBatchProcessingStart], kony.sync.currentSyncReturnParams);
if (paramsToSend != null) {
params = paramsToSend;
kony.sync.downloadClientContext = params.clientcontext;
}
currentSyncReturnParamsTemp = null;
paramsToSend = null;
params.clientcontext = JSON.stringify(kony.sync.downloadClientContext);
sync.log.info("Hitting the service with URL " + kony.sync.getDownloadURL(), params);
kony.sync.invokeServiceAsync(kony.sync.getDownloadURL(), params, downloadNetworkCallbackStatus, null);
}
};
kony.sync.konyUploadChanges = function(changes, uploadNetworkcallback, lastBatch, lastjson) {
sync.log.trace("Entering kony.sync.konyUploadChanges");
if (kony.sync.isSyncStopped) {
kony.sync.stopSyncSession();
return;
}
var results1 = [];
var retries = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
var jsonLua = null;
var json = null;
function uploadNetworkCallbackStatus(status, result, info) {
if (status === 400) {
sync.log.trace("Entering kony.sync.konyUploadChanges->uploadNetworkCallbackStatus");
//fallback when opstatus < 0
if(result.opstatus < 0){
sync.log.info("Got result.opstatus:" + result.opstatus + " and result.errcode:" + result.errcode + "setting errcode to opstatus");
result.opstatus = result.errcode;
}
if (kony.sync.eligibleForRetry(result.opstatus, retries)) {
retries--;
kony.sync.retryServiceCall(kony.sync.getUploadURL(), result, info, retries, retryCallback, params);
} else {
kony.sync.setSessionID(result);
uploadNetworkcallback(result, json);
results1 = null;
jsonLua = null;
}
} else if (status === 300) {
uploadNetworkcallback(kony.sync.getNetworkCancelError(), json);
}
}
function retryCallback(result, info, retry) {
sync.log.trace("Entering kony.sync.konyUploadChanges->retryCallback");
retries = retry;
uploadNetworkCallbackStatus(400, result);
}
if (lastjson === null) {
if (!kony.sync.isNullOrUndefined(changes.tables)) {
for (var i = 0; i < changes.tables.length; i++) {
var tableChange = changes.tables[i];
var tableName = tableChange.tableName;
if (!kony.sync.isNullOrUndefined(tableChange.changes)) {
for (var j = 0; j < tableChange.changes.length; j++) {
var rowChange = tableChange.changes[j];
if (kony.sync.isNullOrUndefined(rowChange.syncConflict)) {
rowChange.syncConflict = "";
}
var result = {
metadata: {
type: tableName,
uri: changes.uri,
changetype: rowChange.changeType,
syncConflict: rowChange.syncConflict
}
};
if (!kony.sync.isNullOrUndefined(rowChange.fields)) {
var fcount = kony.sync.getArrayCount(rowChange.fields);
for (var k = 0; k < fcount; k++) {
if (rowChange.fields[k] !== "ServerId" && rowChange.fields[k] !== "UpdateId") {
result[rowChange.fields[k]] = rowChange.values[k];
}
}
}
results1.push(result);
}
}
}
}
var moreChangesAvailable = null;
if (lastBatch === true) {
moreChangesAvailable = false;
} else {
moreChangesAvailable = true;
}
jsonLua = {
d: {
results: results1,
sync: "not implemented",
scopeName: changes.scopeName,
serverBlob: changes.serverblob,
clientid: changes.clientid,
SequenceNumber: changes.SequenceNumber,
moreChangesAvailable: moreChangesAvailable
}
};
json = JSON.stringify(jsonLua);
} else {
json = lastjson;
}
var params = {};
kony.sync.commonServiceParams(params);
params.UploadRequest = json;
params.scopename = kony.sync.currentScope[kony.sync.scopeName];
params.strategy = kony.sync.currentScope[kony.sync.syncStrategy];
params.instanceid = kony.sync.getInstanceID();
params.clientid = kony.sync.getDeviceID();
params.appVersion = kony.sync.currentSyncConfigParams.appVersion;
if (kony.sync.forceUpload || kony.sync.forceUploadUpgrade) {
params.usehistoryconfig = "true";
}
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks]) &&
!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][kony.sync.currentScope[kony.sync.scopeName]])) {
params[kony.sync.sessionTaskUploadErrorPolicy] = kony.sync.currentSyncConfigParams[kony.sync.sessionTasks][kony.sync.currentScope[kony.sync.scopeName]][kony.sync.sessionTaskUploadErrorPolicy];
}
if (!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey])) {
params.httpconfig = {
timeout: kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey]
};
}
params.clientcontext = kony.sync.uploadClientContext;
var paramsToSend = null;
var currentSyncReturnParamsTemp = kony.sync.currentSyncReturnParams;
currentSyncReturnParamsTemp.uploadRequest = params;
kony.sync.deleteMapKey(currentSyncReturnParamsTemp, kony.sync.serverDetails);
if (kony.sync.isUploadStarted) {
paramsToSend = kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUploadStart], currentSyncReturnParamsTemp);
if (paramsToSend != null) {
params = paramsToSend;
kony.sync.uploadClientContext = params.clientcontext;
}
kony.sync.isUploadStarted = false;
}
currentSyncReturnParamsTemp.uploadRequest = params;
paramsToSend = kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUploadBatchStart], currentSyncReturnParamsTemp);
if (!kony.sync.isNullOrUndefined(paramsToSend)) {
params = paramsToSend;
kony.sync.uploadClientContext = params.clientcontext;
}
params.clientcontext = JSON.stringify(kony.sync.uploadClientContext);
currentSyncReturnParamsTemp = null;
paramsToSend = null;
sync.log.info("Hitting the service with URL : " + kony.sync.getUploadURL(), params);
kony.sync.invokeServiceAsync(kony.sync.getUploadURL(), params, uploadNetworkCallbackStatus, null);
};
kony.sync.konyRegisterDevice = function(registerDeviceCallback) {
sync.log.trace("Entering kony.sync.konyRegisterDevice");
if (kony.sync.isSyncStopped) {
kony.sync.stopSyncSession();
return;
}
var retries = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
function registerDeviceCallbackStatus(status, result) {
if (status === 400) {
sync.log.trace("Entering kony.sync.konyRegisterDevice->registerDeviceCallbackStatus");
//fallback when opstatus < 0
if(result.opstatus < 0){
sync.log.info("Got result.opstatus:" + result.opstatus + " and result.errcode:" + result.errcode + "setting errcode to opstatus");
result.opstatus = result.errcode;
}
if (kony.sync.eligibleForRetry(result.opstatus, retries)) {
retries--;
kony.sync.retryServiceCall(kony.sync.getRegisterDeviceURL(), result, null, retries, retryCallback, params);
} else {
kony.sync.setSessionID(result);
registerDeviceCallback(result);
}
} else if (status === 300) {
registerDeviceCallback(kony.sync.getNetworkCancelError());
}
}
function retryCallback(result, info, retry) {
sync.log.trace("Entering kony.sync.konyRegisterDevice->retryCallback");
retries = retry;
registerDeviceCallbackStatus(400, result, info);
}
var params = {};
kony.sync.commonServiceParams(params);
params.os = kony.os.deviceInfo().name;
params.model = kony.os.deviceInfo().model;
params.version = kony.os.deviceInfo().version + "";
params.deviceID = kony.sync.getDeviceID();
params.userAgent = kony.os.userAgent();
params.channel = kony.sync.getChannelName();
params.platform = kony.sync.getPlatformName();
if (!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey])) {
params.httpconfig = {
timeout: kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey]
};
}
sync.log.info("Hitting the service with URL :" + kony.sync.getRegisterDeviceURL(), params);
kony.sync.invokeServiceAsync(kony.sync.getRegisterDeviceURL(), params, registerDeviceCallbackStatus, null);
};
kony.sync.callSchemaUpgradeService = function(schemaUpgradeCallback, scriptsRequired) {
sync.log.trace("Entering kony.sync.callSchemaUpgradeService");
if (kony.sync.isSyncStopped) {
kony.sync.stopSyncSession();
return;
}
var retries = kony.sync.currentSyncConfigParams[kony.sync.numberOfRetriesKey];
function schemaUpgradeServiceStatus(status, result) {
if (status === 400) {
sync.log.trace("Entering kony.sync.callSchemaUpgradeService->schemaUpgradeServiceStatus");
//fallback when opstatus < 0
if(result.opstatus < 0){
sync.log.info("Got result.opstatus:" + result.opstatus + " and result.errcode:" + result.errcode + "setting errcode to opstatus");
result.opstatus = result.errcode;
}
if (kony.sync.eligibleForRetry(result.opstatus, retries)) {
retries--;
kony.sync.retryServiceCall(kony.sync.getSchemaUpgradeURL(), result, null, retries, retryCallback, params);
} else {
kony.sync.setSessionID(result);
schemaUpgradeCallback(result);
}
}
}
function retryCallback(result, info, retry) {
sync.log.trace("Entering kony.sync.callSchemaUpgradeService->retryCallback");
retries = retry;
schemaUpgradeServiceStatus(400, result, info);
}
var params = {};
kony.sync.commonServiceParams(params);
params.clientid = kony.sync.getDeviceID();
params.appversion = konysyncClientSyncConfig.Version;
params.dbversion = kony.sync.configVersion;
params.scriptsrequired = (scriptsRequired === false) ? "false" : "true";
var paramsToSend = null;
paramsToSend = kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUpgradeQueriesDownloadStartKey], params);
if (!kony.sync.isNullOrUndefined(paramsToSend)) {
params = paramsToSend;
}
if (!kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey])) {
params.httpconfig = {
timeout: kony.sync.currentSyncConfigParams[kony.sync.networkTimeOutKey]
};
}
sync.log.info("Hitting the service with URL :" + kony.sync.getSchemaUpgradeURL(), params);
kony.sync.invokeServiceAsync(kony.sync.getSchemaUpgradeURL(), params, schemaUpgradeServiceStatus, null);
};
kony.sync.getServerURL = function() {
sync.log.trace("Entering kony.sync.getServerURL ");
if(!kony.sync.isNullOrUndefined(kony.sdk.getCurrentInstance()) &&
!kony.sync.isNullOrUndefined(kony.sdk.getCurrentInstance().sync) &&
!kony.sync.isNullOrUndefined(kony.sdk.getCurrentInstance().sync.url)) {
sync.log.trace("Fetching sync url from mbaas-sdk service docs instance");
return kony.sdk.getCurrentInstance().sync.url+"/";
}
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams.serverurl)) {
return kony.sync.currentSyncConfigParams.serverurl;
}
var server = "";
if (kony.sync.currentSyncConfigParams.issecure === true) {
server = "https://" + kony.sync.currentSyncConfigParams.serverhost;
} else {
server = "http://" + kony.sync.currentSyncConfigParams.serverhost;
}
if (kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams.serverport)) {
server = server + ":80";
} else if (kony.sync.currentSyncConfigParams.serverport !== "") {
server = server + ":" + kony.sync.currentSyncConfigParams.serverport;
}
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.authTokenKey])) {
return server + "/syncservice/api/v1/" + kony.sync.getAppId() + "/";
} else {
return server + "/syncservice/resources/";
}
};
kony.sync.getUploadURL = function() {
sync.log.trace("Entering kony.sync.getUploadURL ");
var server = kony.sync.getServerURL();
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams.uploadwebcontext)) {
return server + kony.sync.currentSyncConfigParams.uploadwebcontext;
}
return server + "upload";
};
kony.sync.getDownloadURL = function() {
sync.log.trace("Entering kony.sync.getDownloadURL ");
var server = kony.sync.getServerURL();
if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams.downloadwebcontext)) {
return server + kony.sync.currentSyncConfigParams.downloadwebcontext;
}
return server + "download";
};
kony.sync.getRegisterDeviceURL = function() {
sync.log.trace("Entering kony.sync.getRegisterDeviceURL ");
var server = kony.sync.getServerURL();
return server + "registerdevice";
};
kony.sync.getSchemaUpgradeURL = function() {
sync.log.trace("Entering kony.sync.getSchemaUpgradeURL ");
var server = kony.sync.getServerURL();
return server + "upgrade";
};
kony.sync.httprequest = null;
kony.sync.httprequestsinglesession = false;
//IF user passes his own function instead of using kony.net.invokeServiceAsync
//this is how it would be called.
kony.sync.invokeServiceAsync = function(url, params, callback, context) {
if (kony.sync.isMbaasEnabled) {
kony.sdk.claimsRefresh(claimsRefreshSuccessCallBack, claimsRefreshFailureCallBack);
function claimsRefreshSuccessCallBack() {
if (params && params.httpheaders) {
var currentClaimToken = kony.sdk.getCurrentInstance().currentClaimToken;
if (kony.sync.currentSyncConfigParams[kony.sync.authTokenKey] != currentClaimToken) {
kony.sync.currentSyncConfigParams[kony.sync.authTokenKey] = currentClaimToken;
}
params.httpheaders["X-Kony-Authorization"] = currentClaimToken;
invokeServiceAsyncHelper(url, params, callback, context);
}
}
function claimsRefreshFailureCallBack(res) {
callback(400, res, context);
}
} else {
invokeServiceAsyncHelper(url, params, callback, context);
}
function invokeServiceAsyncHelper(url, params, callback, context) {
if (kony.sync.isNull(kony.sync.currentSyncConfigParams[kony.sync.invokeServiceFunctionKey])) {
//#ifdef KONYSYNC_IOS
var deviceInfo = kony.os.deviceInfo();
var timeoutValue = 0;
var paramsHttpheaders = null;
if (kony.sync.isPhonegap || deviceInfo.osversion < 7) {
kony.net.invokeServiceAsync(url, params, callback, context);
} else {
var paramsTable = new kony.net.FormData();
for (var key in params) {
if (!kony.sync.isNull(params[key])) {
if (key === "httpheaders") {
paramsHttpheaders = params[key];
continue;
}
if (key === "httpconfig") {
timeoutValue = kony.sync.tonumber(params[key]["timeout"]);
continue;
}
paramsTable.append((key), (params[key]));
}
}
function createNewHttpRequest(sessionid, paramsHttpheaders, localRequestCallback, url, timeoutValue) {
var httprequest = null;
httprequest = (sessionid === null) ? new kony.net.HttpRequest() : new kony.net.HttpRequest(sessionid);
httprequest.backgroundTransfer = true;
httprequest.onReadyStateChange = localRequestCallback;
httprequest.open(constants.HTTP_METHOD_POST, url);
//
if (timeoutValue !== 0) {
httprequest.timeout = timeoutValue * 1000;
}
//
if (paramsHttpheaders !== null) {
for (var key in paramsHttpheaders) {
httprequest.setRequestHeader(key, paramsHttpheaders[key]);
}
}
if (paramsHttpheaders === null || typeof(paramsHttpheaders["Content-Type"]) === 'undefined') {
httprequest.setRequestHeader("Content-Type", "application/json");
}
return httprequest;
};
var httprequest = kony.sync.httprequest;
if (null === httprequest) {
httprequest = createNewHttpRequest(null, paramsHttpheaders, localRequestCallback, url, timeoutValue);
kony.sync.httprequest = httprequest;
kony.sync.httprequestsession = httprequest.getSession();
} else if (false === kony.sync.httprequestsinglesession) {
if (kony.sync.httprequestsession) {
httprequest = createNewHttpRequest(kony.sync.httprequestsession, paramsHttpheaders, localRequestCallback, url, timeoutValue);
kony.sync.httprequest = httprequest;
kony.sync.httprequestsinglesession = true;
}
} else {
httprequest.abort();
httprequest.onReadyStateChange = localRequestCallback;
httprequest.open(constants.HTTP_METHOD_POST, url);
}
httprequest.send(paramsTable);
}
//#else
kony.net.invokeServiceAsync(url, params, callback, context);
//#endif
} else {
kony.sync.currentSyncConfigParams[kony.sync.invokeServiceFunctionKey](url, params, callback, context);
}
function localRequestCallback(httprequest) {
if (httprequest.readyState === 4 && httprequest.status === 200) {
callback(400, httprequest.response, context);
} else if (httprequest.readyState === 4) {
httprequest.response = {
'opstatus': 1012
};
callback(400, httprequest.response, context);
}
}
} //end of invokeServiceAsyncHelper
};
kony.sync.commonServiceParams = function(params) {
sync.log.trace("Entering kony.sync.commonServiceParams ");
var httpheaders = {};
if(!kony.sync.isNullOrUndefined(kony.sdk.getCurrentInstance())
&& !kony.sync.isNullOrUndefined(kony.sdk.getCurrentInstance().currentClaimToken)) {
sync.log.trace("mbaas sdk instance is alive so adding current claims token");
if (!kony.sync.isMbaasEnabled) {
kony.sync.isMbaasEnabled = true;
}
httpheaders["X-Kony-Authorization"] = kony.sdk.getCurrentInstance().currentClaimToken;
}
else if (!kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams)) {
if(kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams[kony.sync.authTokenKey])) {
sync.log.trace("Neither Mbaas sdk instance and sync config auth token are not there, so adding userid, password and appid instead of token");
params.userid = kony.sync.currentSyncConfigParams.userid;
params.password = kony.sync.genHash(kony.sync.currentSyncConfigParams[kony.sync.passwordHashingAlgo], kony.sync.currentSyncConfigParams.password);
params.AppID = kony.sync.getAppId();
}
else {
if (!kony.sync.isMbaasEnabled) {
kony.sync.isMbaasEnabled = true;
}
if( !(kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams.userid)) &&
!(kony.sync.isNullOrUndefined(kony.sync.currentSyncConfigParams.password)) ) {
params.userid = kony.sync.currentSyncConfigParams.userid;
params.password = kony.sync.genHash(kony.sync.currentSyncConfigParams[kony.sync.passwordHashingAlgo], kony.sync.currentSyncConfigParams.password);
}
params.AppID = kony.sync.getAppId();
httpheaders["X-Kony-Authorization"] = kony.sync.currentSyncConfigParams[kony.sync.authTokenKey];
}
}
if (!kony.sync.isNullOrUndefined(kony.sync.sessionMap[kony.sync.konySyncSessionID]) &&
!kony.sync.isNullOrUndefined(kony.sync.sessionMap[kony.sync.konySyncRequestNumber])) {
params.konysyncsessionid = kony.sync.sessionMap[kony.sync.konySyncSessionID];
params.konysyncrequestnumber = kony.sync.sessionMap[kony.sync.konySyncRequestNumber];
}
httpheaders["Content-Type"] = "application/json";
params.httpheaders = httpheaders;
};
kony.sync.setSessionID = function(response) {
if (!kony.sync.isNullOrUndefined(response.d) && !kony.sync.isNullOrUndefined(response.d.__session)) {
kony.sync.sessionMap[kony.sync.konySyncSessionID] = response.d.__session.id;
kony.sync.sessionMap[kony.sync.konySyncRequestNumber] = response.d.__session.requestnumber;
}
};
kony.sync.resetSessionVars = function() {
kony.sync.sessionMap = {};
};
kony.sync.getDownloadBinaryURL = function() {
sync.log.trace("Entering kony.sync.getDownloadBinaryURL ");
var server = kony.sync.getServerURL();
sync.log.trace("server url created -> kony.sync.getDownloadBinaryURL "+server);
return server + "downloadBinary";
};
kony.sync.getUploadBinaryURL = function() {
sync.log.trace("Entering kony.sync.getUploadBinaryURL ");
var server = kony.sync.getServerURL();
sync.log.trace("server url created -> kony.sync.getUploadBinaryURL "+server);
return server + "uploadBinary";
}
// **************** End konySyncServiceProvider.js*******************
// **************** Start KonySyncSkyLib.js*******************
//#ifdef bb10
sky = null;
//#endif
kony.sky = {};
//Sky Constants
kony.sky.EventStart = "START";
kony.sky.EventFinish = "FINISH";
kony.sky.EventError = "ERROR";
kony.sky.ConfigParamServer = "SERVER";
kony.sky.ConfigParamPort = "PORT";
kony.sky.ConfigParamProfile = "PROFILE";
kony.sky.ConfigParamUsewifi = "USEWIFI";
kony.sky.ConfigParamUser = "USER";
kony.sky.ConfigParamPasswd = "PASSWORD";
kony.sky.BBPlatform = "blackberry";
kony.sky.TrueStr = "TRUE";
kony.sky.BBPlatformName = "blackberry";
kony.sky.ConfigParamConnMode = "CONNECTIONMODE";
kony.sky.startSkyCallback = "onSkyStart";
kony.sky.startIdentifyCallback = "onIndentifyStart";
kony.sky.successIdentifyCallback = "onIndentifySuccess";
kony.sky.errorIdentifyCallback = "onIndentifyError";
kony.sky.errorSkyCallback = "onSkyError";
kony.sky.startSessionCallback = "onSessionStart";
kony.sky.successSessionCallback = "onSessionSuccess";
kony.sky.errorSessionCallback = "onSessionError";
kony.sky.successSkyCallback = "onSkySuccess";
kony.sky.errorCode = "errorCode";
kony.sky.errorMessage = "errorMessage";
//provision callback methods
kony.sky.startProvisionCallback = "onProvisionStart";
kony.sky.successProvisionCallback = "onProvisionSuccess";
kony.sky.errorProvisionCallback = "onProvisionError";
//reset callback methods
kony.sky.startResetCallback = "onResetStart";
kony.sky.successResetCallback = "onResetSuccess";
kony.sky.errorResetCallback = "onResetError";
//stop callback methods
kony.sky.startStopCallback = "onStopStart";
kony.sky.successStopCallback = "onStopSuccess";
kony.sky.errorStopCallback = "onStopError";
//dataobject upload callback methods
kony.sky.startUploadCallback = "onUploadStart";
kony.sky.successUploadCallback = "onUploadSuccess";
kony.sky.errorUploadCallback = "onUploadError";
//transaction
kony.sky.startTransactionCallback = "onStartTransaction";
kony.sky.successTransactionCallback = "onSuccessTransaction";
kony.sky.parentTableInfo = "parentTable";
kony.sky.provisionSkySync = function(config){
sync.log.trace("Entering kony.sky.provisionSkySync ");
//#ifdef bb10
kony.sky.initializeSkyNamespace();
//#endif
var isProvisioned = sky.isProvisioned();
sync.log.info("SkySync engine provisioned status : ", isProvisioned);
if(config[kony.sky.ConfigParamServer] === null || config[kony.sky.ConfigParamServer] === "" || config[kony.sky.ConfigParamPort] === null || config[kony.sky.ConfigParamPort] === "" || config[kony.sky.ConfigParamProfile] === null || config[kony.sky.ConfigParamProfile] === "") {
var params = {};
params[kony.sky.errorCode] = "7101";
params[kony.sky.errorMessage] = kony.sky.errorMessageForCode(params[kony.sky.errorCode]);
kony.sync.verifyAndCallClosure(config[kony.sky.errorProvisionCallback],params);
return;
}
if(!isProvisioned){
var inputParam = {};
inputParam[kony.sky.ConfigParamServer] =config[kony.sky.ConfigParamServer];
inputParam[kony.sky.ConfigParamPort] = config[kony.sky.ConfigParamPort];
inputParam[kony.sky.ConfigParamProfile] = config[kony.sky.ConfigParamProfile];
if(!kony.sync.isNull(config[kony.sky.ConfigParamPasswd])){
inputParam[kony.sky.ConfigParamPasswd] = config[kony.sky.ConfigParamPasswd];
}
if(!kony.sync.isNull(config[kony.sky.ConfigParamUser])){
inputParam[kony.sky.ConfigParamUser] = config[kony.sky.ConfigParamUser];
}
if(!kony.sync.isNull(config[kony.sky.ConfigParamUsewifi])){
inputParam[kony.sky.ConfigParamUsewifi] = config[kony.sky.ConfigParamUsewifi];
}
if(!kony.sync.isNull(config[kony.sky.ConfigParamConnMode])){
inputParam[kony.sky.ConfigParamConnMode] = config[kony.sky.ConfigParamConnMode];
}
sky.provision(inputParam, provisionSkySyncCallback);
}else{
kony.sync.verifyAndCallClosure(config[kony.sky.successProvisionCallback],null);
}
function provisionSkySyncCallback( event, args ){
if((event !== kony.sky.EventStart)){
if((event === kony.sky.EventError)){
if((args !== null)){
var params = {};
params[kony.sky.errorCode] = args.ERRORCODE;
params[kony.sky.errorMessage] = args.ERRORDESC;
kony.sync.verifyAndCallClosure(config[kony.sky.errorProvisionCallback],params);
}
}
if((event === kony.sky.EventFinish)){
kony.sync.verifyAndCallClosure(config[kony.sky.successProvisionCallback],null);
}
}else{
kony.sync.verifyAndCallClosure(config[kony.sky.startProvisionCallback],null);
}
}
};
kony.sky.startSkySyncSession = function(config){
sync.log.trace("Entering kony.sky.startSkySyncSession ");
var isIdentified = sky.isIdentified();
if(config[kony.sky.ConfigParamUser] === null || config[kony.sky.ConfigParamPasswd] === null) {
var params = {};
params[kony.sky.errorCode] = "7101";
params[kony.sky.errorMessage] = kony.sky.errorMessageForCode(params[kony.sky.errorCode]);
kony.sync.verifyAndCallClosure(config[kony.sky.errorSkyCallback],params);
return;
}
kony.sync.verifyAndCallClosure(config[kony.sky.startSkyCallback ],null);
if(!isIdentified){
var identifyParams = {};
identifyParams[kony.sky.ConfigParamUser] = config[kony.sky.ConfigParamUser];
identifyParams[kony.sky.ConfigParamPasswd] = config[kony.sky.ConfigParamPasswd];
if(!kony.sync.isNull(config[kony.sky.ConfigParamUsewifi])){
identifyParams[kony.sky.ConfigParamUsewifi] = config[kony.sky.ConfigParamUsewifi];
}
if(!kony.sync.isNull(config[kony.sky.ConfigParamConnMode])){
identifyParams[kony.sky.ConfigParamConnMode] = config[kony.sky.ConfigParamConnMode];
}
sky.identify(identifyParams,false,identifySkySyncCallback);
}else{
identifySkySyncCallback(kony.sky.EventFinish, [ ]);
}
function identifySkySyncCallback( event, args ){
if(event !== kony.sky.EventStart){
if(event === kony.sky.EventError){
if((args !== null)){
var params = {};
params[kony.sky.errorCode] = args.ERRORCODE;
params[kony.sky.errorMessage] = args.ERRORDESC;
kony.sync.verifyAndCallClosure(config[kony.sky.errorIdentifyCallback],params);
}
}
if(event === kony.sky.EventFinish){
kony.sync.verifyAndCallClosure(config[kony.sky.successIdentifyCallback],null);
startSkySync();
}
}
else{
kony.sync.verifyAndCallClosure(config[kony.sky.startIdentifyCallback],null);
}
}
function startSkySync( ){
sync.log.trace("Entering startSkySync ");
var isStarted = sky.isStarted();
sync.log.info("SkySync server status : ", isStarted);
kony.sync.verifyAndCallClosure(config[kony.sky.startSessionCallback],null);
if((!isStarted)){
sky.start(startSkySyncCallback);
}else{
startSkySyncCallback(kony.sky.EventFinish, [ ]);
}
}
function startSkySyncCallback( event, args ){
if(event !== kony.sky.EventStart){
if(event === kony.sky.EventError){
if((args !== null)){
var params = {};
params[kony.sky.errorCode] = args.ERRORCODE;
params[kony.sky.errorMessage] = args.ERRORDESC;
kony.sync.verifyAndCallClosure(config[kony.sky.errorSessionCallback],params);
}
}
if(event === kony.sky.EventFinish){
sync.log.info("SkySync server started Successful");
kony.sync.verifyAndCallClosure(config[kony.sky.successSessionCallback],null);
kony.sync.verifyAndCallClosure(config[kony.sky.successSkyCallback],null);
}
}
}
};
kony.sky.skyEmptyFunction = function(){
sync.log.trace("Entering kony.sky.skyEmptyFunction ");
};
kony.sky.getSkyGuiID = function(){
sync.log.trace("Entering kony.sky.getSkyGuiID ");
var serviceId = sky.getParameter("SERVERID");
var currendate = kony.os.date("mm/dd/yyyy");
var currtime = kony.sky.replaceColon(kony.os.time());
var datevalue = currendate.split ("/");
var resultDate = datevalue[2] + datevalue[0] + datevalue[1] + currtime;
var GUID = serviceId + "-" + resultDate;
return GUID;
};
kony.sky.replaceColon = function(currtime){
sync.log.trace("Entering kony.sky.replaceColon ");
if(kony.string.containsChars(currtime,[":"])){
currtime = currtime.replace (":", "");
currtime = kony.sky.replaceColon(currtime);
}
return currtime;
};
kony.sky.generatePKTable = function(pk){
sync.log.trace("Entering kony.sky.generatePKTable ");
var i = 0;
var pks = [];
for (var j in pk){
var v = pk[j];
if(!kony.sync.isNull(v.key)){
pks[i] = v.key + " = " + v.value;
}
else{
pks[i] = j + " = " + v;
}
i = i + 1;
}
return pks;
};
kony.sky.buildConditionSet = function(srchByTargetAttribute, targetKey){
sync.log.trace("Entering kony.sky.buildConditionSet ");
var conditionSet = [];
conditionSet[ 0 ] = srchByTargetAttribute + " = " + targetKey;
return conditionSet;
};
kony.sky.beginTransaction = function(config){
sync.log.trace("Entering kony.sky.beginTransaction ");
sky.beginTransaction(config[kony.sky.successTransactionCallback]);
};
kony.sky.commitTransaction = function(config){
sync.log.trace("Entering kony.sky.commitTransaction ");
sky.commitTransaction(config[kony.sky.successTransactionCallback]);
};
kony.sky.rollbackTransaction = function(config){
sync.log.trace("Entering kony.sky.rollbackTransaction ");
sky.rollbackTransaction(config[kony.sky.successTransactionCallback]);
};
kony.sky.resetSkyEngine = function(config){
sync.log.trace("Entering kony.sky.resetSkyEngine ");
function resetCallback( event, args ){
if((event !== kony.sky.EventStart)){
if((event === kony.sky.EventError)){
if((args !== null)){
var params = {};
params[kony.sky.errorCode] = args.ERRORCODE;
params[kony.sky.errorMessage] = args.ERRORDESC;
kony.sync.verifyAndCallClosure(config[kony.sky.errorResetCallback],params);
}
}
if((event === kony.sky.EventFinish)){
kony.sync.verifyAndCallClosure(config[kony.sky.successResetCallback],null);
}
}else{
kony.sync.verifyAndCallClosure(config[kony.sky.startResetCallback],null);
}
}
sky.reset(resetCallback);
};
kony.sky.stopSkyEngine = function(config){
sync.log.trace("Entering kony.sky.stopSkyEngine ");
function stopCallback( event, args ){
if((event !== kony.sky.EventStart)){
if((event === kony.sky.EventError)){
if((args !== null)){
var params = {};
params[kony.sky.errorCode] = args.ERRORCODE;
params[kony.sky.errorMessage] = args.ERRORDESC;
kony.sync.verifyAndCallClosure(config[kony.sky.errorStopCallback],params);
}
}
if((event === kony.sky.EventFinish)){
if(sky.isStarted()){
sky.stop(stopCallback);
}else{
kony.sync.verifyAndCallClosure(config[kony.sky.successStopCallback],null);
}
}
}else{
kony.sync.verifyAndCallClosure(config[kony.sky.startStopCallback],null);
}
}
if(sky.isStarted()){
sky.stop(stopCallback);
}else{
kony.sync.verifyAndCallClosure(config[kony.sky.successStopCallback],null);
}
};
kony.sky.errorMessageForCode = function( errorCode ){
sync.log.trace("Entering kony.sky.errorMessageForCode ");
var statusMsgTable = {};
statusMsgTable["-1002"] = "ERROR_ALREADY_IDENTIFIED";
statusMsgTable["-1003"] = "ERROR_ALREADY_PROVISIONED";
statusMsgTable["-1004"] = "ERROR_BAD_CONDITION_SET";
statusMsgTable["-1005"] = "ERROR_BLACKLISTED";
statusMsgTable["-1006"] = "ERROR_CONFIGURATION";
statusMsgTable["-1007"] = "ERROR_DATA_OBJECT_NOT_FOUND";
statusMsgTable["-1008"] = "ERROR_DUPLICATE_ITEM";
statusMsgTable["-1009"] = "ERROR_ENCRYPTION_HANDSHAKE";
statusMsgTable["-1010"] = "ERROR_ENCRYPTION_MISMATCH";
statusMsgTable["-1001"] = "ERROR_GENERAL_FAILURE";
statusMsgTable["-1011"] = "ERROR_HOST_IF_SETUP_ERROR";
statusMsgTable["-1012"] = "ERROR_HOST_NOT_AVAILABLE";
statusMsgTable["-1013"] = "ERROR_IDENTITY_FAILURE";
statusMsgTable["-1014"] = "ERROR_INVALID_PARAMETER";
statusMsgTable["-1015"] = "ERROR_IS_STARTED";
statusMsgTable["-1016"] = "ERROR_MEAP_IS_DISABLED";
statusMsgTable["-1017"] = "ERROR_NO_CONFIGURATION";
statusMsgTable["-1018"] = "ERROR_NO_INSTANCES_SELECTED";
statusMsgTable["-1019"] = "ERROR_NOT_IDENTIFIED";
statusMsgTable["-1020"] = "ERROR_NOT_PROVISIONED";
statusMsgTable["-1021"] = "ERROR_NOT_RUNNING";
statusMsgTable["-1022"] = "ERROR_PROFILE_DEACTIVATED";
statusMsgTable["-1023"] = "ERROR_PROFILE_NOT_FOUND";
statusMsgTable["-1024"] = "ERROR_RETRY";
statusMsgTable["-1025"] = "ERROR_TABLE_NOT_FOUND";
statusMsgTable["-1026"] = "ERROR_UNCAUGHT_EXCEPTION";
statusMsgTable["-1027"] = "ERROR_USER_NOT_FOUND";
statusMsgTable["7101"] = "MISSING ATTRIBUTES FOR SKY";
var errMsg = "";
if(statusMsgTable[errorCode] === null) {
errMsg = "Some unknown error";
}else{
errMsg = statusMsgTable[errorCode];
}
return errMsg;
};
kony.sky.buildSkyOrderByMap = function(orderByMap){
sync.log.trace("Entering kony.sky.buildSkyOrderByMap ");
var i = 0;
var ordering = [];
for ( var j in orderByMap ){
var v = orderByMap[j];
var sortType = v.sortType;
var orderBy = (v.key).toString() ;
if(sortType === "desc"){
orderBy = orderBy +" D*";
}else{
orderBy = orderBy + " *";
}
ordering[ i ] = orderBy ;
i = i + 1;
}
return ordering;
};
//#ifdef bb10
kony.sky.initializeSkyNamespace = function(){
if (sky === null) {
sky = new SkySync.ffi();
}
};
//#endif
//#ifdef android
kony.sky.initializeSkySync = function(){
sky.initializeSkySync();
};
//#endif
//#ifdef tabrcandroid
kony.sky.initializeSkySync = function(){
sky.initializeSkySync();
};
//#endif
skySync = {
init : kony.sky.provisionSkySync,
startSession : kony.sky.startSkySyncSession,
reset : kony.sky.resetSkyEngine,
stop : kony.sky.stopSkyEngine,
beginTransaction : kony.sky.beginTransaction,
rollbackTransaction :kony.sky.rollbackTransaction,
commitTransaction : kony.sky.commitTransaction,
//#ifdef KONYSYNC_BB10
initializeSkyNamespace : kony.sky.initializeSkyNamespace
//#endif
//#ifdef KONYSYNC_ANDROID
initializeSkySync : kony.sky.initializeSkySync
//#endif
// quiesce : kony.sky.quiesce,
//unquiesce : kony.sky.unquiesce
};
// **************** End KonySyncSkyLib.js*******************
// **************** Start KonySyncUpload.js*******************
if(typeof(kony.sync)=== "undefined"){
kony.sync = {};
}
if(typeof(sync) === "undefined") {
sync = {};
}
if(typeof(kony.sync.blobManager) === "undefined") {
kony.sync.blobManager = {};
}
kony.sync.syncUploadChanges = function(sname, dsname, onCompletion) {
sync.log.trace("Entering kony.sync.syncUploadChanges ");
kony.sync.onUploadCompletion = onCompletion;
kony.sync.resetuploadsessioglobals();
kony.sync.objectLevelInfoMap = {};
kony.sync.OTAChangestobeDeleted = [];
kony.sync.uploadcontextMap = {};
kony.sync.getLastSyncUploadContext(sname, dsname, kony.sync.syncUploadChangesForBatch);
};
kony.sync.createClone = function(obj) {
var copy;
if (null == obj || "object" != typeof obj)
return obj;
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = kony.sync.createClone(obj[i]);
}
return copy;
}
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = kony.sync.createClone(obj[attr]);
}
return copy;
}
}
kony.sync.syncUploadChangesForBatch = function(rowItem, previousUpload, limit) {
sync.log.trace("Entering kony.sync.syncUploadChangesForBatch");
var batchSize = kony.sync.getUploadBatchSize();
var offset = 0;
var serverblob1 = rowItem[kony.sync.metaTableUploadSyncTimeColumn];
var lastSeqNo = rowItem[kony.sync.metaTableSyncOrderCloumn];
//previousUpload = "";//temporary -- to be removed while handling duplicate row issue
sync.log.info("Current Scope Server Time Stamp", serverblob1);
kony.sync.currentSyncReturnParams[kony.sync.lastSyncTimestamp] = serverblob1;
kony.sync.currentSyncReturnParams[kony.sync.uploadSequenceNumber] = kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName];
var firstBatch = false;
var lastBatch = false;
var isError = false;
var changeset = {
clientid: kony.sync.getDeviceID(),
SequenceNumber: kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName],
serverblob: serverblob1,
scopeName: kony.sync.currentScope[kony.sync.scopeName],
uri: kony.sync.currentScope[kony.sync.scopeDataSource],
totalChanges: 0,
tables: []
};
function updateSyncOrderForDeferredRows(tx, limit) {
sync.log.trace("Entering kony.sync.updateSyncOrderForDeferredRows");
if(kony.sync.isNullOrUndefined(kony.sync.currentScope.ScopeTables)){
return true;
}
for (var i = 0; i < kony.sync.currentScope.ScopeTables.length; i++) {
var syncTable = kony.sync.currentScope.ScopeTables[i];
if(kony.sync.isNullOrUndefined(syncTable)){
continue;
}
var tablename = syncTable.Name;
var settable = [];
settable[kony.sync.historyTableSyncVersionColumn] = kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName];
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tablename+kony.sync.historyTableName);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, [{key:kony.sync.historyTableReplaySequenceColumn,value:limit, optype: "LT"}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
}
return true;
}
function uploadAllTransaction(tx){
sync.log.trace("Entering kony.sync.syncUploadChangesForBatch->uploadAllTransaction");
//get offset for the 1st batch
if(kony.sync.isNull(limit) || previousUpload === "*"){
if( (previousUpload == "*") && !kony.sync.isNull(limit)) {
if(updateSyncOrderForDeferredRows(tx, limit) === false) {
isError = true;
}
}
offset = kony.sync.getSmallestSequenceNumber(tx);
if(offset===false){
isError = true;
return;
}
if(previousUpload !== "*"){
firstBatch = true; //If not resuming after sending duplicate row
}else{
previousUpload = "";
}
}
//otherwise increase it by limit + 1
else{
offset = limit + 1;
}
limit = offset + batchSize - 1;
var uploadCache = {};
if(offset !== -1){
kony.sync.syncTotalBatchInserts = 0;
kony.sync.syncTotalBatchUpdates = 0;
kony.sync.syncTotalBatchDeletes = 0;
var scopeName = kony.sync.currentScope[kony.sync.scopeName];
var changeSetCopy = kony.sync.createClone(changeset);
uploadCache[kony.sync.scope] = scopeName;
uploadCache[kony.sync.offset] = offset;
uploadCache[kony.sync.limit] = limit;
uploadCache[kony.sync.changeSet] = JSON.stringify(changeSetCopy);
uploadCache[kony.sync.lastSequenceNumber] = lastSeqNo;
uploadCache[kony.sync.batchSize] = batchSize;
//updating the offset in case of kony.sync.getBatchChanges is not able to get records in 1st attempt
limit = kony.sync.getBatchChanges(tx, kony.sync.currentScope, offset, limit, changeset, lastSeqNo, batchSize);
if(limit===false){
isError = true;
return;
}
kony.sync.syncTotalInserts += kony.sync.syncTotalBatchInserts;
kony.sync.syncTotalUpdates += kony.sync.syncTotalBatchUpdates;
kony.sync.syncTotalDeletes += kony.sync.syncTotalBatchDeletes;
}
if(limit >= lastSeqNo){
lastBatch = true;
}
if(offset !== -1){
uploadCache[kony.sync.lastBatch] = lastBatch;
uploadCache[kony.sync.uploadChangesLimit] = kony.sync.uploadLimit;
cacheLastUploadRequest(tx, uploadCache);
}
}
function cacheLastUploadRequest(tx, uploadCache) {
if(changeset.totalChanges > 0) {
var scopeName = kony.sync.currentScope[kony.sync.scopeName]
var lastRequest = kony.sync.checkForPendingUpload(tx, scopeName);
if(lastRequest != "") {
return;
}
var contextInfo = {};
contextInfo[kony.sync.metaTableScopeColumn] = scopeName;
contextInfo[kony.sync.pendingUploadTableInsertCount] = kony.sync.syncTotalInserts;
contextInfo[kony.sync.pendingUploadTableUpdateCount] = kony.sync.syncTotalUpdates;
contextInfo[kony.sync.pendingUploadTableDeleteCount] = kony.sync.syncTotalDeletes;
contextInfo[kony.sync.pendingUploadTableBatchInsertCount] = kony.sync.syncTotalBatchInserts;
contextInfo[kony.sync.pendingUploadTableBatchUpdateCount] = kony.sync.syncTotalBatchUpdates;
contextInfo[kony.sync.pendingUploadTableBatchDeleteCount] = kony.sync.syncTotalBatchDeletes;
contextInfo[kony.sync.pendingUploadTableObjectLevelInfo] = JSON.stringify(kony.sync.objectLevelInfoMap);
contextInfo[kony.sync.pendingUploadTableUploadRequest] = JSON.stringify(uploadCache);
contextInfo[kony.sync.pendingUploadTableUploadLimit] = kony.sync.uploadLimit;
var query = kony.sync.qb_createQuery();
kony.sync.qb_insert(query, kony.sync.pendingUploadTableName);
kony.sync.qb_set(query, contextInfo);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if (resultSet === false) {
isError = true;
}
}
}
function uploadTransactionSuccess(){
sync.log.trace("Entering kony.sync.syncUploadChangesForBatch->uploadTransactionSuccess");
if(changeset.totalChanges > 0 || previousUpload !== ""){
if(firstBatch){
//kony.sync.deleteMapKey(kony.sync.currentSyncReturnParams, kony.sync.serverDetails);
//kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUploadStart], kony.sync.currentSyncReturnParams);
kony.sync.isUploadStarted = true;
}
//kony.sync.konyUploadChanges(changeset, uploadAllTransactionSuccess, lastBatch);
if(previousUpload===""){
kony.sync.konyUploadChanges(changeset, uploadAllTransactionSuccess, lastBatch, null);
}
else{
kony.sync.konyUploadChanges(null, uploadAllTransactionSuccess, null, changeset);
}
}
else{
if(firstBatch){ //nothing to upload, hence skip it
kony.sync.uploadCompleted();
}
else{ //upload batch processing finished
kony.sync.currentSyncReturnParams[kony.sync.uploadContext] = kony.sync.uploadcontextMap;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUploadSuccess], kony.sync.currentSyncReturnParams);
kony.sync.currentSyncReturnParams[kony.sync.uploadContext] = {};
kony.sync.uploadcontextMap = {};
kony.sync.onUploadCompletion(false, null);
}
}
}
function transactionErrorCallback(){
sync.log.trace("Entering kony.sync.syncUploadChangesForBatch->transactionErrorCallback");
if (!isError){
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
}
else{
kony.sync.syncUploadFailed(kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
function uploadAllTransactionSuccess(otaServerChanges, oldJson) {
sync.log.trace("Entering kony.sync.syncUploadChangesForBatch->uploadAllTransactionSuccess");
sync.log.info("Upload response:", otaServerChanges);
if (!kony.sync.isNullOrUndefined(otaServerChanges.opstatus) && otaServerChanges.opstatus !== 0){
if (!kony.sync.isNullOrUndefined(otaServerChanges.d)) {
kony.sync.deleteLastUploadRequestWithNewTransaction(deleteLastUploadRequestCallback);
} else {
addLastUploadRequestCallback();
}
return;
}
else if(kony.sync.isNullOrUndefined(otaServerChanges.d)){
if(kony.sync.isSyncStopped){
sync.log.debug("sync stopped in kony.sync.syncUploadChangesForBatch->uploadAllTransactionSuccess");
kony.sync.stopSyncSession();
return;
}
kony.sync.onUploadCompletion(true, kony.sync.getServerError(otaServerChanges.d));
return;
}
function addLastUploadRequestCallback(){
if(kony.sync.isSyncStopped){
sync.log.debug("sync stopped in kony.sync.syncUploadChangesForBatch->addLastUploadRequestCallback");
kony.sync.stopSyncSession();
return;
}
sync.log.trace("Entering kony.sync.syncUploadChangesForBatch->addLastUploadRequestCallback");
kony.sync.onUploadCompletion(true, kony.sync.getServerError(otaServerChanges.d));
}
if (otaServerChanges.d.error === "false"){
if(!kony.sync.isNullOrUndefined(otaServerChanges.d.__sync) && !kony.sync.isNullOrUndefined(otaServerChanges.d.__sync.serverblob)) {
rowItem[kony.sync.metaTableUploadSyncTimeColumn] = otaServerChanges.d.__sync.serverblob;
kony.sync.currentSyncReturnParams[kony.sync.serverDetails] = {};
kony.sync.currentSyncReturnParams[kony.sync.serverDetails][kony.sync.hostName] = kony.sync.getServerDetailsHostName(otaServerChanges);
kony.sync.currentSyncReturnParams[kony.sync.serverDetails][kony.sync.ipAddress] = kony.sync.getServerDetailsIpAddress(otaServerChanges);
kony.sync.clearSyncOrder(kony.sync.currentScope[kony.sync.scopeDataSource], limit, rowItem[kony.sync.metaTableUploadSyncTimeColumn], true, clearSyncOrderCallback);
} else {
addLastUploadRequestCallback();
}
}else {
kony.sync.deleteLastUploadRequestWithNewTransaction(deleteLastUploadRequestCallback);
return;
}
function deleteLastUploadRequestCallback(){
if(kony.sync.isSyncStopped){
sync.log.debug("sync stopped in kony.sync.syncUploadChangesForBatch->deleteLastUploadRequestCallback");
kony.sync.stopSyncSession();
return;
}
kony.sync.onUploadCompletion(true,kony.sync.getServerError(otaServerChanges.d));
}
function clearSyncOrderCallback(){
sync.log.trace("Entering kony.sync.syncUploadChangesForBatch->clearSyncOrderCallback");
if (kony.sync.currentScope[kony.sync.syncStrategy] !== kony.sync.syncStrategy_OTA) {
setSeqNoWrapper();
} else {
kony.sync.setOTAUploadResponse(otaServerChanges, setSeqNoWrapper);
}
}
function setSeqNoWrapper(){
sync.log.trace("Entering kony.sync.syncUploadChangesForBatch->setSeqNoWrapper");
kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName] = kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName] + 1;
kony.sync.setSeqnumber(kony.sync.currentScope.ScopeName, kony.sync.currentScope[kony.sync.scopeDataSource], kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName], setSeqNoCallback);
}
function setSeqNoCallback(){
if(kony.sync.isSyncStopped){
sync.log.debug("sync stopped in uploadAllTransactionSuccess -> setSeqNoCallback");
kony.sync.stopSyncSession();
return;
}
sync.log.trace("Entering kony.sync.syncUploadChangesForBatch->setSeqNoCallback");
kony.sync.uploadcontextMap[kony.sync.numberOfRowsUploaded] = kony.sync.syncTotalInserts + kony.sync.syncTotalUpdates + kony.sync.syncTotalDeletes;
kony.sync.uploadcontextMap[kony.sync.numberOfRowsInserted] = kony.sync.syncTotalInserts;
kony.sync.uploadcontextMap[kony.sync.numberOfRowsUpdated] = kony.sync.syncTotalUpdates;
kony.sync.uploadcontextMap[kony.sync.numberOfRowsDeleted] = kony.sync.syncTotalDeletes;
var uploadBatchContextMap = {};
uploadBatchContextMap[kony.sync.numberOfRowsUploaded] = kony.sync.syncTotalBatchInserts + kony.sync.syncTotalBatchUpdates + kony.sync.syncTotalBatchDeletes;
uploadBatchContextMap[kony.sync.numberOfRowsInserted] = kony.sync.syncTotalBatchInserts;
uploadBatchContextMap[kony.sync.numberOfRowsUpdated] = kony.sync.syncTotalBatchUpdates;
uploadBatchContextMap[kony.sync.numberOfRowsDeleted] = kony.sync.syncTotalBatchDeletes;
uploadBatchContextMap[kony.sync.serverDetails] = {};
uploadBatchContextMap[kony.sync.serverDetails][kony.sync.hostName] = kony.sync.getServerDetailsHostName(otaServerChanges);
uploadBatchContextMap[kony.sync.serverDetails][kony.sync.ipAddress] = kony.sync.getServerDetailsIpAddress(otaServerChanges);
if (kony.sync.currentScope[kony.sync.syncStrategy] === kony.sync.syncStrategy_OTA) {
kony.sync.uploadcontextMap[kony.sync.objectLevelInfo] = kony.sync.objectLevelInfoMap;
kony.sync.uploadcontextMap[kony.sync.numberOfRowsAcknowledged] = kony.sync.serverInsertAckCount + kony.sync.serverUpdateAckCount + kony.sync.serverDeleteAckCount;
kony.sync.uploadcontextMap[kony.sync.numberOfRowsInsertedAck] = kony.sync.serverInsertAckCount;
kony.sync.uploadcontextMap[kony.sync.numberOfRowsUpdatedAck] = kony.sync.serverUpdateAckCount;
kony.sync.uploadcontextMap[kony.sync.numberOfRowsDeletedAck] = kony.sync.serverDeleteAckCount;
kony.sync.uploadcontextMap[kony.sync.failedRowInfo] = kony.sync.uploadSummary;
kony.sync.uploadcontextMap[kony.sync.numberOfRowsFailedtoUpload] = kony.sync.serverFailedCount;
}
var uploadBatchParams = {};
uploadBatchParams[kony.sync.uploadContext] = kony.sync.uploadcontextMap;
uploadBatchParams[kony.sync.uploadBatchContext] = uploadBatchContextMap;
kony.sync.verifyAndCallClosure(kony.sync.currentSyncConfigParams[kony.sync.onUploadBatchSuccess], uploadBatchParams);
//clearing variables before calling 2nd batch
otaServerChanges = null;
uploadBatchParams = null;
uploadBatchContextMap = null;
changeset = null;
firstBatch = null;
lastBatch = null;
batchSize = null;
offset = null;
serverblob1 = null;
//call upload batching recursively
kony.sync.syncUploadChangesForBatch(rowItem, previousUpload!==""?"*":"", limit);
}
}
if(previousUpload === "" || previousUpload === "*"){
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var connection = kony.sync.getConnectionOnly(dbname, dbname, kony.sync.syncUploadFailed);
if(connection!==null){
kony.db.transaction(connection, uploadAllTransaction, transactionErrorCallback, uploadTransactionSuccess);
}
}
else{
changeset = previousUpload[kony.sync.pendingUploadTableUploadRequest];
try{
kony.sync.objectLevelInfoMap = JSON.parse(previousUpload[kony.sync.pendingUploadTableObjectLevelInfo]);
}
catch(e){
sync.log.error("Error occurred while re-framing last persisted upload request:" + e);
kony.sync.onUploadCompletion(true, kony.sync.getErrorTable(kony.sync.errorCodeParseError, kony.sync.getErrorMessage(kony.sync.errorCodeParseError,previousUpload[kony.sync.pendingUploadTableObjectLevelInfo], e)));
return;
}
changeset = previousUpload[kony.sync.pendingUploadTableUploadRequest];
kony.sync.syncTotalInserts = previousUpload[kony.sync.pendingUploadTableInsertCount];
kony.sync.syncTotalUpdates = previousUpload[kony.sync.pendingUploadTableUpdateCount];
kony.sync.syncTotalDeletes = previousUpload[kony.sync.pendingUploadTableDeleteCount];
kony.sync.syncTotalBatchInserts = previousUpload[kony.sync.pendingUploadTableBatchInsertCount];
kony.sync.syncTotalBatchUpdates = previousUpload[kony.sync.pendingUploadTableBatchUpdateCount];
kony.sync.syncTotalBatchDeletes = previousUpload[kony.sync.pendingUploadTableBatchDeleteCount];
limit = previousUpload[kony.sync.pendingUploadTableUploadLimit];
firstBatch = true;
uploadTransactionSuccess();
}
};
kony.sync.setOTAUploadResponse = function (serverChanges, callback) {
sync.log.trace("Entering kony.sync.setOTAUploadResponse");
var isError = false;
if(!kony.sync.isNullOrUndefined(serverChanges.d) && !kony.sync.isNullOrUndefined(serverChanges.d.results)){
for(var i in serverChanges.d.results){
kony.sync.OTAChangestobeDeleted.push(serverChanges.d.results[i]);
}
}
function setOTAUploadResponseTransaction(tx) {
sync.log.trace("Entering kony.sync.setOTAUploadResponse->setOTAUploadResponseTransaction");
isError = kony.sync.applyChanges(tx, kony.sync.currentScope, serverChanges, kony.sync.gPolicy);
}
function setOTAUploadResponseTransactionSuccess() {
sync.log.trace("Entering kony.sync.setOTAUploadResponse->setOTAUploadResponseTransactionSuccess");
callback();
}
function setOTAUploadResponseTransactionFailure() {
sync.log.trace("Entering kony.sync.setOTAUploadResponse->setOTAUploadResponseTransactionFailure");
if (!isError) {
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
} else {
kony.sync.syncUploadFailed(kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var connection = kony.sync.getConnectionOnly(dbname, dbname, kony.sync.syncUploadFailed);
if(connection!==null){
kony.db.transaction(connection, setOTAUploadResponseTransaction, setOTAUploadResponseTransactionFailure, setOTAUploadResponseTransactionSuccess);
}
};
kony.sync.syncUploadFailed = function(connection) {
sync.log.trace("Entering kony.sync.syncUploadFailed");
kony.sync.onUploadCompletion(true,JSON.stringify(connection));
sync.log.error("Upload Failed",connection);
};
//To get smallest sequence number from all history tables of a scope
kony.sync.getSmallestSequenceNumber = function(tx){
sync.log.trace("Entering kony.sync.getSmallestSequenceNumber");
if(kony.sync.isNullOrUndefined(kony.sync.currentScope.ScopeTables)){
return -1;
}
var seqNo = -1; //initialize sequence number
for (var i = 0; i < kony.sync.currentScope.ScopeTables.length; i++){
var syncTable = kony.sync.currentScope.ScopeTables[i];
//not using query builder to speedup sync time
var sql = "select min(" + kony.sync.historyTableReplaySequenceColumn + ") from " +
syncTable.Name + kony.sync.historyTableName + " where " +
kony.sync.historyTableChangeTypeColumn + " NOT LIKE '9%' AND " +
kony.sync.historyTableSyncVersionColumn + " = " + kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName];
var resultset = kony.sync.executeSql(tx, sql, null);
if(resultset === false){
return false; //error occurred while executing query
}
var rowItem = kony.db.sqlResultsetRowItem(tx, resultset, 0);
var seqNoFromTable = kony.sync.tonumber(rowItem["min(" + kony.sync.historyTableReplaySequenceColumn + ")"]);
seqNo = (seqNo === -1 || seqNoFromTable < seqNo) && seqNoFromTable !== null ? seqNoFromTable : seqNo;
}
return seqNo;
};
kony.sync.getBatchChanges = function(tx, scope, offset, limit, changeset, lastSeqNo, batchSize) {
sync.log.trace("Entering kony.sync.getBatchChanges");
var tc = null;
var continueGettingChanges = true;
kony.sync.uploadLimit = 0;
var tempUploadLimit;
var tableDictionary = {};//dictionary to get index of a table in changeset
var tableDictionarySize = 0;
var replaySequenceDictionary = [];
var dummyReplaySequenceNumber = -1 * batchSize;
do{
for(var i = 0; !kony.sync.isNull(kony.sync.currentScope.ScopeTables) && i < kony.sync.currentScope.ScopeTables.length; i++){
var syncTable = kony.sync.currentScope.ScopeTables[i];
if(kony.sync.isNullOrUndefined(kony.sync.objectLevelInfoMap[syncTable.Name])){
kony.sync.objectLevelInfoMap[syncTable.Name] = {};
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsUploaded] = 0;
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsInserted] = 0;
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsUpdated] = 0;
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsDeleted] = 0;
if ((kony.sync.currentScope[kony.sync.syncStrategy] === kony.sync.syncStrategy_OTA)) {
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsInsertedAck] = 0;
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsUpdatedAck]= 0;
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsDeletedAck] = 0;
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsAcknowledged] = 0;
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsFailedtoUpload] = 0;
}
}
if(kony.sync.currentScope.isHierarchical === true){
tableDictionary[syncTable.Name] = i;
tableDictionarySize++;
}
tc = null;
if(kony.sync.isNullOrUndefined(changeset.tables[i])) {
tc = {
tableName: syncTable.Name,
changes: []
};
changeset.tables[i] = tc;
} else {
tc = changeset.tables[i];
}
var fields = [];
if(!kony.sync.isNullOrUndefined(kony.sync.currentScope.ScopeTables[i].Columns)){
for (var j = 0; j < kony.sync.currentScope.ScopeTables[i].Columns.length; j++) {
var col = kony.sync.currentScope.ScopeTables[i].Columns[j];
kony.table.insert(fields, col.Name);
}
}
kony.table.insert(fields, kony.sync.historyTableChangeTypeColumn);
kony.table.insert(fields, kony.sync.historyTableReplaySequenceColumn);
kony.table.insert(fields, kony.sync.historyTableSyncVersionColumn);
kony.table.insert(fields, kony.sync.historyTableHashSumColumn);
//not using query builder to speedup sync time
var sql = "select * from " + syncTable.Name + kony.sync.historyTableName + " where " +
kony.sync.historyTableChangeTypeColumn + " NOT LIKE '9%' AND " +
kony.sync.historyTableSyncVersionColumn + " = " + kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName] +
" AND " + kony.sync.historyTableReplaySequenceColumn + " between " + offset + " AND " + limit;
var resultset = kony.sync.executeSql(tx, sql, null);
if(resultset===false){
return false;
}
prepareChangeSet(tx, resultset);
sync.log.info("changes for " + syncTable.Name + ":", changeset.tables[i].changes);
sql = "select max(" + kony.sync.historyTableReplaySequenceColumn + ") from " + syncTable.Name + kony.sync.historyTableName + " where " +
kony.sync.historyTableChangeTypeColumn + " NOT LIKE '9%' AND " +
kony.sync.historyTableSyncVersionColumn + " = " + kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName] +
" AND " + kony.sync.historyTableReplaySequenceColumn + " between " + offset + " AND " + limit;
resultset = kony.sync.executeSql(tx, sql, null);
if(resultset===false){
return false;
}
tempUploadLimit = kony.db.sqlResultsetRowItem(tx, resultset, 0)["max(" + kony.sync.historyTableReplaySequenceColumn + ")"];
if(tempUploadLimit !== null && tempUploadLimit > kony.sync.uploadLimit){
kony.sync.uploadLimit = tempUploadLimit;
}
if(changeset.totalChanges === batchSize){
break; //got all changes
}
}
if(changeset.totalChanges < batchSize && limit < lastSeqNo){
offset = limit + 1;
limit += batchSize - changeset.totalChanges;
}
else{
if(kony.sync.currentScope.isHierarchical === true){
function createDummyChangeSet(parentTableName,row) {
sync.log.trace("Creating Dummy ChangeSet Record");
var changesetIndex = tableDictionary[parentTableName];
tc = null;
//getting the actual table
if(kony.sync.isNullOrUndefined(changeset.tables[changesetIndex])) {
tc = {
tableName: parentTableName,
changes: []
};
changeset.tables[changesetIndex] = tc;
} else {
tc = changeset.tables[changesetIndex];
}
var changeType = row[kony.sync.historyTableChangeTypeColumn] + "";
var rc = {
fields: [],
values: []
};
syncTable = kony.sync.currentScope.syncTableDic[parentTableName];
if(!kony.sync.isNullOrUndefined(syncTable.Columns)){
for (var x = 0; x < syncTable.Columns.length; x++) {
var column = syncTable.Columns[x];
if(kony.sync.isNullOrUndefined(row[column.Name])){
kony.table.insert(rc.fields, column.Name);
kony.table.insert(rc.values, "null");
}
}
}
row[kony.sync.mainTableChangeTypeColumn] = 1;
row[kony.sync.historyTableChangeTimeColumn] = null;
row[kony.sync.mainTableHashSumColumn] = null;
for(var key in row){
if (key !== kony.sync.syncStatusColumn){
kony.table.insert(rc.fields, key);
kony.table.insert(rc.values, row[key]);
}
}
rc.changeType = "update";
//creating metainfo if it doesnot exist
if(kony.sync.isNullOrUndefined(kony.sync.objectLevelInfoMap[parentTableName])){
kony.sync.objectLevelInfoMap[parentTableName] = {};
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsUploaded] = 0;
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsInserted] = 0;
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsUpdated] = 0;
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsDeleted] = 0;
if ((kony.sync.currentScope[kony.sync.syncStrategy] === kony.sync.syncStrategy_OTA)) {
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsInsertedAck] = 0;
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsUpdatedAck]= 0;
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsDeletedAck] = 0;
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsAcknowledged] = 0;
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsFailedtoUpload] = 0;
}
}
kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsUpdated]=kony.sync.objectLevelInfoMap[parentTableName][kony.sync.numberOfRowsUpdated]+1;
kony.sync.syncTotalBatchUpdates += 1;
sync.log.info("adding the dummy record metadata to batchchangeset metadata");
kony.table.insert(rc.fields, kony.sync.historyTableReplaySequenceColumn);
kony.table.insert(rc.values, dummyReplaySequenceNumber);
//giving dummy replay sequence number for the record and sending it as update
dummyReplaySequenceNumber++;
sync.log.info("updated dummy replay sequence number "+dummyReplaySequenceNumber);
//finally adding the record to the changeset
sync.log.info("inserted the record into the change set "+JSON.stringify(rc));
kony.table.insert(tc.changes, rc);
sync.log.info("changeset of table "+parentTableName + " "+JSON.stringify(tc.changes));
//return the index of newly inserted record
return (tc.changes.length - 1);
}
function isEmptyObject(object){
for(var key in object){
return false;
}
return true;
}
function fetchParentFromMainTable(parentTableName,childRecord,childTableName){
sync.log.trace("entering into fetch parent from main table");
wherecondition = [];
//getting the parents of the child table
parentRelationshipMap = kony.sync.currentScope.syncTableDic[childTableName+kony.sync.parentRelationshipMap];
childTable = kony.sync.currentScope.syncTableDic[childTableName];
var childValues = childRecord.values;
if(parentRelationshipMap[parentTableName]) {//checking whether child is a part of any onetomany relationship of parent
var relationshipAttributes = parentRelationshipMap[parentTableName];
for(var k = 0;k<relationshipAttributes.length;k++){
relationshipAttribute =relationshipAttributes[k];
var columnName = relationshipAttribute["ParentObject_Attribute"];
var childColumnName = relationshipAttribute["ChildObject_Attribute"];
childFieldIndex = getFieldsIndex(childRecord.fields,childColumnName);
kony.table.insert(wherecondition, {
key : columnName,
value : childValues[childFieldIndex]
});
}
}
else {
ManyToOne = childTable.Relationships.ManyToOne;
if(!kony.sync.isNullOrUndefined(ManyToOne)){
for(var k = 0;k<ManyToOne.length;k++){
var currentRelation = ManyToOne[k];
if(currentRelation.TargetObject == parentTableName){
var relationshipAttributes = currentRelation.RelationshipAttributes;
for (var j = 0; j < relationshipAttributes.length; j++) {
var columnName = relationshipAttributes[j].TargetObject_Attribute;
var childColumnName = relationshipAttributes[j].SourceObject_Attribute;
childFieldIndex = getFieldsIndex(childRecord.fields,childColumnName);
kony.table.insert(wherecondition, {
key : columnName,
value : childValues[childFieldIndex]
});
};
}
}
}
}
if(wherecondition.length != 0){
//fetchParentFromMainTable
query = kony.sync.qb_createQuery();
kony.sync.qb_select(query,null);
kony.sync.qb_from(query,parentTableName);
kony.sync.qb_where(query,wherecondition);
query_compile =kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
resultset = kony.sync.executeSql(tx, sql,params);
if(resultset.rows.length >= 1 ){
var rowItem =kony.db.sqlResultsetRowItem(tx,resultset,0);
parentRecordIndex = createDummyChangeSet(parentTableName,rowItem);
sync.log.info("index of the dummy record in the changeset corrrespoding to the "+parentTableName+" is "+parentRecordIndex );
return parentRecordIndex;//actual index according to zero based indexing
}
else{
sync.log.error("no records in :"+parentTableName+ " with a child in "+childTableName);
return -1;
}
}
else {
sync.log.error("Invalid Operation is defined for table :"+childTable+ " with operations to"+parentTable);
return -1;
}
}
function checkInChangeSet(parentTableName,childRecord,childTableName){
sync.log.trace("entering into checkInChangeSet function ");
var parentColumns = [];
var childColumns = [];
sync.log.info("check in changeset for parent "+parentTableName + " with child "+childTableName);
parentRelationshipMap = kony.sync.currentScope.syncTableDic[childTableName+kony.sync.parentRelationshipMap];
if(parentRelationshipMap[parentTableName]) {//checking whether child is a part of any onetomany relationship of parent
var relationshipAttributes = parentRelationshipMap[parentTableName];
var relationshipAttributes_length = relationshipAttributes.length;
for(var k = 0;k<relationshipAttributes_length;k++){
relationshipAttribute = relationshipAttributes[k];
var columnName = relationshipAttribute["ParentObject_Attribute"];
var childColumnName = relationshipAttribute["ChildObject_Attribute"];
parentColumns.push(columnName);
childColumns.push(childColumnName);
}
}
else {
ManyToOne = childTable.Relationships.ManyToOne;
if(!kony.sync.isNullOrUndefined(ManyToOne)){
for(var k = 0;k<ManyToOne.length;k++){
currentRelation = ManyToOne[k];
if(currentRelation.TargetObject == parentTableName){
var relationshipAttributes = currentRelation.RelationshipAttributes;
for (var j = 0; j < relationshipAttributes.length; j++) {
var columnName = relationshipAttributes[j].TargetObject_Attribute;
var childColumnName = relationshipAttributes[j].SourceObject_Attribute;
parentColumns.push(columnName);
childColumns.push(childColumnName);
}
}
}
}
}
if(kony.sync.isNullOrUndefined(tableDictionary[parentTableName]))
return false;
var changeSetIndex = tableDictionary[parentTableName];//index in changeset
var records = changeset.tables[changeSetIndex].changes;//child object changeset
for(var j =0; j < records.length;j++){
parentRecord = records[j];//parent records
var matchCount = 0;
var parentValues = parentRecord.values;
var childValues = childRecord.values;
for(var k=0;k<parentColumns.length;k++){
parentFieldIndex = getFieldsIndex(parentRecord.fields,parentColumns[k]);
childFieldIndex = getFieldsIndex(childRecord.fields,childColumns[k]);
if(parentValues[parentFieldIndex] != childValues[childFieldIndex]){
break;
}
matchCount++;
}
if(matchCount == parentColumns.length){
sync.log.info("record found in changeset for parent "+parentTableName + " with child "+childTableName);
return true;
}
}
return false;
}
function getFieldsIndex(fields,columnName){//helper function
for(var k = 0;k < fields.length;k++){
if(fields[k] === columnName)
return k;//fieldIndex
}
sync.log.error("error in changeSet record creation: no "+columnName +" found in fields");
}
function fetchAndAddParents(parentTableName,childRecord,childTableName){
sync.log.trace("entering into fetchAndAddParents");
//checking whether this parentTable is a part of changesetdictionary
if(tableDictionary[parentTableName] === undefined){
tableDictionary[parentTableName] = tableDictionarySize;//for the changeset
tableDictionarySize++;
}
parentRecordIndex = fetchParentFromMainTable(parentTableName,childRecord,childTableName);
if(parentRecordIndex == -1){
sync.log.error("improper relationships defined for "+parentTableName);
return -1;//
}
var tablesIndex = tableDictionary[parentTableName];
var parentRecord = changeset.tables[tablesIndex].changes[parentRecordIndex];
var parentTable = kony.sync.currentScope.syncTableDic[parentTableName];
//hierarchial upload operations metadata
var parentTableOperations = parentTable.InputOperations;
if(parentTableOperations === undefined)
return ;//no operations defined for the parent
var parentRecordChangeType = parentRecord.changeType;
var currentOperation = parentTableOperations[parentRecordChangeType];
if(currentOperation === undefined)
return;//no operation defined with this change type
var parentTableNames = currentOperation.Parents;
var childTableNames = currentOperation.Children;
if(isRoot(currentOperation) === false){//not root
if(parentTableNames != undefined){
for(var i = 0; i < parentTableNames.length ;i++ ){
//to avoid sending a record which is already in changeset
if(checkInChangeSet(parentTableNames[i],parentRecord,parentTableName) === false){
parentRecordIndex = fetchAndAddParents(parentTableNames[i],parentRecord,parentTableName);
}
}
}
}
sync.log.info("mark all the child records in the changeSet");
//mark all the children in the changeset
if(childTableNames != undefined){
for(var i = 0;i < childTableNames.length ;i++){
markChildRecords(childRelationInfo[parentTableName],parentRecord,parentTableName,childTableNames[i]);
}
}
}
function markChildRecords(childRelation,parentRecord,parentTableName,childTableName){
sync.log.trace("entering into markChildRecords function");
changeSetIndex = tableDictionary[childTableName];//index in changeset
if(changeSetIndex === undefined){
sync.log.info("no child records found in the change set to mark");
//when the childRecords are no there at all in changeset they wont be present in tabledictionary
return;
}
var records = changeset.tables[changeSetIndex].changes;//child object changeset
// not putting a null check as changes is an array
for(var j =0;j<records.length;j++){
var parentColumns = childRelation[childTableName].parentColumns;
var childColumns = childRelation[childTableName].childColumns;
childRecord = records[j];//child records
var matchCount = 0;
var parentValues = parentRecord.values;
var childValues = childRecord.values;
for(var k=0;k < parentColumns.length;k++){
parentFieldIndex = getFieldsIndex(parentRecord.fields,parentColumns[k]);
childFieldIndex = getFieldsIndex(childRecord.fields,childColumns[k]);
if(parentValues[parentFieldIndex] != childValues[childFieldIndex]){
break;
}
matchCount++;
}
if(matchCount == parentColumns.length){
if(childRecord.visitedParents === undefined)
childRecord.visitedParents = [];
sync.log.info("child record found in changeset with parent "+parentTableName+" and child "+childTableName);
childRecord.visitedParents.push(parentTableName);
}
}
}
function getChildRelationsInfo(currentTableName){
sync.log.trace("entering into getChildRelationsInfo ");
var childRelation = {};
// dictionary for relationships,need to optimise
currentTable = kony.sync.currentScope.syncTableDic[currentTableName];
OneToMany = currentTable.Relationships.OneToMany;
if(!kony.sync.isNullOrUndefined(currentTable.Relationships.OneToMany)){
for(var j=0;j < OneToMany.length;j++){
var currentRelation = OneToMany[j];
if(childRelation[currentRelation.TargetObject] === undefined){
childRelation[currentRelation.TargetObject] = {};
childRelation[currentRelation.TargetObject].parentColumns = [];
childRelation[currentRelation.TargetObject].childColumns = [];
}
RelationshipAttributes = currentRelation.RelationshipAttributes;
for(var k=0;k < RelationshipAttributes.length;k++){
childRelation[currentRelation.TargetObject].parentColumns.push(RelationshipAttributes[k].SourceObject_Attribute);
childRelation[currentRelation.TargetObject].childColumns.push(RelationshipAttributes[k].TargetObject_Attribute);
}
}
}
reverseRelationships = kony.sync.currentScope.reverseRelationships[currentTableName];
for (var k in reverseRelationships) {
var currentRelation = reverseRelationships[k]
if(childRelation[currentRelation.TargetObject] === undefined){
childRelation[currentRelation.TargetObject] = {};
childRelation[currentRelation.TargetObject].parentColumns = [];
childRelation[currentRelation.TargetObject].childColumns = [];
}
relationshipAttributes = currentRelation.RelationshipAttributes;
for (var j = 0; j < relationshipAttributes.length; j++) {
childRelation[currentRelation.TargetObject].parentColumns.push(relationshipAttributes[j].SourceObject_Attribute);
childRelation[currentRelation.TargetObject].childColumns.push(relationshipAttributes[j].TargetObject_Attribute);
}
}
return childRelation;
}
//entry point here
childRelationInfo = {};
scopeTables = kony.sync.currentScope.ScopeTables;
for(var j = 0;j < scopeTables.length;j++){
childRelationInfo[scopeTables[j].Name] = getChildRelationsInfo(scopeTables[j].Name);
}
//comparator function to sort dictionary
function compare(a,b) {
if (a.konysyncreplaysequence < b.konysyncreplaysequence)
return -1;
if (a.konysyncreplaysequence > b.konysyncreplaysequence)
return 1;
return 0;
}
sync.log.info("sorting the dictionary of changeset metadata w.r.t konyreplaysequence");
//sorting the dictionary of changeset metadata w.r.t konyreplaysequence
replaySequenceDictionary.sort(compare);
//Parent-child heirarchy upload Algoritm starts here ......
for(var j = 0;j < replaySequenceDictionary.length ; j++ ){
var replaySequenceValue = replaySequenceDictionary[j];
var changeSetIndex = replaySequenceValue.changeSetIndex;
var syncTableName = replaySequenceValue.syncTableName;
var tableIndex = tableDictionary[syncTableName];
var currentRecord = changeset.tables[tableIndex].changes[changeSetIndex];
var changeType = currentRecord.changeType;
if(kony.sync.currentScope.syncTableDic[syncTableName].InputOperations === undefined){
sync.log.info("no operation defined for "+syncTableName+" table");
continue;//no operation defined for this table
}
var operations = kony.sync.currentScope.syncTableDic[syncTableName].InputOperations;
var currentOperation = operations[changeType];
if(currentOperation === undefined){
sync.log.info("no operation defined for "+syncTableName+" table with changetype " +changeType );
continue;//no operation with this change type defined for this table
}
var childTableNames = currentOperation.Children;
if(isRoot(currentOperation) === false){
var parentsTable = currentOperation.Parents;
if(parentsTable === undefined){
sync.log.info("no parents defined for "+syncTableName+" table with changetype " +changeType );
continue;//no parents defined for a child
}
if(currentRecord.visitedParents === undefined){
currentRecord.visitedParents = [];
}
//getting the parents that are not visited
for(var k = 0;k < currentRecord.visitedParents.length;k++){
var index = parentsTable.indexOf(currentRecord.visitedParents[k]);
if (index > -1) {
parentsTable.splice(index, 1);
}
else{
sync.log.error("operations not defined properly for "+syncTableName);
}
}
for(var k = 0;k < parentsTable.length;k++){
sync.log.info("fetch parent records of "+currentRecord + " tablename "+syncTableName+" with parent "+parentsTable[k]);
parentRecord = fetchAndAddParents(parentsTable[k],currentRecord,syncTableName);
}
}
//mark all the children in the changeset
if(childTableNames != undefined){
for(var k = 0;k < childTableNames.length ;k++){
sync.log.info("mark child records of "+syncTableName +" for child "+childTableNames[k]);
markChildRecords(childRelationInfo[syncTableName],currentRecord,syncTableName,childTableNames[k]);
}
}
}
function isRoot(currentOperation){
sync.log.trace("entering into isRoot");
if(currentOperation.isRoot != undefined){
isRootFlag = currentOperation.isRoot[0];
if(isRootFlag === "true")
return true;
}
return false;
}
}
continueGettingChanges = false;
}
}while(continueGettingChanges);
function prepareChangeSet(tx, resultset){
sync.log.trace("Entering kony.sync.getBatchChanges->prepareChangeSet");
var len = resultset.rows.length;
for (var k = 0; k < len; k++) {
var row = kony.db.sqlResultsetRowItem(tx, resultset, k);
if(!kony.sync.isNullOrUndefined(kony.sync.scopes.syncScopeBlobInfoMap[syncTable.Name])) {
populateBinaryData(tx, row);
}
var changeType = row[kony.sync.historyTableChangeTypeColumn] + "";
if(kony.sync.currentScope.isHierarchical === true){
var replaySequenceMap = {};
replaySequenceMap["syncTableName"] = syncTable.Name;
replaySequenceMap["changeSetIndex"] = k;
replaySequenceMap["konysyncreplaysequence"] = row[kony.sync.historyTableReplaySequenceColumn];
replaySequenceDictionary.push(replaySequenceMap);//need to check
}
var rc = {
fields: [],
values: []
};
if (changeType === kony.sync.insertColStatus) {
rc.changeType = "insert";
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsInserted]=kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsInserted]+1;
kony.sync.syncTotalBatchInserts += 1;
} else if (changeType === kony.sync.updateColStatus) {
rc.changeType = "update";
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsUpdated]=kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsUpdated]+1;
kony.sync.syncTotalBatchUpdates += 1;
} else if (changeType === kony.sync.deleteColStatus) {
rc.changeType = "delete";
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsDeleted]=kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsDeleted]+1;
kony.sync.syncTotalBatchDeletes += 1;
}
//for all the missing columns, insert null.
if(!kony.sync.isNullOrUndefined(syncTable.Columns)){
for (var x = 0; x < syncTable.Columns.length; x++) {
var column = syncTable.Columns[x];
if(kony.sync.isNullOrUndefined(row[column.Name])){
if (column.Name.indexOf(kony.sync.binaryMetaColumnPrefix) !== 0 && column.type !== kony.sync.blob){
kony.table.insert(rc.fields, column.Name);
kony.table.insert(rc.values, "null");
}
}
}
}
for(var key in row){
if (key !== kony.sync.syncStatusColumn){
kony.table.insert(rc.fields, key);
kony.table.insert(rc.values, row[key]);
}
}
kony.table.insert(tc.changes, rc);
}
changeset.totalChanges = changeset.totalChanges + len;
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsUploaded] =
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsInserted] +
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsUpdated] +
kony.sync.objectLevelInfoMap[syncTable.Name][kony.sync.numberOfRowsDeleted];
}
function populateBinaryData(tx, row) {
var binaryColumns = kony.sync.scopes.syncScopeBlobInfoMap[syncTable.Name][kony.sync.columns];
var binaryColumnName = null;
var binaryMetaFieldKey = null;
for(var i=0; i<binaryColumns.length; i++) {
binaryColumnName = binaryColumns[i];
var downloadPolicy = kony.sync.getDownloadPolicy(syncTable.Name, binaryColumnName);
if(downloadPolicy !== kony.sync.inline) {
delete row[binaryColumnName];
binaryMetaFieldKey = kony.sync.binaryMetaColumnPrefix + binaryColumnName;
delete row[binaryMetaFieldKey];
}
//Add the columns with inline downloadpolicy.
else if(downloadPolicy === kony.sync.inline) {
binaryMetaFieldKey = kony.sync.binaryMetaColumnPrefix + binaryColumnName;
var blobIndex = row[binaryMetaFieldKey];
//If the record has any binary data..
if (blobIndex && blobIndex !== kony.sync.blobRefNotFound && blobIndex !== kony.sync.blobRefNotDefined) {
//get the state of the blob. if is in stable, then only push.
var blobMeta = kony.sync.blobManager.getBlobMetaDetails(tx, blobIndex, function(err){
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeTransaction,
kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
});
if(blobMeta[kony.sync.blobManager.state] === kony.sync.blobManager.NO_OPERATION &&
blobMeta[kony.sync.blobManager.status] === 100) {
//file exists. upload.
var base64String = binary.util.getBase64FromFiles([blobMeta[kony.sync.blobManager.localPath]]);
if(base64String[0].length > 0){
row[binaryColumnName] = base64String[0];
} else {
//FILE Doesn't exist.
var valuesTable = {};
valuesTable.state = kony.sync.blobManager.FILE_DOESNOT_EXIST;
var resultset = kony.sync.blobManager.updateBlobManager(tx, blobIndex, valuesTable, function(err){
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeTransaction,
kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
});
if(resultset !== null && resultset !== false) {
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeBlobFileDoesnotExist,
kony.sync.getErrorMessage(kony.sync.errorCodeBlobFileDoesnotExist), null));
}
delete row[binaryMetaFieldKey];
}
} else {
//file is in invalid state.
//TODO-throw error..blob in invalid state..
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeBlobInvalidState,
kony.sync.getErrorMessage(kony.sync.errorCodeBlobInvalidState), null));
}
}
}
}
function errorCallback(error) {
sync.log.trace(" error occured while fetching blob ");
}
}
sync.log.info("Total number of changes to be uploaded = ", changeset.totalChanges);
return limit;
};
//This will update syncorder for Pending uploads
kony.sync.updateSyncOrderForUploadBatching = function(tx, limit){
sync.log.trace("Entering kony.sync.updateSyncOrderForUploadBatching");
if(kony.sync.isNullOrUndefined(kony.sync.currentScope.ScopeTables)){
return true;
}
for (var i = 0; i < kony.sync.currentScope.ScopeTables.length; i++) {
var syncTable = kony.sync.currentScope.ScopeTables[i];
if(kony.sync.isNullOrUndefined(syncTable)){
continue;
}
var tablename = syncTable.Name;
var settable = [];
settable[kony.sync.historyTableSyncVersionColumn] = kony.sync.currentSyncScopesState[kony.sync.currentScope.ScopeName] + 1;
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tablename+kony.sync.historyTableName);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, [{key:kony.sync.historyTableReplaySequenceColumn,value:limit, optype: "GT"}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
}
return true;
};
//This method reconciles Foreign key relationships in case of autogenerated pk
kony.sync.reconcileForeignKey = function(tx, setClause, whereClause, tablename){
sync.log.trace("Entering kony.sync.reconcileForeignKey");
//Forward Relationships(OneToMany) reconcilation
var OTM = kony.sync.currentScope.syncTableDic[tablename].Relationships.OneToMany;
if(kony.sync.reconcileForeignKeyForRelationShip(tx, setClause, whereClause, tablename, OTM)===false){
return false;
}
//Forward Relationships(OneToOne) reconcilation
var OTO = kony.sync.currentScope.syncTableDic[tablename].Relationships.OneToOne;
if(kony.sync.reconcileForeignKeyForRelationShip(tx, setClause, whereClause, tablename, OTO)===false){
return false;
}
//Reverse Relationships(ManyToOne) reconcilation
var MTO = kony.sync.currentScope.reverseRelationships[tablename];
return kony.sync.reconcileForeignKeyForRelationShip(tx, setClause, whereClause, tablename, MTO);
};
kony.sync.reconcileForeignKeyForRelationShip = function(tx, setClause, whereClause, tablename, relationshipSet){
sync.log.trace("Entering kony.sync.reconcileForeignKeyForRelationShip");
if(!kony.sync.isNullOrUndefined(relationshipSet)){
for(var i in relationshipSet) {
sync.log.info("Reconciling relationships for object " + tablename + " with relationship ", relationshipSet[i]);
var setC = {};
var tbname = relationshipSet[i].TargetObject;
var wcs = [];
if(!kony.sync.isNullOrUndefined(relationshipSet[i].RelationshipAttributes))
{
var relationshipAttributes = relationshipSet[i].RelationshipAttributes;
for (var j = 0; j < relationshipAttributes.length; j++) {
if(!kony.sync.isNullOrUndefined(setClause[relationshipAttributes[j].SourceObject_Attribute])) {
setC[relationshipAttributes[j].TargetObject_Attribute] = setClause[relationshipAttributes[j].SourceObject_Attribute];
}
}
for(var j in whereClause){
for(var k=0;k<relationshipAttributes.length;k++){
if(whereClause[j].key === relationshipAttributes[k].SourceObject_Attribute){
wcs.push({key:relationshipAttributes[k].TargetObject_Attribute, value:whereClause[j].value});
}
}
}
} else if(!kony.sync.isNullOrUndefined(setClause[relationshipSet[i].SourceObject_Attribute])){
setC = {};
setC[relationshipSet[i].TargetObject_Attribute] = setClause[relationshipSet[i].SourceObject_Attribute];
tbname = relationshipSet[i].TargetObject;
wcs = [];
for(var j in whereClause){
if(whereClause[j].key === relationshipSet[i].SourceObject_Attribute){
wcs[0] = {key:relationshipSet[i].TargetObject_Attribute, value:whereClause[j].value};
break;
}
}
}
//update main foreign table
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, tbname);
kony.sync.qb_set(query, setC);
kony.sync.qb_where(query, wcs);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
//update history foreign table
kony.sync.qb_update(query, tbname + kony.sync.historyTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
//update original foreign table
kony.sync.qb_update(query, tbname + kony.sync.originalTableName);
query_compile = kony.sync.qb_compile(query);
sql = query_compile[0];
params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
}
}
};
kony.sync.checkForPendingUpload = function(tx, scopename){
sync.log.trace("Entering kony.sync.checkForPendingUpload");
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, kony.sync.pendingUploadTableName);
kony.sync.qb_where(query, [{
key: kony.sync.metaTableScopeColumn,
value: scopename
}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet===false){
return false;
}
if(resultSet.rows.length === 0){
return "";
}
else{
return kony.db.sqlResultsetRowItem(tx, resultSet, 0);
}
};
kony.sync.getUploadRequest = function (changes, lastBatch) {
var totalChanges = [];
if (!kony.sync.isNullOrUndefined(changes.tables)) {
for (var i = 0; i < changes.tables.length; i++) {
var tableChange = changes.tables[i];
var tableName = tableChange.tableName;
if (!kony.sync.isNullOrUndefined(tableChange.changes)) {
for (var j = 0; j < tableChange.changes.length; j++) {
var rowChange = tableChange.changes[j];
if (kony.sync.isNullOrUndefined(rowChange.syncConflict)) {
rowChange.syncConflict = "";
}
var result = {
metadata: {
type: tableName,
uri: changes.uri,
changetype: rowChange.changeType,
syncConflict: rowChange.syncConflict
}
};
if (!kony.sync.isNullOrUndefined(rowChange.fields)) {
var fcount = kony.sync.getArrayCount(rowChange.fields);
for (var k = 0; k < fcount; k++) {
if (rowChange.fields[k] !== "ServerId" && rowChange.fields[k] !== "UpdateId") {
result[rowChange.fields[k]] = rowChange.values[k];
}
}
}
totalChanges.push(result);
}
}
}
}
var moreChangesAvailable = null;
if (lastBatch === true) {
moreChangesAvailable = false;
} else {
moreChangesAvailable = true;
}
var jsonLua = {
d: {
results: totalChanges,
sync: "not implemented",
scopeName: changes.scopeName,
serverBlob: changes.serverblob,
clientid: changes.clientid,
SequenceNumber: changes.SequenceNumber,
moreChangesAvailable: moreChangesAvailable
}
};
return JSON.stringify(jsonLua);
}
kony.sync.getLastSyncUploadContext = function(scopename, dbname, scallback){
sync.log.trace("Entering kony.sync.getLastSyncUploadContext");
var uploadContext = null;
var pendingUploads = null;
var isError = false;
function transactionCallback(tx){
var query = kony.sync.qb_createQuery();
kony.sync.qb_select(query, null);
kony.sync.qb_from(query, kony.sync.metaTableName);
kony.sync.qb_where(query, [{
key: kony.sync.metaTableScopeColumn,
value: scopename
},{
key: kony.sync.metaTableFilterValue,
value: "no filter"
}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet===false){
isError = true;
return;
}
pendingUploads = kony.sync.checkForPendingUpload(tx, scopename);
if(pendingUploads===false){
return;
}
if(pendingUploads) {
if(pendingUploads.uploadrequest) {
var uploadrequest = JSON.parse(pendingUploads.uploadrequest);
var scopeName = uploadrequest[kony.sync.scope];
var cachedCurrentScope = kony.sync.scopes[scopeName];
var cachedOffset = uploadrequest[kony.sync.offset];
var cachedLimit = uploadrequest[kony.sync.limit];
var cachedLastSeqNo = uploadrequest[kony.sync.lastSequenceNumber];
var cachedBatchSize = uploadrequest[kony.sync.batchSize];
var cacheChangeSet = JSON.parse(uploadrequest[kony.sync.changeSet]);
var cacheUploadLimit = uploadrequest[kony.sync.uploadChangesLimit];
kony.sync.getBatchChanges(tx, cachedCurrentScope, cachedOffset, cacheUploadLimit, cacheChangeSet, cachedLastSeqNo, cachedBatchSize);
var cacheLastBatch = uploadrequest[kony.sync.lastBatch];
pendingUploads[kony.sync.pendingUploadTableUploadRequest] = kony.sync.getUploadRequest(cacheChangeSet, cacheLastBatch);
}
}
if(resultSet.rows.length === 0){
return "";
}
else{
uploadContext = kony.db.sqlResultsetRowItem(tx, resultSet, 0);
}
}
function transactionSuccessCallback(){
scallback(uploadContext, pendingUploads);
}
function transactionErrorCallback(){
sync.log.trace("Entering kony.sync.setOTAUploadResponse->setOTAUploadResponseTransactionFailure");
if (!isError){
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
}
else{
kony.sync.syncUploadFailed(kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
var connection = kony.sync.getConnectionOnly(dbname, dbname, transactionErrorCallback);
if(connection!==null){
kony.db.transaction(connection, transactionCallback, transactionErrorCallback, transactionSuccessCallback);
}
};
kony.sync.setLastSyncUploadContext = function(tx, scopename, serverblob) {
sync.log.trace("Entering kony.sync.setLastSyncUploadContext");
var settable = [];
settable[kony.sync.metaTableUploadSyncTimeColumn] = serverblob;
var query = kony.sync.qb_createQuery();
kony.sync.qb_update(query, kony.sync.metaTableName);
kony.sync.qb_set(query, settable);
kony.sync.qb_where(query, [{
key: kony.sync.metaTableScopeColumn,
value: scopename
}, {
key: kony.sync.metaTableFilterValue,
value: "no filter"
}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
};
kony.sync.addLastUploadRequest = function (json, scopename, limit, callback){
sync.log.trace("Entering kony.sync.addLastUploadRequest");
var isError = false;
function transactionCallback(tx){
//check whether failed upload request is already logged
var lastRequest = kony.sync.checkForPendingUpload(tx, scopename);
//return if query failed, should go to error callback
if(lastRequest===false){
return;
}
//return if request already logged, should go to success callback
if(lastRequest!==""){
return;
}
var settable = {};
settable[kony.sync.metaTableScopeColumn] = scopename;
settable[kony.sync.pendingUploadTableInsertCount] = kony.sync.syncTotalInserts;
settable[kony.sync.pendingUploadTableUpdateCount] = kony.sync.syncTotalUpdates;
settable[kony.sync.pendingUploadTableDeleteCount] = kony.sync.syncTotalDeletes;
settable[kony.sync.pendingUploadTableBatchInsertCount] = kony.sync.syncTotalBatchInserts;
settable[kony.sync.pendingUploadTableBatchUpdateCount] = kony.sync.syncTotalBatchUpdates;
settable[kony.sync.pendingUploadTableBatchDeleteCount] = kony.sync.syncTotalBatchDeletes;
settable[kony.sync.pendingUploadTableObjectLevelInfo] = JSON.stringify(kony.sync.objectLevelInfoMap);
settable[kony.sync.pendingUploadTableUploadRequest] = json;
settable[kony.sync.pendingUploadTableUploadLimit] = limit;
var query = kony.sync.qb_createQuery();
kony.sync.qb_insert(query, kony.sync.pendingUploadTableName);
kony.sync.qb_set(query, settable);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
var resultSet = kony.sync.executeSql(tx, sql, params);
if(resultSet===false){
isError = true;
}
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.addLastUploadRequest->transactionSuccessCallback");
callback(true);
}
function transactionErrorCallback(){
sync.log.trace("Entering kony.sync.addLastUploadRequest->transactionErrorCallback");
if (!isError){
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeTransaction,
kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
}
else{
kony.sync.syncUploadFailed(kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var connection = kony.sync.getConnectionOnly(dbname, dbname, transactionErrorCallback);
if(connection!==null){
kony.db.transaction(connection, transactionCallback, transactionErrorCallback, transactionSuccessCallback);
}
};
kony.sync.deleteLastUploadRequest = function (tx, scopename){
sync.log.trace("Entering kony.sync.deleteLastUploadRequest");
var query = kony.sync.qb_createQuery();
kony.sync.qb_delete(query, kony.sync.pendingUploadTableName);
kony.sync.qb_where(query, [{key:kony.sync.metaTableScopeColumn, value:scopename}]);
var query_compile = kony.sync.qb_compile(query);
var sql = query_compile[0];
var params = query_compile[1];
if(kony.sync.executeSql(tx, sql, params)===false){
return false;
}
return true;
};
kony.sync.deleteLastUploadRequestWithNewTransaction = function (callback){
sync.log.trace("Entering kony.sync.deleteLastUploadRequestWithNewTransaction");
var isError = false;
function transactionCallback(tx){
if(kony.sync.deleteLastUploadRequest(tx, kony.sync.currentScope[kony.sync.scopeName])===false){
isError = true;
}
}
function transactionSuccessCallback(){
sync.log.trace("Entering kony.sync.deleteLastUploadRequestWithNewTransaction->transactionSuccessCallback");
callback(true);
}
function transactionErrorCallback(){
sync.log.trace("Entering kony.sync.deleteLastUploadRequestWithNewTransaction->transactionErrorCallback");
if (!isError){
kony.sync.syncUploadFailed(kony.sync.getErrorTable(kony.sync.errorCodeTransaction, kony.sync.getErrorMessage(kony.sync.errorCodeTransaction), null));
}
else{
kony.sync.syncUploadFailed(kony.sync.errorObject);
kony.sync.errorObject = null;
}
}
var dbname = kony.sync.currentScope[kony.sync.scopeDataSource];
var connection = kony.sync.getConnectionOnly(dbname, dbname, transactionErrorCallback);
if(connection!==null){
kony.db.transaction(connection, transactionCallback, transactionErrorCallback, transactionSuccessCallback);
}
};
// **************** End KonySyncUpload.js*******************
// **************** Start KonySyncValidations.js*******************
if (typeof(kony.sync) === "undefined") {
kony.sync = {};
}
kony.sync.attributeValidation = function(valuestable, tablename, errorcallback, isInsert){
sync.log.trace("kony.sync.attributeValidation ", valuestable);
if(!kony.sync.enableORMValidations){
return true;
}
if(valuestable != null){
var scope = kony.sync.scopes[kony.sync.scopes.syncTableScopeDic[tablename]];
var columns = scope.syncTableDic[tablename].ColumnsDic;
kony.sync.filterAttributes(valuestable, columns, tablename, isInsert);
var expectedType = null;
var expectedLength = null;
var jsType = null;
for(var key in columns){
expectedType = columns[key].type;
expectedLength = columns[key].Length;
jsType = kony.sync.getJSType(expectedType);
//Type validation
sync.log.debug("kony.sync.attributeValidation:Starting Type Validations");
if(jsType === "number" || jsType === "boolean"){
if(!kony.sync.isEmptyString(valuestable[key])){
if(!kony.sync.isNull(valuestable[key]) && jsType === "number" && !kony.sync.isValidNumberType(valuestable[key])){
sync.log.error("Invalid data type for the attribute " + key + " in " + tablename + ".\nExpected:\"" + expectedType + "\"\nActual:\"" + kony.type(valuestable[key]) + "\"");
errorcallback(kony.sync.getErrorTable(kony.sync.errorCodeInvalidDataType,kony.sync.getInvalidDataTypeMsg(tablename, key, expectedType, kony.type(valuestable[key]))));
return false;
}
if(!kony.sync.isNull(valuestable[key]) && jsType === "boolean" && !kony.sync.isValidBooleanType(valuestable[key])){
sync.log.error("Invalid data type for the attribute " + key + " in " + tablename + ".\nExpected:\"" + expectedType + "\"\nActual:\"" + kony.type(valuestable[key]) + "\"");
errorcallback(kony.sync.getErrorTable(kony.sync.errorCodeInvalidDataType,kony.sync.getInvalidDataTypeMsg(tablename, key, expectedType, kony.type(valuestable[key]))));
return false;
}
}else {
valuestable[key] = "null";
}
}
sync.log.debug("kony.sync.attributeValidation:Type Validations done");
//Malicious type validation
sync.log.debug("kony.sync.attributeValidation:Starting Malicious Validations");
if(jsType === "number" || typeof(valuestable[key]) === "number"){
var maliciousType=kony.sync.isMaliciousType(valuestable[key]);
if(maliciousType!== false){
var errorMessage = kony.sync.getErrorMessage(kony.sync.errorCodeMaliciousType, key, maliciousType);
sync.log.error("Malicious object detected", kony.sync.getErrorTable(kony.sync.errorCodeMaliciousType, errorMessage));
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(kony.sync.errorCodeMaliciousType, errorMessage));
return false;
}
}
sync.log.debug("kony.sync.attributeValidation:Malicious Validations done");
//Length Validation
sync.log.debug("kony.sync.attributeValidation:Starting Length Validations");
if(jsType === "string"){
if(kony.sync.validateLength(tablename, key, valuestable[key], expectedLength, errorcallback)===false){
return false;
}
}
sync.log.debug("kony.sync.attributeValidation:Length Validations done");
//Mandatory Attribute Validation
sync.log.debug("kony.sync.attributeValidation:Starting Mandatory Attribute Validations");
// if(columns[key].IsNullable === false && !(columns[key].Autogenerated === "true") && !(isInsert===false && columns[key].IsPrimaryKey===true)){
// if(kony.sync.validateMandatoryColumns(tablename, key, valuestable[key], errorcallback)===false){
// return false;
// }
// }
if(isInsert){
//check all mandatory attributes
if(columns[key].IsNullable === false){
if(columns[key].Autogenerated !== "true"){
if(kony.sync.validateMandatoryColumns(tablename, key, valuestable[key], errorcallback)===false){
return false;
}
}
}
}
else{
//check mandatory attributes only if they are defined
if(columns[key].IsNullable === false){
if(columns[key].Autogenerated !== "true"){
if(typeof(valuestable[key])!=="undefined"){
if(kony.sync.validateMandatoryColumns(tablename, key, valuestable[key], errorcallback)===false){
return false;
}
}
}
}
}
sync.log.debug("kony.sync.attributeValidation:Mandatory Attribute Validations done");
}
}
return true;
};
kony.sync.filterAttributes = function(valuestable, attributeTable, tablename, isInsert){
for (var k in valuestable){
if(kony.sync.isNull(attributeTable[k])){
sync.log.warn("Ignoring the attribute " + k + " for the SyncObject " + tablename + ". " + k + " is not defined as an attribute in SyncConfiguration.");
delete valuestable[k];
}else if(attributeTable[k].IsPrimaryKey){
if(isInsert === false){
sync.log.warn("Ignoring the primary key " + k + " for the SyncObject " + tablename + ". Primary Key should not be the part of the attributes to be updated in the local device database.");
delete valuestable[k];
}else if(attributeTable[k].Autogenerated === "true"){
sync.log.warn("Ignoring the auto-generated primary key " + k + " for the SyncObject " + tablename + ". Auto-generated Primary Key should not be the part of the attributes to be inserted in the local device database.");
delete valuestable[k];
}
}
}
};
kony.sync.getJSType = function(myType){
myType = myType.toLowerCase();
var stringTypes = {
"string" : true,
"character" : true,
"java.lang.String" : true,
"char" : true
};
var numberTypes = {
"int" : true,
"double" : true,
"float" : true,
"long" : true,
"short" : true,
"integer" : true,
"big_decimal" : true,
"byte" : true,
"big_integer" : true
};
var booleanTypes = {
"boolean" : true,
"yes_no" : true
};
if(stringTypes[myType] === true) {
return "string";
}
if (numberTypes[myType] === true) {
return "number";
}
if (booleanTypes[myType] === true) {
return "boolean";
}
return null;
};
kony.sync.validateLength = function (tablename, colname, colvalue, length, errorcallback) {
sync.log.trace("Entering kony.sync.validateLength ");
if (!kony.sync.isNull(colvalue) && kony.string.equalsIgnoreCase(kony.type(colvalue), "string") && kony.string.len(colvalue) > length) {
sync.log.error("Length exceeds the limit for the attribute " + colname + " in " + tablename + ".\nExpected:\'" + length + "\'\nActual:\'" + kony.string.len(colvalue) + "\'");
kony.sync.verifyAndCallClosure(errorcallback, kony.sync.getErrorTable(kony.sync.errorCodeLengthValidationFailed, kony.sync.getValidateLengthErrMsg(tablename, colname, length, kony.string.len(colvalue))));
return false;
}
return true;
};
kony.sync.validateMandatoryColumns = function(tablename, colname, colvalue, errorcallback){
sync.log.trace("Entering Address.validateNullInsert function");
if(kony.sync.isNull(colvalue)){
sync.log.error("Mandatory attribute " + colname + " is missing for the SyncObject" + tablename + ".");
errorcallback(kony.sync.getErrorTable(kony.sync.errorCodeMandatoryAttribute,kony.sync.getErrorMessage(kony.sync.errorCodeMandatoryAttribute, tablename, colname)));
return false;
}
return true;
};
kony.sync.isSyncInitialized = function (errorcallback) {
sync.log.trace("Entering kony.sync.isSyncInitialized");
if (!kony.sync.syncInitialized) {
sync.log.error("Please initialize sync by calling sync.init");
kony.sync.alert("Please initialize sync by calling sync.init");
kony.sync.verifyAndCallClosure(errorcallback, {});
return false;
}
return true;
};
kony.sync.validateInput = function (input, objectName, ormType, errorcallback) {
sync.log.trace("Entering kony.sync.validateInput");
if (ormType === "create") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validatePrimaryKeyField(objectName, ormType, input[0], errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "updateByPk") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 2)) {
if (!kony.sync.validatePrimaryKeyField(objectName, ormType, input[0], errorcallback)) {
return false;
}
if (!kony.sync.validateInputField(objectName, ormType, input[1], "object", errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "update") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 2)) {
if (!kony.sync.validateInputField(objectName, ormType, input[0], "string", errorcallback)) {
return false;
}
if (!kony.sync.validateInputField(objectName, ormType, input[1], "object", errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "getCount") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validateInputField(objectName, ormType, input[0], "string", errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "createAll") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validateInputField(objectName, ormType, input[0], "object", errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "updateAll") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validateInputField(objectName, ormType, input[0], "object", errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "deleteByPK") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validatePrimaryKeyField(objectName, ormType, input[0], errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "remove") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validateInputField(objectName, ormType, input[0], "string", errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "removeDeviceInstanceByPK") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validatePrimaryKeyField(objectName, ormType, input[0], errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "getAllDetailsByPK") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validatePrimaryKeyField(objectName, ormType, input[0], errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "find") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validateInputField(objectName, ormType, input[0], "string", errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "markForUploadbyPK") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validatePrimaryKeyField(objectName, ormType, input[0], errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "markForUpload") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validateInputField(objectName, ormType, input[0], "string", errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "rollbackPendingLocalChangesByPK") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validatePrimaryKeyField(objectName, ormType, input[0], errorcallback)) {
return false;
}
} else {
return false;
}
}else if (ormType === "relationship") {
if (kony.sync.validateArgumentLength(objectName, ormType, input.length, 1)) {
if (!kony.sync.validatePrimaryKeyField(objectName, ormType, input[0], errorcallback)) {
return false;
}
} else {
return false;
}
}
return true;
};
kony.sync.validatePrimaryKeyField = function(objName, opType, inputAttribute, errorcallback) {
sync.log.trace("Entering kony.sync.validatePrimaryKeyField");
if (kony.sync.isNullOrUndefined(inputAttribute)) {
kony.sync.verifyAndCallClosure(errorcallback, "Argument type mismatch found for operation:" + objName + ". Expected 'integer, string or object ' Actual null or undefined '");
kony.sync.alert("Argument type mismatch found for operation:" + objName + ". Expected 'integer, string or object' Actual 'null or undefined'");
return false;
}
var actualType = typeof(inputAttribute);
if(!(actualType === "number" || actualType === "string" || actualType === "object")){
kony.sync.verifyAndCallClosure(errorcallback, "Argument type mismatch found for Primary Key in operation:" + objName + ". Expected 'integer, string or object' Actual '" + actualType + "'");
kony.sync.alert("Argument type mismatch found for operation:" + objName + ". Expected 'integer, string or object' Actual '" + actualType + "'");
return false;
}
return true;
};
kony.sync.validateInputField = function (objName, opType, inputAttribute, expectedType, errorcallback) {
sync.log.trace("Entering kony.sync.validateInputField");
if (kony.sync.isNullOrUndefined(inputAttribute)) {
kony.sync.verifyAndCallClosure(errorcallback, "Argument type mismatch found for operation:" + objName + ". Expected '" + expectedType + "' Actual 'null or undefined '");
kony.sync.alert("Argument type mismatch found for operation:" + objName + ". Expected '" + expectedType + "' Actual 'null or undefined'");
return false;
}
var actualType = typeof(inputAttribute);
if (actualType !== expectedType) {
kony.sync.verifyAndCallClosure(errorcallback, "Argument type mismatch found for operation:" + objName + ". Expected '" + expectedType + "' Actual '" + actualType + "'");
kony.sync.alert("Argument type mismatch found for operation:" + objName + ". Expected '" + expectedType + "' Actual '" + actualType + "'");
return false;
}
return true;
};
kony.sync.validateArgumentLength = function (objName, ormType, actualLength, expectedLength) {
sync.log.trace("Entering kony.sync.validateArgumentLength");
if (actualLength < expectedLength) {
kony.sync.alert("Insufficient number of arguments passed for operation: " + objName);
return false;
}
return true;
};
kony.sync.alert = function(msg){
if(kony.sync.isAlertEnabled){
alert(msg);
}
else{
kony.print(msg);
}
};
// **************** End KonySyncValidations.js*******************
|
var _arity = require('./internal/_arity');
var _pipe = require('./internal/_pipe');
var reduce = require('./reduce');
var tail = require('./tail');
/**
* Performs left-to-right function composition. The leftmost function may have
* any arity; the remaining functions must be unary.
*
* In some libraries this function is named `sequence`.
*
* @func
* @memberOf R
* @category Function
* @sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z)
* @param {...Function} functions
* @return {Function}
* @see R.compose
* @example
*
* var f = R.pipe(Math.pow, R.negate, R.inc);
*
* f(3, 4); // -(3^4) + 1
*/
module.exports = function pipe() {
if (arguments.length === 0) {
throw new Error('pipe requires at least one argument');
}
return _arity(arguments[0].length,
reduce(_pipe, arguments[0], tail(arguments)));
};
|
var searchData=
[
['onebyfftlen',['onebyfftLen',['../structarm__cfft__radix2__instance__f32.html#a1d3d289d47443e597d88a40effd14b8f',1,'arm_cfft_radix2_instance_f32::onebyfftLen()'],['../structarm__cfft__radix4__instance__f32.html#ab9eed39e40b8d7c16381fbccf84467cd',1,'arm_cfft_radix4_instance_f32::onebyfftLen()']]],
['outlen',['outLen',['../arm__convolution__example__f32_8c.html#a9c49c44c8bc5c432d220d33a26b4b589',1,'arm_convolution_example_f32.c']]],
['outputq31',['outputQ31',['../arm__graphic__equalizer__example__q31_8c.html#a9862488450f2547b07aee8035d6b4d8a',1,'arm_graphic_equalizer_example_q31.c']]]
];
|
'use strict';
var async = require('async');
var logger = require('../logger/logger').logger;
var NewsImporter = function NewsImporter(festivalsClient) {
var news = {};
var NewsResolver = {
addNews: function (name, news) {
news[name] = news;
},
getNews: function (name) {
if (news.hasOwnProperty(name)) {
return news[name];
}
return null;
},
resolve: function (news, festivalId, cb) {
var _this = this;
if (_this.getNews(news.name)) {
return cb(null, _this.getNews[news.name]);
}
var query = {
name: news.name
};
return festivalsClient.getFestivalNewsCollection(festivalId, query, function (errGet, responseGet, bodyGet) {
if (errGet) {
logger.warn(errGet, bodyGet);
return cb(errGet);
}
if (responseGet.statusCode !== 200 || bodyGet.total === 0) {
var data = {
name: news.name,
description: news.description,
tags: news.tags,
authors: news.authors,
images: news.images,
publishedAt: news.publishedAt
};
return festivalsClient.createNews(festivalId, data, function (errCreate, responseCreate, bodyCreate) {
if (errCreate) {
logger.warn(errCreate, bodyCreate);
return cb(errCreate);
}
if (responseCreate.statusCode === 201 && bodyCreate) {
_this.addNews(news.name, bodyCreate);
return cb(null, bodyCreate);
}
logger.warn('Failed to create news: ', data, bodyCreate);
return cb(new Error('Failed to create news: ' + data.name));
});
}
else {
_this.addNews(news.name, bodyGet.news[0]);
return cb(null, bodyGet.news[0]);
}
});
}
};
var createTasksForNews = function createTasksForNews(newsCollection, festivalId) {
var tasks = {};
for (var j in newsCollection) {
if (newsCollection.hasOwnProperty(j)) {
var news = newsCollection[j];
logger.debug('Prepare news task ' + j + ': ' + news.name);
(function (news, fid) {
var func = function (callback) {
logger.debug('Initiated ' + j + ' news: ' + news);
NewsResolver.resolve(news, fid, callback);
};
tasks[news.name] = func;
}(news, festivalId));
}
}
return tasks;
};
var extractNews = function extractNews(templateData, callback) {
var newsCollection = {};
templateData.news.map(function (news) {
newsCollection[news.name] = news;
});
return callback(null, newsCollection);
};
var syncNews = function syncNews(newsData, festivalId, callback) {
var tasks = createTasksForNews(newsData, festivalId);
async.series(tasks, callback);
};
var importNews = function importNews(festivalId, templateData, callback) {
return extractNews(templateData, function (err, data) {
if (err) {
return callback(err);
}
return syncNews(data, festivalId, callback);
});
};
return {
importNews: importNews
};
};
module.exports = {
NewsImporter: NewsImporter
}; |
/**
* This is the main method that converts the document to a collection of pages. Since this method can be slow (depending
* on the number of DOM elements in the document), it runs async and returns a promise.
* @param currentScroll
*/
function composePage(currentScroll) {
var deferred = new $.Deferred();
ROOT = $(OPTIONS.rootElement);
var fragment = createDocumentFragment();
CONTAINER = $(fragment.querySelector('#hrz-container'));
CONTAINER.css({
'display': 'none', // setting display:none considerably speeds up rendering
'top': 0,
'left': 0
});
VIEWPORT_HEIGHT = $(window).height() - OPTIONS.pageMargin * 2;
displayLoadingIndicator().then(function() {
// a setTimeout is used to force async execution and allow the loadingIndicator to display before the
// heavy computations of composePage() are begun.
setTimeout(function() {
if (!OPTIONS.displayScrollbar) {
$('body').css('overflow-y', 'hidden');
}
var allNodes = new NodeCollection(OPTIONS.selector);
PAGE_COLLECTION = pageCollectionGenerator.fromNodeCollection(allNodes);
PAGE_COLLECTION.appendToDom(currentScroll);
// remove any DOM nodes that are not included in the selector,
// since they will just be left floating around in the wrong place.
CONTAINER.children().not('.hrz-page').filter(':visible').remove();
ROOT.empty().append(fragment);
// add the theme's custom CSS to the document now so that it can be
// used in calculating the elements' styles.
addCustomCssToDocument();
PAGE_COLLECTION.forEach(function(page) {
page.nodes.forEach(function(node) {
node.renderStyles(page);
});
});
CONTAINER.css('display', '');
var documentHeight = PAGE_COLLECTION.last().bottom / OPTIONS.scrollbarShortenRatio + VIEWPORT_HEIGHT;
ROOT.height(documentHeight);
renderPageCount();
removeLoadingIndicator();
deferred.resolve();
}, 0);
});
return deferred.promise();
}
/**
* Add the CSS text loaded by loadCustomCss() into the document head.
*/
function addCustomCssToDocument() {
var $customCssElement = $('#hrz-custom-css');
if (0 < $customCssElement.length) {
$customCssElement.text(CUSTOM_CSS);
} else {
$('head').append('<style id="hrz-custom-css" type="text/css">' + CUSTOM_CSS + '</style>');
}
}
/**
* Building up a documentFragment and then appending it all at once to the DOM
* is done to improve performance.
* @returns {*}
*/
function createDocumentFragment() {
var fragment = document.createDocumentFragment();
var containerDiv = document.createElement('div');
containerDiv.id = 'hrz-container';
fragment.appendChild(containerDiv);
return fragment;
}
function displayLoadingIndicator() {
var deferred = new $.Deferred();
if ($('.hrz-loading-indicator').length === 0) {
$('body').append('<div class="hrz-loading-indicator" style="display:none;"><p class="hrz-loading-indicator">Loading...</p></div>');
$('div.hrz-loading-indicator').fadeIn(50, function() {
deferred.resolve();
});
}
return deferred.promise();
}
function removeLoadingIndicator() {
setTimeout(function() {
$('div.hrz-loading-indicator').fadeOut(50, function() {
$(this).remove();
});
}, 300);
}
function renderPageCount() {
if ($('.hrz-page-count').length === 0) {
var pageCountDiv = $('<div class="hrz-page-count"></div>');
$('body').append(pageCountDiv);
pageCountDiv.append('<span id="hrz-current-page"></span> / <span id="hrz-total-pages"></span>');
$('#hrz-total-pages').html(PAGE_COLLECTION.length);
if (!OPTIONS.displayPageCount) {
pageCountDiv.addClass('hidden');
}
}
}
function removePageCount() {
$('.hrz-page-count').remove();
}
function updatePageCount() {
$('#hrz-current-page').html(PAGE_COLLECTION.currentPage);
}
/**
* + Jonas Raoni Soares Silva
* @ http://jsfromhell.com/array/shuffle [v1.0]
* @param o
* @returns {*}
*/
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
function noop() {} |
BASE.require([
"jQuery",
"jQuery.fn.region",
"BASE.util.invokeMethodIfExistsAsync",
"BASE.util.invokeMethodIfExists"
], function () {
var invokeMethodIfExistsAsync = BASE.util.invokeMethodIfExistsAsync;
var invokeMethodIfExists = BASE.util.invokeMethodIfExists;
var Future = BASE.async.Future;
var fulfilledFuture = Future.fromResult();
var $body = $(document.body);
BASE.namespace("components.gem");
components.gem.Window = function (elem, tags, scope) {
var self = this;
var $elem = $(elem);
var $container = $(tags["container"]);
var $resize = $(tags["resize"]);
var $resizeBox = $(tags["resize-box"]);
var $handle = $(tags["handle"]);
var $close = $(tags["close"]);
var $name = $(tags["name"]);
var regionConstraint = null;
var windowMouseStartXY = null;
var windowStartXY = null;
var resizeMouseStartXY = null;
var windowRegion = null;
var lastCoords = {};
var delegate = {};
var minSize = {
width: 400,
height: 400
};
var maxSize = null;
self.getComponent = function () {
return $container.children()[0];
};
self.setRegionContraint = function (region) {
regionConstraint = region;
};
self.centerAsync = function () {
if (delegate && typeof delegate.centerAsync === "function") {
return delegate.centerAsync();
}
return fulfilledFuture;
};
self.closeAsync = function () {
if (delegate && typeof delegate.closeAsync === "function") {
return delegate.closeAsync();
}
return fulfilledFuture;
};
self.showAsync = function () {
if (delegate && typeof delegate.showAsync === "function") {
return delegate.showAsync();
}
return fulfilledFuture;
};
self.disposeAsync = function () {
if (delegate && typeof delegate.disposeAsync === "function") {
return delegate.disposeAsync();
}
return fulfilledFuture;
};
self.setDelegate = function (value) {
delegate = value;
};
self.setName = function (name) {
$name.text(name);
};
self.hideCloseButton = function () {
$close.addClass("hide");
};
self.showCloseButton = function () {
$close.removeClass("hide");
};
self.setMinSize = function (size) {
if (typeof size.width !== "number" || typeof size.height !== "number" || size.width <= 0 || size.height <= 0) {
throw new Error("Width and height need to be set to a number greater than 0.");
}
minSize = size;
};
self.setMaxSize = function (size) {
if (typeof size.width !== "number" || typeof size.height !== "number" || size.width <= 0 || size.height <= 0) {
throw new Error("Width and height need to be set to a number greater than 0.");
}
maxSize = size;
};
self.setSize = function (size) {
if (typeof size.width !== "number" || typeof size.height !== "number" || size.width <= 0 || size.height <= 0) {
throw new Error("Width and height need to be set to a number greater than 0.");
}
$elem.css({
width: size.width + "px",
height: size.height + "px"
});
};
self.disableResize = function () {
if ($resize.attr("enabled") != null) {
$resize.off("mousedown", resizeMouseDown);
$resize.removeAttr("enabled");
$resize.addClass("hide");
}
};
self.enableResize = function () {
if ($resize.attr("enabled") == null) {
$resize.on("mousedown", resizeMouseDown);
$resize.attr("enabled", "enabled");
$resize.removeClass("hide");
}
};
self.setColor = function (cssColor) {
$handle.css("background-color", cssColor);
};
var mousemove = function (event) {
var cursorDeltaX = event.pageX - windowMouseStartXY.x;
var cursorDeltaY = event.pageY - windowMouseStartXY.y;
lastCoords.left = cursorDeltaX + windowStartXY.x;
lastCoords.top = cursorDeltaY + windowStartXY.y;
$resizeBox.offset({
top: lastCoords.top,
left: lastCoords.left
});
};
var mouseup = function (event) {
$elem.css({
top: lastCoords.top + "px",
left: lastCoords.left + "px"
});
$resizeBox.addClass("hide");
$resizeBox.css({
top: 0,
left: 0
});
$body.off("mousemove", mousemove);
$body.off("mouseup", mouseup);
$body.off("mouseleave", mouseup);
};
$handle.on("mousedown", function (event) {
$resizeBox.removeClass("hide");
invokeMethodIfExists(delegate, "focus");
windowMouseStartXY = {
x: event.pageX,
y: event.pageY
};
windowStartXY = $elem.region();
lastCoords.left = windowStartXY.left;
lastCoords.top = windowStartXY.top;
$body.on("mousemove", mousemove);
$body.on("mouseup", mouseup);
$body.on("mouseleave", mouseup);
return false;
});
var resizeMouseDown = function (event) {
windowRegion = $elem.region();
resizeMouseStartXY = {
x: event.pageX,
y: event.pageY
};
$resizeBox.css({
"width": windowRegion.width + "px",
"height": windowRegion.height + "px"
});
$body.on("mousemove", resizeMouseMove).
on("mouseup", resizeMouseUp).
on("mouseleave", resizeMouseUp);
return false;
};
var resizeMouseMove = function (event) {
var deltaX = event.pageX - resizeMouseStartXY.x;
var deltaY = event.pageY - resizeMouseStartXY.y;
var currentWidth = windowRegion.width + deltaX;
var currentHeight = windowRegion.height + deltaY;
currentWidth = currentWidth >= minSize.width ? currentWidth : minSize.width;
currentHeight = currentHeight >= minSize.height ? currentHeight : minSize.height;
$resizeBox.removeClass("hide");
$resizeBox.css({
"width": currentWidth + "px",
"height": currentHeight + "px"
});
return false;
};
var resizeMouseUp = function () {
$(document.body).off("mousemove", resizeMouseMove).
off("mouseup", resizeMouseUp).
off("mouseleave", resizeMouseUp);
var resizeRegion = $resizeBox.region();
if (resizeRegion.height !== 0 || resizeRegion.width !== 0) {
$elem.css({
width: resizeRegion.width + "px",
height: resizeRegion.height + "px"
});
}
$resizeBox.addClass("hide");
$resizeBox.css({
width: "100%",
height: "100%"
});
var controller = $(self.getComponent()).controller();
if (controller) {
invokeMethodIfExists(controller, "windowResize");
}
return false;
};
$close.on("mousedown", function () {
invokeMethodIfExists(delegate, "focus");
return false;
});
$close.on("click", function () {
self.closeAsync().try();
});
$elem.on("mousedown", function () {
invokeMethodIfExists(delegate, "focus");
});
$resize.on("mousedown", resizeMouseDown);
};
}); |
// Pseudo-random generator
'use strict';
// Generate a random function that is seeded with the given value.
function generator(seed) {
// Note: the generator didn't work with negative seed values, so here we
// transform our original seed into a new (positive) seed value with which we
// create a new generator.
if (seed < 0) {
var gen = generator(Math.abs(seed));
for (var i = 0; i < 23; i += 1) {
gen();
}
return generator(gen(0, 10000));
}
// Based on random number generator from
// http://indiegamr.com/generate-repeatable-random-numbers-in-js/
return function (min, max) {
min = min || 0;
max = max || 1;
seed = (seed * 9301 + 49297) % 233280;
var v = seed / 233280;
return min + v * (max - min);
};
}
exports.generator = generator;
|
define({
titulo: 'SQUAREFramework Archetype Application',
menu: {
inicio: 'Home',
todo: 'Todo MVC'
},
defaults: {
salvar: 'Save',
cancelar: 'Cancel',
deletar: 'Delete',
avancar: 'Advance',
localizar: 'Searching',
alteracaoSucesso: 'Operation performed successfully.',
exclusaoSucesso: 'Exclusion performed successful.'
},
home: {
titulo: '\'Allo, \'Allo!',
subTitulo: 'Enjoy coding! - SQUAREFramework',
instaladoPre: 'You now have',
instaladoPos: 'installed.'
},
todo: {
novo: 'New Todo',
editar: 'Edit Todo',
deletar: 'Delete Todo',
cadastros: 'Todos registered',
deletarPergunta: 'Are you sure you want to delete this ',
titulo: 'Title',
concluido: 'Completed'
}
}); |
/**************************************************************************
* AngularJS-nvD3, v1.0.0-beta; MIT License; 25/02/2015 22:27
* http://krispo.github.io/angular-nvd3
**************************************************************************/
(function(){
'use strict';
angular.module('nvd3', [])
.directive('nvd3', ['utils', function(utils){
return {
restrict: 'AE',
scope: {
data: '=', //chart data, [required]
options: '=', //chart options, according to nvd3 core api, [required]
api: '=?', //directive global api, [optional]
events: '=?', //global events that directive would subscribe to, [optional]
config: '=?' //global directive configuration, [optional]
},
link: function(scope, element, attrs){
var defaultConfig = {
extended: false,
visible: true,
disabled: false,
autorefresh: true,
refreshDataOnly: false,
deepWatchData: true,
debounce: 10 // default 10ms, time silence to prevent refresh while multiple options changes at a time
};
//basic directive configuration
scope._config = angular.extend(defaultConfig, scope.config);
//directive global api
scope.api = {
// Fully refresh directive
refresh: function(){
scope.api.updateWithOptions(scope.options);
},
// Update chart layout (for example if container is resized)
update: function() {
scope.chart.update();
},
// Update chart with new options
updateWithOptions: function(options){
// Clearing
scope.api.clearElement();
// Exit if options are not yet bound
if (angular.isDefined(options) === false) return;
// Exit if chart is hidden
if (!scope._config.visible) return;
// Initialize chart with specific type
scope.chart = nv.models[options.chart.type]();
// Generate random chart ID
scope.chart.id = Math.random().toString(36).substr(2, 15);
angular.forEach(scope.chart, function(value, key){
if ([
'options',
'_options',
'_inherited',
'_d3options',
'state',
'id',
'resizeHandler'
].indexOf(key) >= 0);
else if (key === 'dispatch') {
if (options.chart[key] === undefined || options.chart[key] === null) {
if (scope._config.extended) options.chart[key] = {};
}
configureEvents(scope.chart[key], options.chart[key]);
}
else if ([
'lines',
'lines1',
'lines2',
'bars',
'bars1',
'bars2',
'stack1',
'stack2',
'stacked',
'multibar',
'discretebar',
'pie',
'scatter',
'bullet',
'sparkline',
'legend',
'distX',
'distY',
'xAxis',
'x2Axis',
'yAxis',
'yAxis1',
'yAxis2',
'y1Axis',
'y2Axis',
'y3Axis',
'y4Axis',
'interactiveLayer',
'controls'
].indexOf(key) >= 0){
if (options.chart[key] === undefined || options.chart[key] === null) {
if (scope._config.extended) options.chart[key] = {};
}
configure(scope.chart[key], options.chart[key], options.chart.type);
}
//TODO: need to fix bug in nvd3
else if ((key === 'xTickFormat' || key === 'yTickFormat') && options.chart.type === 'lineWithFocusChart');
else if (options.chart[key] === undefined || options.chart[key] === null){
if (scope._config.extended) options.chart[key] = value();
}
else scope.chart[key](options.chart[key]);
});
// Update with data
scope.api.updateWithData(scope.data);
// Configure wrappers
if (options['title'] || scope._config.extended) configureWrapper('title');
if (options['subtitle'] || scope._config.extended) configureWrapper('subtitle');
if (options['caption'] || scope._config.extended) configureWrapper('caption');
// Configure styles
if (options['styles'] || scope._config.extended) configureStyles();
nv.addGraph(function() {
// Update the chart when window resizes
// nK fix error after destroy
scope.chart.resizeHandler = nv.utils.windowResize(function() { scope.chart && scope.chart.update(); });
return scope.chart;
}, options.chart['callback']);
},
// Update chart with new data
updateWithData: function (data){
if (data) {
scope.options.chart['transitionDuration'] = +scope.options.chart['transitionDuration'] || 250;
// remove whole svg element with old data
d3.select(element[0]).select('svg').remove();
// Select the current element to add <svg> element and to render the chart in
d3.select(element[0]).append('svg')
.attr('height', scope.options.chart.height)
.attr('width', scope.options.chart.width || '100%')
.datum(data)
.transition().duration(scope.options.chart['transitionDuration'])
.call(scope.chart);
}
},
// Fully clear directive element
clearElement: function (){
element.find('.title').remove();
element.find('.subtitle').remove();
element.find('.caption').remove();
element.empty();
if (scope.chart) {
// clear window resize event handler
if (scope.chart.resizeHandler) scope.chart.resizeHandler.clear();
// remove chart from nv.graph list
for (var i = 0; i < nv.graphs.length; i++)
if (nv.graphs[i].id === scope.chart.id) {
nv.graphs.splice(i, 1);
}
}
scope.chart = null;
nv.tooltip.cleanup();
if(window.nv) {
window.nv.charts = {};
window.nv.graphs = [];
window.nv.logs = {};
window.onresize = null;
}
},
// Get full directive scope
getScope: function(){ return scope; }
};
// Configure the chart model with the passed options
function configure(chart, options, chartType){
if (chart && options){
angular.forEach(chart, function(value, key){
if (key === 'dispatch') {
if (options[key] === undefined || options[key] === null) {
if (scope._config.extended) options[key] = {};
}
configureEvents(value, options[key]);
}
else if ([
'scatter',
'defined',
'options',
'axis',
'rangeBand',
'rangeBands',
'_options',
'_inherited',
'_d3options',
'_calls'
].indexOf(key) < 0){
if (options[key] === undefined || options[key] === null){
if (scope._config.extended) options[key] = value();
}
else chart[key](options[key]);
}
});
}
}
// Subscribe to the chart events (contained in 'dispatch')
// and pass eventHandler functions in the 'options' parameter
function configureEvents(dispatch, options){
if (dispatch && options){
angular.forEach(dispatch, function(value, key){
if (options[key] === undefined || options[key] === null){
if (scope._config.extended) options[key] = value.on;
}
else dispatch.on(key + '._', options[key]);
});
}
}
// Configure 'title', 'subtitle', 'caption'.
// nvd3 has no sufficient models for it yet.
function configureWrapper(name){
var _ = utils.deepExtend(defaultWrapper(name), scope.options[name] || {});
if (scope._config.extended) scope.options[name] = _;
var wrapElement = angular.element('<div></div>').html(_['html'] || '')
.addClass(name).addClass(_.class)
.removeAttr('style')
.css(_.css);
if (!_['html']) wrapElement.text(_.text);
if (_.enable) {
if (name === 'title') element.prepend(wrapElement);
else if (name === 'subtitle') element.find('.title').after(wrapElement);
else if (name === 'caption') element.append(wrapElement);
}
}
// Add some styles to the whole directive element
function configureStyles(){
var _ = utils.deepExtend(defaultStyles(), scope.options['styles'] || {});
if (scope._config.extended) scope.options['styles'] = _;
angular.forEach(_.classes, function(value, key){
value ? element.addClass(key) : element.removeClass(key);
});
element.removeAttr('style').css(_.css);
}
// Default values for 'title', 'subtitle', 'caption'
function defaultWrapper(_){
switch (_){
case 'title': return {
enable: false,
text: 'Write Your Title',
class: 'h4',
css: {
width: scope.options.chart.width + 'px',
textAlign: 'center'
}
};
case 'subtitle': return {
enable: false,
text: 'Write Your Subtitle',
css: {
width: scope.options.chart.width + 'px',
textAlign: 'center'
}
};
case 'caption': return {
enable: false,
text: 'Figure 1. Write Your Caption text.',
css: {
width: scope.options.chart.width + 'px',
textAlign: 'center'
}
};
}
}
// Default values for styles
function defaultStyles(){
return {
classes: {
'with-3d-shadow': true,
'with-transitions': true,
'gallery': false
},
css: {}
};
}
/* Event Handling */
// Watching on options changing
scope.$watch('options', utils.debounce(function(newOptions){
if (!scope._config.disabled && scope._config.autorefresh) scope.api.refresh();
}, scope._config.debounce, true), true);
// Watching on data changing
scope.$watch('data', function(newData, oldData){
if (newData !== oldData && scope.chart){
if (!scope._config.disabled && scope._config.autorefresh) {
scope._config.refreshDataOnly ? scope.chart.update() : scope.api.refresh(); // if wanted to refresh data only, use chart.update method, otherwise use full refresh.
}
}
}, scope._config.deepWatchData);
// Watching on config changing
scope.$watch('config', function(newConfig, oldConfig){
if (newConfig !== oldConfig){
scope._config = angular.extend(defaultConfig, newConfig);
scope.api.refresh();
}
}, true);
//subscribe on global events
angular.forEach(scope.events, function(eventHandler, event){
scope.$on(event, function(e){
return eventHandler(e, scope);
});
});
// remove completely when directive is destroyed
element.on('$destroy', function () {
scope.api.clearElement();
});
}
};
}])
.factory('utils', function(){
return {
debounce: function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
},
deepExtend: function(dst){
var me = this;
angular.forEach(arguments, function(obj) {
if (obj !== dst) {
angular.forEach(obj, function(value, key) {
if (dst[key] && dst[key].constructor && dst[key].constructor === Object) {
me.deepExtend(dst[key], value);
} else {
dst[key] = value;
}
});
}
});
return dst;
}
};
});
})(); |
version https://git-lfs.github.com/spec/v1
oid sha256:db953ed2223a6f144e138118df03da2fd8c82aa401695064d532aec80f5a6741
size 2480
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.