<commit_before>// license see http://www.openvstorage.com/licenses/opensource/
/*global define */
define([
    'jquery', 'durandal/app', 'plugins/dialog', 'knockout',
    'ovs/shared', 'ovs/generic', 'ovs/refresher', 'ovs/api',
    '../containers/vmachine', '../containers/vpool', '../wizards/clone/index', '../wizards/snapshot/index'
], function($, app, dialog, ko, shared, generic, Refresher, api, VMachine, VPool, CloneWizard, SnapshotWizard) {
    "use strict";
    return function() {
        var self = this;

        // System
        self.shared    = shared;
        self.guard     = { authenticated: true };
        self.refresher = new Refresher();
        self.widgets   = [];

        // Data
        self.vMachineHeaders = [
            { key: 'name',         value: $.t('ovs:generic.name'),       width: 150,       colspan: undefined },
            { key: 'vpool',        value: $.t('ovs:generic.vpool'),      width: 150,       colspan: undefined },
            { key: 'vsa',          value: $.t('ovs:generic.vsa'),        width: 150,       colspan: undefined },
            { key: undefined,      value: $.t('ovs:generic.vdisks'),     width: 60,        colspan: undefined },
            { key: 'storedData',   value: $.t('ovs:generic.storeddata'), width: 110,       colspan: undefined },
            { key: 'cacheRatio',   value: $.t('ovs:generic.cache'),      width: 100,       colspan: undefined },
            { key: 'iops',         value: $.t('ovs:generic.iops'),       width: 55,        colspan: undefined },
            { key: 'readSpeed',    value: $.t('ovs:generic.readspeed'),  width: 100,       colspan: undefined },
            { key: 'writeSpeed',   value: $.t('ovs:generic.writespeed'), width: 100,       colspan: undefined },
            { key: 'failoverMode', value: $.t('ovs:generic.focstatus'),  width: undefined, colspan: undefined },
            { key: undefined,      value: $.t('ovs:generic.actions'),    width: 80,        colspan: undefined }
        ];
        self.vMachines = ko.observableArray([]);
        self.vMachineGuids =  [];

        // Variables
        self.loadVMachinesHandle = undefined;

        // Functions
        self.vpoolUrl = function(guid) {
            return '#' + self.shared.mode() + '/vpool/' + (guid.call ? guid() : guid);
        };
        self.vmachineUrl = function(guid) {
            return '#' + self.shared.mode() + '/vmachine/' + (guid.call ? guid() : guid);
        };
        self.load = function() {
            return $.Deferred(function(deferred) {
                generic.xhrAbort(self.loadVMachinesHandle);
                self.loadVMachinesHandle = api.get('vmachines')
                    .done(function(data) {
                        var i, guids = [];
                        for (i = 0; i < data.length; i += 1) {
                            guids.push(data[i].guid);
                        }
                        generic.crossFiller(
                            guids, self.vMachineGuids, self.vMachines,
                            function(guid) {
                                return new VMachine(guid);
                            }
                        );
                        deferred.resolve();
                    })
                    .fail(deferred.reject);
            }).promise();
        };
        self.loadVMachine = function(vm) {
            $.when.apply($, [
                    vm.load(),
                    vm.fetchVSAGuids(),
                    vm.fetchVPoolGuids()
                ])
                .done(function() {
                    // Merge in the VSAs
                    var i, currentGuids = [];
                    for (i = 0; i < vm.vsas().length; i += 1) {
                        currentGuids.push(vm.vsas()[i].guid());
                    }
                    generic.crossFiller(
                        vm.vsaGuids, currentGuids, vm.vsas,
                        function(guid) {
                            var vm = new VMachine(guid);
                            vm.load();
                            return vm;
                        }
                    );
                    // Merge in the vPools
                    currentGuids = [];
                    for (i = 0; i < vm.vpools().length; i += 1) {
                        currentGuids.push(vm.vpools()[i].guid());
                    }
                    generic.crossFiller(
                        vm.vPoolGuids, currentGuids, vm.vpools,
                        function(guid) {
                            var vm = new VPool(guid);
                            vm.load();
                            return vm;
                        }
                    );
                });
        };
        self.clone = function(guid) {
            var i, vms = self.vMachines();
            for (i = 0; i < vms.length; i += 1) {
                if (vms[i].guid() === guid) {
                    dialog.show(new CloneWizard({
                        modal: true,
                        machineguid: guid
                    }));
                }
            }
        };
        self.snapshot = function(guid) {
            var i, vms = self.vMachines();
            for (i = 0; i < vms.length; i += 1) {
                if (vms[i].guid() === guid) {
                    dialog.show(new SnapshotWizard({
                        modal: true,
                        machineguid: guid
                    }));
                }
            }
        };
        self.deleteVM = function(guid) {
            var i, vms = self.vMachines(), vm;
            for (i = 0; i < vms.length; i += 1) {
                if (vms[i].guid() === guid) {
                    vm = vms[i];
                }
            }
            if (vm !== undefined) {
                (function(vm) {
                    app.showMessage(
                            $.t('ovs:vmachines.suretodelete', { what: vm.name() }),
                            $.t('ovs:generic.areyousure'),
                            [$.t('ovs:generic.yes'), $.t('ovs:generic.no')]
                        )
                        .done(function(answer) {
                            if (answer === $.t('ovs:generic.yes')) {
                                self.vMachines.destroy(vm);
                                generic.alertInfo($.t('ovs:vmachines.marked'), $.t('ovs:vmachines.machinemarked', { what: vm.name() }));
                                api.del('vmachines/' + vm.guid())
                                    .then(self.shared.tasks.wait)
                                    .done(function() {
                                        generic.alertSuccess($.t('ovs:vmachines.deleted'), $.t('ovs:vmachines.machinedeleted', { what: vm.name() }));
                                    })
                                    .fail(function(error) {
                                        generic.alertSuccess($.t('ovs:generic.error'), 'Machine ' + vm.name() + ' could not be deleted: ' + error);
                                    });
                            }
                        });
                }(vm));
            }
        };

        // Durandal
        self.activate = function() {
            self.refresher.init(self.load, 5000);
            self.refresher.run();
            self.refresher.start();
        };
        self.deactivate = function() {
            var i;
            for (i = 0; i < self.widgets.length; i += 2) {
                self.widgets[i].deactivate();
            }
            self.refresher.stop();
        };
    };
});
<commit_msg>OVS-42 : Replaced old api.get call with api.post query in vMachines Overview<commit_after>// license see http://www.openvstorage.com/licenses/opensource/
/*global define */
define([
    'jquery', 'durandal/app', 'plugins/dialog', 'knockout',
    'ovs/shared', 'ovs/generic', 'ovs/refresher', 'ovs/api',
    '../containers/vmachine', '../containers/vpool', '../wizards/clone/index', '../wizards/snapshot/index'
], function($, app, dialog, ko, shared, generic, Refresher, api, VMachine, VPool, CloneWizard, SnapshotWizard) {
    "use strict";
    return function() {
        var self = this;

        // System
        self.shared    = shared;
        self.guard     = { authenticated: true };
        self.refresher = new Refresher();
        self.widgets   = [];

        // Data
        self.vMachineHeaders = [
            { key: 'name',         value: $.t('ovs:generic.name'),       width: 150,       colspan: undefined },
            { key: 'vpool',        value: $.t('ovs:generic.vpool'),      width: 150,       colspan: undefined },
            { key: 'vsa',          value: $.t('ovs:generic.vsa'),        width: 150,       colspan: undefined },
            { key: undefined,      value: $.t('ovs:generic.vdisks'),     width: 60,        colspan: undefined },
            { key: 'storedData',   value: $.t('ovs:generic.storeddata'), width: 110,       colspan: undefined },
            { key: 'cacheRatio',   value: $.t('ovs:generic.cache'),      width: 100,       colspan: undefined },
            { key: 'iops',         value: $.t('ovs:generic.iops'),       width: 55,        colspan: undefined },
            { key: 'readSpeed',    value: $.t('ovs:generic.readspeed'),  width: 100,       colspan: undefined },
            { key: 'writeSpeed',   value: $.t('ovs:generic.writespeed'), width: 100,       colspan: undefined },
            { key: 'failoverMode', value: $.t('ovs:generic.focstatus'),  width: undefined, colspan: undefined },
            { key: undefined,      value: $.t('ovs:generic.actions'),    width: 80,        colspan: undefined }
        ];
        self.vMachines = ko.observableArray([]);
        self.vMachineGuids =  [];

        // Variables
        self.loadVMachinesHandle = undefined;

        // Functions
        self.vpoolUrl = function(guid) {
            return '#' + self.shared.mode() + '/vpool/' + (guid.call ? guid() : guid);
        };
        self.vmachineUrl = function(guid) {
            return '#' + self.shared.mode() + '/vmachine/' + (guid.call ? guid() : guid);
        };
        self.load = function() {
            return $.Deferred(function(deferred) {
                generic.xhrAbort(self.loadVMachinesHandle);
                var query = {
                        query: {
                            type: 'AND',
                            items: [['is_internal', 'EQUALS', false]]
                        }
                    };
                self.loadVMachinesHandle = api.post('vmachines/filter', query)
                    .done(function(data) {
                        var i, guids = [];
                        for (i = 0; i < data.length; i += 1) {
                            guids.push(data[i].guid);
                        }
                        generic.crossFiller(
                            guids, self.vMachineGuids, self.vMachines,
                            function(guid) {
                                return new VMachine(guid);
                            }
                        );
                        deferred.resolve();
                    })
                    .fail(deferred.reject);
            }).promise();
        };
        self.loadVMachine = function(vm) {
            $.when.apply($, [
                    vm.load(),
                    vm.fetchVSAGuids(),
                    vm.fetchVPoolGuids()
                ])
                .done(function() {
                    // Merge in the VSAs
                    var i, currentGuids = [];
                    for (i = 0; i < vm.vsas().length; i += 1) {
                        currentGuids.push(vm.vsas()[i].guid());
                    }
                    generic.crossFiller(
                        vm.vsaGuids, currentGuids, vm.vsas,
                        function(guid) {
                            var vm = new VMachine(guid);
                            vm.load();
                            return vm;
                        }
                    );
                    // Merge in the vPools
                    currentGuids = [];
                    for (i = 0; i < vm.vpools().length; i += 1) {
                        currentGuids.push(vm.vpools()[i].guid());
                    }
                    generic.crossFiller(
                        vm.vPoolGuids, currentGuids, vm.vpools,
                        function(guid) {
                            var vm = new VPool(guid);
                            vm.load();
                            return vm;
                        }
                    );
                });
        };
        self.clone = function(guid) {
            var i, vms = self.vMachines();
            for (i = 0; i < vms.length; i += 1) {
                if (vms[i].guid() === guid) {
                    dialog.show(new CloneWizard({
                        modal: true,
                        machineguid: guid
                    }));
                }
            }
        };
        self.snapshot = function(guid) {
            var i, vms = self.vMachines();
            for (i = 0; i < vms.length; i += 1) {
                if (vms[i].guid() === guid) {
                    dialog.show(new SnapshotWizard({
                        modal: true,
                        machineguid: guid
                    }));
                }
            }
        };
        self.deleteVM = function(guid) {
            var i, vms = self.vMachines(), vm;
            for (i = 0; i < vms.length; i += 1) {
                if (vms[i].guid() === guid) {
                    vm = vms[i];
                }
            }
            if (vm !== undefined) {
                (function(vm) {
                    app.showMessage(
                            $.t('ovs:vmachines.suretodelete', { what: vm.name() }),
                            $.t('ovs:generic.areyousure'),
                            [$.t('ovs:generic.yes'), $.t('ovs:generic.no')]
                        )
                        .done(function(answer) {
                            if (answer === $.t('ovs:generic.yes')) {
                                self.vMachines.destroy(vm);
                                generic.alertInfo($.t('ovs:vmachines.marked'), $.t('ovs:vmachines.machinemarked', { what: vm.name() }));
                                api.del('vmachines/' + vm.guid())
                                    .then(self.shared.tasks.wait)
                                    .done(function() {
                                        generic.alertSuccess($.t('ovs:vmachines.deleted'), $.t('ovs:vmachines.machinedeleted', { what: vm.name() }));
                                    })
                                    .fail(function(error) {
                                        generic.alertSuccess($.t('ovs:generic.error'), 'Machine ' + vm.name() + ' could not be deleted: ' + error);
                                    });
                            }
                        });
                }(vm));
            }
        };

        // Durandal
        self.activate = function() {
            self.refresher.init(self.load, 5000);
            self.refresher.run();
            self.refresher.start();
        };
        self.deactivate = function() {
            var i;
            for (i = 0; i < self.widgets.length; i += 2) {
                self.widgets[i].deactivate();
            }
            self.refresher.stop();
        };
    };
});
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

/**
 * Method using a factory pattern variant to get a reducer
 * for a particular page or page style.
 *
 * For a new page - create a constant object with the
 * methods from reducerMethods which are composed to create
 * a reducer. Add to PAGE_REDUCERS.
 *
 * Each key value pair in a reducer object should be in the form
 * action type: reducer function, returning a new state object
 *
 */

import {
  filterData,
  focusNextCell,
  selectRow,
  deselectRow,
  deselectAll,
  focusCell,
  sortData,
  openBasicModal,
  closeBasicModal,
  addMasterListItems,
  addItem,
  editTheirRef,
  editComment,
  deleteRecordsById,
  refreshData,
  createAutomaticOrder,
  hideOverStocked,
  showOverStocked,
  editField,
} from './reducerMethods';

/**
 * Used for actions that should be in all pages using a data table.
 */
const BASE_TABLE_PAGE_REDUCER = {
  focusNextCell,
  focusCell,
  sortData,
};

const customerInvoice = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  editField,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  addMasterListItems,
  addItem,
  editTheirRef,
  editComment,
  deleteRecordsById,
  refreshData,
};

const customerInvoices = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  deleteRecordsById,
};

const supplierInvoice = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  closeBasicModal,
  openBasicModal,
  editTheirRef,
  editComment,
  refreshData,
  addItem,
  editField,
  deleteRecordsById,
};

const supplierRequisition = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  editTheirRef,
  editComment,
  refreshData,
  addMasterListItems,
  addItem,
  createAutomaticOrder,
  hideOverStocked,
  showOverStocked,
  editField,
  deleteRecordsById,
};

const programSupplierRequisition = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  editTheirRef,
  editComment,
  refreshData,
  addMasterListItems,
  addItem,
  createAutomaticOrder,
  hideOverStocked,
  showOverStocked,
  editField,
};

const supplierRequisitions = {
  sortData,
  filterData,
  selectRow,
  deselectRow,
  openBasicModal,
  closeBasicModal,
  refreshData,
};

const stocktakes = {
  openBasicModal,
  closeBasicModal,
  filterData,
  selectRow,
  deselectAll,
  deselectRow,
  sortData,
};

const PAGE_REDUCERS = {
  customerInvoice,
  customerInvoices,
  supplierInvoice,
  supplierRequisitions,
  supplierRequisition,
  programSupplierRequisition,
  stocktakes,
};

const getReducer = page => {
  const reducer = PAGE_REDUCERS[page];
  return (state, action) => {
    const { type } = action;
    if (!reducer[type]) return state;
    return reducer[type](state, action);
  };
};

export default getReducer;
<commit_msg>Add complete creating new record to stocktakes page reducer<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

/**
 * Method using a factory pattern variant to get a reducer
 * for a particular page or page style.
 *
 * For a new page - create a constant object with the
 * methods from reducerMethods which are composed to create
 * a reducer. Add to PAGE_REDUCERS.
 *
 * Each key value pair in a reducer object should be in the form
 * action type: reducer function, returning a new state object
 *
 */

import {
  filterData,
  focusNextCell,
  selectRow,
  deselectRow,
  deselectAll,
  focusCell,
  sortData,
  openBasicModal,
  closeBasicModal,
  addMasterListItems,
  addItem,
  editTheirRef,
  editComment,
  deleteRecordsById,
  refreshData,
  createAutomaticOrder,
  hideOverStocked,
  showOverStocked,
  editField,
} from './reducerMethods';

/**
 * Used for actions that should be in all pages using a data table.
 */
const BASE_TABLE_PAGE_REDUCER = {
  focusNextCell,
  focusCell,
  sortData,
};

const customerInvoice = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  editField,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  addMasterListItems,
  addItem,
  editTheirRef,
  editComment,
  deleteRecordsById,
  refreshData,
};

const customerInvoices = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  deleteRecordsById,
};

const supplierInvoice = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  closeBasicModal,
  openBasicModal,
  editTheirRef,
  editComment,
  refreshData,
  addItem,
  editField,
  deleteRecordsById,
};

const supplierRequisition = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  editTheirRef,
  editComment,
  refreshData,
  addMasterListItems,
  addItem,
  createAutomaticOrder,
  hideOverStocked,
  showOverStocked,
  editField,
  deleteRecordsById,
};

const programSupplierRequisition = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  editTheirRef,
  editComment,
  refreshData,
  addMasterListItems,
  addItem,
  createAutomaticOrder,
  hideOverStocked,
  showOverStocked,
  editField,
};

const supplierRequisitions = {
  sortData,
  filterData,
  selectRow,
  deselectRow,
  openBasicModal,
  closeBasicModal,
  refreshData,
};

const stocktakes = {
  openBasicModal,
  closeBasicModal,
  filterData,
  selectRow,
  deselectAll,
  deselectRow,
  sortData,
  completeCreatingNewRecord,
};

const PAGE_REDUCERS = {
  customerInvoice,
  customerInvoices,
  supplierInvoice,
  supplierRequisitions,
  supplierRequisition,
  programSupplierRequisition,
  stocktakes,
};

const getReducer = page => {
  const reducer = PAGE_REDUCERS[page];
  return (state, action) => {
    const { type } = action;
    if (!reducer[type]) return state;
    return reducer[type](state, action);
  };
};

export default getReducer;
<|endoftext|>


<commit_before>//Keycloak methods start
function logKeycloak() {
    document.getElementById('resultsKeycloak').innerText = '';

    Array.prototype.forEach.call(arguments, function (msg) {
        if (msg instanceof Error) {
            msg = "Error: " + msg.message;
        }
        else if (typeof msg !== 'string') {
            msg = JSON.stringify(msg, null, 2);
        }
        document.getElementById('resultsKeycloak').innerHTML += msg + '\r\n';
    });
}

var kcmgr = makeRequest('GET', 'appsettings.json')
    .then(function (data) {
        var parsedData = JSON.parse(data);
        var config = {
            authority: parsedData.keyCloakBaseUri,
            client_id: parsedData.keyCloakClientId,
            redirect_uri: parsedData.serverurls,
            response_type: "id_token token",
            scope: "openid profile",
            post_logout_redirect_uri: parsedData.serverurls + "/index.html"
        };
        var kcmgr = new Oidc.UserManager(config);
        return kcmgr;
    })
    .catch(function (err) {
        console.error('Error: ', err.statusText);
    });

kcmgr.then(
    kcmgr => kcmgr.getUser().then(function (user) {
        if (user) {
            logKeycloak("User logged in with Keycloak", user.profile);
        }
        else {
            logKeycloak("User not logged in with Keycloak");
        }
    })
);

function loginKeycloak() {
    kcmgr.then(
        kcmgr => kcmgr.signinRedirect()
    );
}

var invoiceApi = makeRequest('GET', 'appsettings.json')
    .then(function (data) {
        var parsedData = JSON.parse(data);
        var invoiceApi = parsedData.invoiceApiBaseUri;
        return invoiceApi;
    })
    .catch(function (err) {
        console.error('Error: ', err.statusText);
    });

function kcapi() {
    path = "/invoice";
    kcmgr.then(
        kcmgr => kcmgr.getUser().then(function (user) {
            var url = productApi.then(function (api) {
                var xhr = new XMLHttpRequest();
                xhr.open("GET", kcapi + path);
                xhr.onload = function () {
                    log(xhr.status, JSON.parse(xhr.responseText));
                };
                xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
                xhr.send();
            });
        })
    );
}

function logoutKeycloak() {
    kcmgr.then(
        kcmgr => kcmgr.signoutRedirect()
    );
}
//Keycloak methods end

<commit_msg>added callback url for keycloak<commit_after>//Keycloak methods start
function logKeycloak() {
    document.getElementById('resultsKeycloak').innerText = '';

    Array.prototype.forEach.call(arguments, function (msg) {
        if (msg instanceof Error) {
            msg = "Error: " + msg.message;
        }
        else if (typeof msg !== 'string') {
            msg = JSON.stringify(msg, null, 2);
        }
        document.getElementById('resultsKeycloak').innerHTML += msg + '\r\n';
    });
}

var kcmgr = makeRequest('GET', 'appsettings.json')
    .then(function (data) {
        var parsedData = JSON.parse(data);
        var config = {
            authority: parsedData.keyCloakBaseUri,
            client_id: parsedData.keyCloakClientId,
            redirect_uri: parsedData.serverurls + "/callback.html",
            response_type: "id_token token",
            scope: "openid profile",
            post_logout_redirect_uri: parsedData.serverurls + "/index.html"
        };
        var kcmgr = new Oidc.UserManager(config);
        return kcmgr;
    })
    .catch(function (err) {
        console.error('Error: ', err.statusText);
    });

kcmgr.then(
    kcmgr => kcmgr.getUser().then(function (user) {
        if (user) {
            logKeycloak("User logged in with Keycloak", user.profile);
        }
        else {
            logKeycloak("User not logged in with Keycloak");
        }
    })
);

function loginKeycloak() {
    kcmgr.then(
        kcmgr => kcmgr.signinRedirect()
    );
}

var invoiceApi = makeRequest('GET', 'appsettings.json')
    .then(function (data) {
        var parsedData = JSON.parse(data);
        var invoiceApi = parsedData.invoiceApiBaseUri;
        return invoiceApi;
    })
    .catch(function (err) {
        console.error('Error: ', err.statusText);
    });

function kcapi() {
    path = "/invoice";
    kcmgr.then(
        kcmgr => kcmgr.getUser().then(function (user) {
            var url = invoiceApi.then(function (kcapi) {
                var xhr = new XMLHttpRequest();
                xhr.open("GET", kcapi + path);
                xhr.onload = function () {
                    log(xhr.status, JSON.parse(xhr.responseText));
                };
                xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
                xhr.send();
            });
        })
    );
}

function logoutKeycloak() {
    kcmgr.then(
        kcmgr => kcmgr.signoutRedirect()
    );
}
//Keycloak methods end

<|endoftext|>


<commit_before>defineSuite([
    'Core/Resource',
    'Core/DefaultProxy',
    'Core/Request',
    'ThirdParty/when'
], function(
    Resource,
    DefaultProxy,
    Request,
    when) {
    'use strict';

    it('Constructor sets correct properties', function() {
        var proxy = new DefaultProxy('/proxy/');
        var request = new Request();
        function retryFunc() {
        }

        var resource = new Resource({
            url: 'http://test.com/tileset',
            queryParameters: {
                key1: 'value1',
                key2: 'value2'
            },
            templateValues: {
                key3: 'value3',
                key4: 'value4'
            },
            headers: {
                Accept: 'application/test-type'
            },
            proxy: proxy,
            retryCallback: retryFunc,
            retryAttempts: 4,
            request: request
        });

        expect(resource.getUrlComponent(false, false)).toEqual('http://test.com/tileset');
        expect(resource.getUrlComponent(true, false)).toEqual('http://test.com/tileset?key1=value1&key2=value2');
        expect(resource.getUrlComponent(false, true)).toEqual(proxy.getURL('http://test.com/tileset'));
        expect(resource.getUrlComponent(true, true)).toEqual(proxy.getURL('http://test.com/tileset?key1=value1&key2=value2'));
        expect(resource.url).toEqual(proxy.getURL('http://test.com/tileset?key1=value1&key2=value2'));
        expect(resource.queryParameters).toEqual({
            key1: 'value1',
            key2: 'value2'
        });
        expect(resource.templateValues).toEqual({
            key3: 'value3',
            key4: 'value4'
        });
        expect(resource.headers).toEqual({
            Accept: 'application/test-type'
        });
        expect(resource.proxy).toBe(proxy);
        expect(resource.retryCallback).toBe(retryFunc);
        expect(resource.retryAttempts).toEqual(4);
        expect(resource._retryCount).toEqual(0);
        expect(resource.request).toBe(request);
    });

    it('Constructor sets correct properties', function() {
        var url = 'http://invalid.domain.com/tileset'
        var resource = new Resource(url);
        expect(resource.url).toEqual(url);
        expect(resource.queryParameters).toEqual({});
        expect(resource.templateValues).toEqual({});
        expect(resource.headers).toEqual({});
        expect(resource.proxy).toBeUndefined();
        expect(resource.retryCallback).toBeUndefined();
        expect(resource.retryAttempts).toEqual(0);
        expect(resource.request).toBeDefined();
    });

    it('appendForwardSlash appends a /', function() {
        var resource = new Resource({
            url: 'http://test.com/tileset'
        });
        expect(resource.url).toEqual('http://test.com/tileset');
        resource.appendForwardSlash();
        expect(resource.url).toEqual('http://test.com/tileset/');
    });

    it('Setting a url with a query string sets queryParameters correctly', function() {
        var resource = new Resource({
            url: 'http://test.com/tileset?foo=bar&baz=foo'
        });
        expect(resource.getUrlComponent()).toEqual('http://test.com/tileset');
        expect(resource.getUrlComponent(true)).toEqual('http://test.com/tileset?foo=bar&baz=foo');
        expect(resource.queryParameters).toEqual({
            foo: 'bar',
            baz: 'foo'
        });
    });

    it('createIfNeeded returns undefined, if parameter is undefined', function() {
        expect(Resource.createIfNeeded()).toBeUndefined();
    });

    it('createIfNeeded returns Resource, if parameter is a Resource', function() {
        var resource = new Resource({
            url: 'http://test.com/tileset'
        });
        expect(Resource.createIfNeeded(resource)).toEqual(resource);
    });

    it('createIfNeeded returns Resource, if parameter is a String', function() {
        var resource = Resource.createIfNeeded('http://test.com/tileset');
        expect(resource.url).toEqual('http://test.com/tileset');
    });

    it('templateValues are respected', function() {
        var resource = new Resource({
            url: 'http://test.com/tileset/{foo}/{bar}',
            templateValues: {
                foo: 'test1',
                bar: 'test2'
            }
        });

        expect(resource.url).toEqual('http://test.com/tileset/test1/test2');
    });

    it('getDerivedResource sets correct properties', function() {
        var proxy = new DefaultProxy('/proxy/');
        var request = new Request();
        function retryFunc() {
        }

        var parent = new Resource({
            url: 'http://test.com/tileset?key=value',
            queryParameters: {
                foo: 'bar'
            },
            templateValues: {
                key5: 'value5',
                key6: 'value6'
            }
        });
        parent.appendForwardSlash();

        var resource = parent.getDerivedResource({
            url: 'tileset.json',
            queryParameters: {
                key1: 'value1',
                key2: 'value2'
            },
            templateValues: {
                key3: 'value3',
                key4: 'value4'
            },
            headers: {
                Accept: 'application/test-type'
            },
            proxy: proxy,
            retryCallback: retryFunc,
            retryAttempts: 4,
            request: request
        });

        expect(resource.getUrlComponent(false, false)).toEqual('http://test.com/tileset/tileset.json');
        expect(resource.getUrlComponent(true, false)).toEqual('http://test.com/tileset/tileset.json?key1=value1&key2=value2&foo=bar&key=value');
        expect(resource.getUrlComponent(false, true)).toEqual(proxy.getURL('http://test.com/tileset/tileset.json'));
        expect(resource.getUrlComponent(true, true)).toEqual(proxy.getURL('http://test.com/tileset/tileset.json?key1=value1&key2=value2&foo=bar&key=value'));
        expect(resource.url).toEqual(proxy.getURL('http://test.com/tileset/tileset.json?key1=value1&key2=value2&foo=bar&key=value'));
        expect(resource.queryParameters).toEqual({
            foo: 'bar',
            key: 'value',
            key1: 'value1',
            key2: 'value2'
        });
        expect(resource.templateValues).toEqual({
            key5: 'value5',
            key6: 'value6',
            key3: 'value3',
            key4: 'value4'
        });
        expect(resource.headers).toEqual({
            Accept: 'application/test-type'
        });
        expect(resource.proxy).toBe(proxy);
        expect(resource.retryCallback).toBe(retryFunc);
        expect(resource.retryAttempts).toEqual(4);
        expect(resource._retryCount).toEqual(0);
        expect(resource.request).toBe(request);
    });

    it('getDerivedResource works with directory parent resource', function() {
        var parent = new Resource({
            url: 'http://test.com/tileset/'
        });

        expect(parent.url).toEqual('http://test.com/tileset/');

        var resource = parent.getDerivedResource({
            url: 'tileset.json'
        });

        expect(resource.url).toEqual('http://test.com/tileset/tileset.json');
    });

    it('getDerivedResource works with file parent resource', function() {
        var parent = new Resource({
            url: 'http://test.com/tileset/tileset.json'
        });

        expect(parent.url).toEqual('http://test.com/tileset/tileset.json');

        var resource = parent.getDerivedResource({
            url: '0/0/0.b3dm'
        });

        expect(resource.url).toEqual('http://test.com/tileset/0/0/0.b3dm');
    });

    it('getDerivedResource works with only template values', function() {
        var parent = new Resource({
            url: 'http://test.com/terrain/{z}/{x}/{y}.terrain'
        });

        expect(parent.url).toEqual('http://test.com/terrain/{z}/{x}/{y}.terrain');

        var resource = parent.getDerivedResource({
            templateValues: {
                x: 1,
                y: 2,
                z: 0
            }
        });

        expect(resource.url).toEqual('http://test.com/terrain/0/1/2.terrain');
    });

    it('getDerivedResource works with only query parameters', function() {
        var parent = new Resource({
            url: 'http://test.com/terrain'
        });

        expect(parent.url).toEqual('http://test.com/terrain');

        var resource = parent.getDerivedResource({
            queryParameters: {
                x: 1,
                y: 2,
                z: 0
            }
        });

        expect(resource.url).toEqual('http://test.com/terrain?x=1&y=2&z=0');
    });

    it('addQueryParameters with useAsDefault set to true', function() {
        var resource = new Resource({
            url: 'http://test.com/terrain',
            queryParameters: {
                x: 1,
                y: 2
            }
        });

        expect(resource.queryParameters).toEqual({
            x: 1,
            y: 2
        });

        resource.addQueryParameters({
            x: 3,
            y: 4,
            z: 0
        }, true);

        expect(resource.queryParameters).toEqual({
            x: 1,
            y: 2,
            z: 0
        });
    });

    it('addQueryParameters with useAsDefault set to false', function() {
        var resource = new Resource({
            url: 'http://test.com/terrain',
            queryParameters: {
                x: 1,
                y: 2
            }
        });

        expect(resource.queryParameters).toEqual({
            x: 1,
            y: 2
        });

        resource.addQueryParameters({
            x: 3,
            y: 4,
            z: 0
        }, false);

        expect(resource.queryParameters).toEqual({
            x: 3,
            y: 4,
            z: 0
        });
    });

    it('addTemplateValues with useAsDefault set to true', function() {
        var resource = new Resource({
            url: 'http://test.com/terrain/{z}/{x}/{y}.terrain',
            templateValues: {
                x: 1,
                y: 2,
                map: 'my map'
            }
        });

        expect(resource.templateValues).toEqual({
            x: 1,
            y: 2,
            map: 'my map'
        });

        resource.addTemplateValues({
            x: 3,
            y: 4,
            z: 0,
            style: 'my style'
        }, true);

        expect(resource.templateValues).toEqual({
            x: 1,
            y: 2,
            map: 'my map',
            z: 0,
            style: 'my style'
        });
    });

    it('addTemplateValues with useAsDefault set to false', function() {
        var resource = new Resource({
            url: 'http://test.com/terrain/{z}/{x}/{y}.terrain',
            templateValues: {
                x: 1,
                y: 2,
                map: 'my map'
            }
        });

        expect(resource.templateValues).toEqual({
            x: 1,
            y: 2,
            map: 'my map'
        });

        resource.addTemplateValues({
            x: 3,
            y: 4,
            z: 0,
            style: 'my style'
        }, false);

        expect(resource.templateValues).toEqual({
            x: 3,
            y: 4,
            map: 'my map',
            z: 0,
            style: 'my style'
        });
    });

    it('retryOnFail doesn\'t exceed retryAttempts', function() {
        var cb = jasmine.createSpy('retry').and.returnValue(true);
        var resource = new Resource({
            url: 'http://test.com/terrain',
            retryCallback: cb,
            retryAttempts: 3
        });

        var promises = [];
        for (var i=0;i<6;++i) {
            promises.push(resource.retryOnError());
        }

        when.all(promises)
            .then(function(result) {
                expect(result).toEqual([true, true, true, false, false, false]);
                expect(cb.calls.count()).toEqual(3);
                expect(resource._retryCount).toEqual(3);
            });
    });

    it('retryOnFail returns value from callback', function() {
        var result = true;
        var cb = jasmine.createSpy('retry').and.callFake(function() {
            result = !result;
            return result;
        });

        var resource = new Resource({
            url: 'http://test.com/terrain',
            retryCallback: cb,
            retryAttempts: 4
        });

        var promises = [];
        for (var i=0;i<6;++i) {
            promises.push(resource.retryOnError());
        }

        when.all(promises)
            .then(function(result) {
                expect(result).toEqual([false, true, false, true, false, false]);
                expect(cb.calls.count()).toEqual(4);
                expect(resource._retryCount).toEqual(4);
            });
    });

    it('isDataUri returns correct values', function() {
        var dataResource = new Resource({
            url: 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3'
        });

        expect(dataResource.isDataUri).toBe(true);

        var resource = new Resource({
            url: 'http://invalid.uri/tileset'
        });

        expect(resource.isDataUri).toBe(false);
    });

    it('isBlobUri returns correct values', function() {
        var dataResource = new Resource({
            url: 'blob:d3958f5c-0777-0845-9dcf-2cb28783acaf'
        });

        expect(dataResource.isBlobUri).toBe(true);

        var resource = new Resource({
            url: 'http://invalid.uri/tileset'
        });

        expect(resource.isBlobUri).toBe(false);
    });

    it('post calls with correct method', function() {
        var expectedUrl = 'http://test.com/endpoint';
        var expectedResponseType = 'json';
        var expectedData = {
            stuff: 'myStuff'
        };
        var expectedHeaders = {
            'X-My-Header': 'My-Value'
        };
        var expectedResult = {
            status: 'success'
        };
        var expectedMimeType = 'application/test-data';
        var expectedResource = new Resource({
            url: expectedUrl,
            headers: expectedHeaders
        });

        spyOn(Resource._Implementations, 'loadWithXhr').and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType, resource) {
            expect(url).toEqual(expectedUrl);
            expect(responseType).toEqual(expectedResponseType);
            expect(method).toEqual('POST');
            expect(data).toEqual(expectedData);
            expect(headers['X-My-Header']).toEqual('My-Value');
            expect(headers['X-My-Other-Header']).toEqual('My-Other-Value');
            expect(overrideMimeType).toBe(expectedMimeType);
            expect(resource).toBe(expectedResource);
            deferred.resolve(expectedResult);
        });

        return expectedResource.post(expectedData, {
            responseType: expectedResponseType,
            headers: {
                'X-My-Other-Header': 'My-Other-Value'
            },
            overrideMimeType: expectedMimeType
        })
            .then(function(result) {
                expect(result).toEqual(expectedResult);
            });
    });

    it('static post calls with correct method', function() {
        var expectedUrl = 'http://test.com/endpoint';
        var expectedResponseType = 'json';
        var expectedData = {
            stuff: 'myStuff'
        };
        var expectedHeaders = {
            'X-My-Header': 'My-Value'
        };
        var expectedResult = {
            status: 'success'
        };
        var expectedMimeType = 'application/test-data';

        spyOn(Resource._Implementations, 'loadWithXhr').and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType, resource) {
            expect(url).toEqual(expectedUrl);
            expect(responseType).toEqual(expectedResponseType);
            expect(method).toEqual('POST');
            expect(data).toEqual(expectedData);
            expect(headers).toEqual(expectedHeaders);
            expect(overrideMimeType).toBe(expectedMimeType);
            expect(resource).toBeDefined();
            deferred.resolve(expectedResult);
        });

        return Resource.post(expectedUrl, expectedData, {
            responseType: expectedResponseType,
            headers: expectedHeaders,
            overrideMimeType: expectedMimeType
        })
            .then(function(result) {
                expect(result).toEqual(expectedResult);
            });
    });
});
<commit_msg>eslint fix.<commit_after>defineSuite([
    'Core/Resource',
    'Core/DefaultProxy',
    'Core/Request',
    'ThirdParty/when'
], function(
    Resource,
    DefaultProxy,
    Request,
    when) {
    'use strict';

    it('Constructor sets correct properties', function() {
        var proxy = new DefaultProxy('/proxy/');
        var request = new Request();
        function retryFunc() {
        }

        var resource = new Resource({
            url: 'http://test.com/tileset',
            queryParameters: {
                key1: 'value1',
                key2: 'value2'
            },
            templateValues: {
                key3: 'value3',
                key4: 'value4'
            },
            headers: {
                Accept: 'application/test-type'
            },
            proxy: proxy,
            retryCallback: retryFunc,
            retryAttempts: 4,
            request: request
        });

        expect(resource.getUrlComponent(false, false)).toEqual('http://test.com/tileset');
        expect(resource.getUrlComponent(true, false)).toEqual('http://test.com/tileset?key1=value1&key2=value2');
        expect(resource.getUrlComponent(false, true)).toEqual(proxy.getURL('http://test.com/tileset'));
        expect(resource.getUrlComponent(true, true)).toEqual(proxy.getURL('http://test.com/tileset?key1=value1&key2=value2'));
        expect(resource.url).toEqual(proxy.getURL('http://test.com/tileset?key1=value1&key2=value2'));
        expect(resource.queryParameters).toEqual({
            key1: 'value1',
            key2: 'value2'
        });
        expect(resource.templateValues).toEqual({
            key3: 'value3',
            key4: 'value4'
        });
        expect(resource.headers).toEqual({
            Accept: 'application/test-type'
        });
        expect(resource.proxy).toBe(proxy);
        expect(resource.retryCallback).toBe(retryFunc);
        expect(resource.retryAttempts).toEqual(4);
        expect(resource._retryCount).toEqual(0);
        expect(resource.request).toBe(request);
    });

    it('Constructor sets correct properties', function() {
        var url = 'http://invalid.domain.com/tileset';
        var resource = new Resource(url);
        expect(resource.url).toEqual(url);
        expect(resource.queryParameters).toEqual({});
        expect(resource.templateValues).toEqual({});
        expect(resource.headers).toEqual({});
        expect(resource.proxy).toBeUndefined();
        expect(resource.retryCallback).toBeUndefined();
        expect(resource.retryAttempts).toEqual(0);
        expect(resource.request).toBeDefined();
    });

    it('appendForwardSlash appends a /', function() {
        var resource = new Resource({
            url: 'http://test.com/tileset'
        });
        expect(resource.url).toEqual('http://test.com/tileset');
        resource.appendForwardSlash();
        expect(resource.url).toEqual('http://test.com/tileset/');
    });

    it('Setting a url with a query string sets queryParameters correctly', function() {
        var resource = new Resource({
            url: 'http://test.com/tileset?foo=bar&baz=foo'
        });
        expect(resource.getUrlComponent()).toEqual('http://test.com/tileset');
        expect(resource.getUrlComponent(true)).toEqual('http://test.com/tileset?foo=bar&baz=foo');
        expect(resource.queryParameters).toEqual({
            foo: 'bar',
            baz: 'foo'
        });
    });

    it('createIfNeeded returns undefined, if parameter is undefined', function() {
        expect(Resource.createIfNeeded()).toBeUndefined();
    });

    it('createIfNeeded returns Resource, if parameter is a Resource', function() {
        var resource = new Resource({
            url: 'http://test.com/tileset'
        });
        expect(Resource.createIfNeeded(resource)).toEqual(resource);
    });

    it('createIfNeeded returns Resource, if parameter is a String', function() {
        var resource = Resource.createIfNeeded('http://test.com/tileset');
        expect(resource.url).toEqual('http://test.com/tileset');
    });

    it('templateValues are respected', function() {
        var resource = new Resource({
            url: 'http://test.com/tileset/{foo}/{bar}',
            templateValues: {
                foo: 'test1',
                bar: 'test2'
            }
        });

        expect(resource.url).toEqual('http://test.com/tileset/test1/test2');
    });

    it('getDerivedResource sets correct properties', function() {
        var proxy = new DefaultProxy('/proxy/');
        var request = new Request();
        function retryFunc() {
        }

        var parent = new Resource({
            url: 'http://test.com/tileset?key=value',
            queryParameters: {
                foo: 'bar'
            },
            templateValues: {
                key5: 'value5',
                key6: 'value6'
            }
        });
        parent.appendForwardSlash();

        var resource = parent.getDerivedResource({
            url: 'tileset.json',
            queryParameters: {
                key1: 'value1',
                key2: 'value2'
            },
            templateValues: {
                key3: 'value3',
                key4: 'value4'
            },
            headers: {
                Accept: 'application/test-type'
            },
            proxy: proxy,
            retryCallback: retryFunc,
            retryAttempts: 4,
            request: request
        });

        expect(resource.getUrlComponent(false, false)).toEqual('http://test.com/tileset/tileset.json');
        expect(resource.getUrlComponent(true, false)).toEqual('http://test.com/tileset/tileset.json?key1=value1&key2=value2&foo=bar&key=value');
        expect(resource.getUrlComponent(false, true)).toEqual(proxy.getURL('http://test.com/tileset/tileset.json'));
        expect(resource.getUrlComponent(true, true)).toEqual(proxy.getURL('http://test.com/tileset/tileset.json?key1=value1&key2=value2&foo=bar&key=value'));
        expect(resource.url).toEqual(proxy.getURL('http://test.com/tileset/tileset.json?key1=value1&key2=value2&foo=bar&key=value'));
        expect(resource.queryParameters).toEqual({
            foo: 'bar',
            key: 'value',
            key1: 'value1',
            key2: 'value2'
        });
        expect(resource.templateValues).toEqual({
            key5: 'value5',
            key6: 'value6',
            key3: 'value3',
            key4: 'value4'
        });
        expect(resource.headers).toEqual({
            Accept: 'application/test-type'
        });
        expect(resource.proxy).toBe(proxy);
        expect(resource.retryCallback).toBe(retryFunc);
        expect(resource.retryAttempts).toEqual(4);
        expect(resource._retryCount).toEqual(0);
        expect(resource.request).toBe(request);
    });

    it('getDerivedResource works with directory parent resource', function() {
        var parent = new Resource({
            url: 'http://test.com/tileset/'
        });

        expect(parent.url).toEqual('http://test.com/tileset/');

        var resource = parent.getDerivedResource({
            url: 'tileset.json'
        });

        expect(resource.url).toEqual('http://test.com/tileset/tileset.json');
    });

    it('getDerivedResource works with file parent resource', function() {
        var parent = new Resource({
            url: 'http://test.com/tileset/tileset.json'
        });

        expect(parent.url).toEqual('http://test.com/tileset/tileset.json');

        var resource = parent.getDerivedResource({
            url: '0/0/0.b3dm'
        });

        expect(resource.url).toEqual('http://test.com/tileset/0/0/0.b3dm');
    });

    it('getDerivedResource works with only template values', function() {
        var parent = new Resource({
            url: 'http://test.com/terrain/{z}/{x}/{y}.terrain'
        });

        expect(parent.url).toEqual('http://test.com/terrain/{z}/{x}/{y}.terrain');

        var resource = parent.getDerivedResource({
            templateValues: {
                x: 1,
                y: 2,
                z: 0
            }
        });

        expect(resource.url).toEqual('http://test.com/terrain/0/1/2.terrain');
    });

    it('getDerivedResource works with only query parameters', function() {
        var parent = new Resource({
            url: 'http://test.com/terrain'
        });

        expect(parent.url).toEqual('http://test.com/terrain');

        var resource = parent.getDerivedResource({
            queryParameters: {
                x: 1,
                y: 2,
                z: 0
            }
        });

        expect(resource.url).toEqual('http://test.com/terrain?x=1&y=2&z=0');
    });

    it('addQueryParameters with useAsDefault set to true', function() {
        var resource = new Resource({
            url: 'http://test.com/terrain',
            queryParameters: {
                x: 1,
                y: 2
            }
        });

        expect(resource.queryParameters).toEqual({
            x: 1,
            y: 2
        });

        resource.addQueryParameters({
            x: 3,
            y: 4,
            z: 0
        }, true);

        expect(resource.queryParameters).toEqual({
            x: 1,
            y: 2,
            z: 0
        });
    });

    it('addQueryParameters with useAsDefault set to false', function() {
        var resource = new Resource({
            url: 'http://test.com/terrain',
            queryParameters: {
                x: 1,
                y: 2
            }
        });

        expect(resource.queryParameters).toEqual({
            x: 1,
            y: 2
        });

        resource.addQueryParameters({
            x: 3,
            y: 4,
            z: 0
        }, false);

        expect(resource.queryParameters).toEqual({
            x: 3,
            y: 4,
            z: 0
        });
    });

    it('addTemplateValues with useAsDefault set to true', function() {
        var resource = new Resource({
            url: 'http://test.com/terrain/{z}/{x}/{y}.terrain',
            templateValues: {
                x: 1,
                y: 2,
                map: 'my map'
            }
        });

        expect(resource.templateValues).toEqual({
            x: 1,
            y: 2,
            map: 'my map'
        });

        resource.addTemplateValues({
            x: 3,
            y: 4,
            z: 0,
            style: 'my style'
        }, true);

        expect(resource.templateValues).toEqual({
            x: 1,
            y: 2,
            map: 'my map',
            z: 0,
            style: 'my style'
        });
    });

    it('addTemplateValues with useAsDefault set to false', function() {
        var resource = new Resource({
            url: 'http://test.com/terrain/{z}/{x}/{y}.terrain',
            templateValues: {
                x: 1,
                y: 2,
                map: 'my map'
            }
        });

        expect(resource.templateValues).toEqual({
            x: 1,
            y: 2,
            map: 'my map'
        });

        resource.addTemplateValues({
            x: 3,
            y: 4,
            z: 0,
            style: 'my style'
        }, false);

        expect(resource.templateValues).toEqual({
            x: 3,
            y: 4,
            map: 'my map',
            z: 0,
            style: 'my style'
        });
    });

    it('retryOnFail doesn\'t exceed retryAttempts', function() {
        var cb = jasmine.createSpy('retry').and.returnValue(true);
        var resource = new Resource({
            url: 'http://test.com/terrain',
            retryCallback: cb,
            retryAttempts: 3
        });

        var promises = [];
        for (var i=0;i<6;++i) {
            promises.push(resource.retryOnError());
        }

        when.all(promises)
            .then(function(result) {
                expect(result).toEqual([true, true, true, false, false, false]);
                expect(cb.calls.count()).toEqual(3);
                expect(resource._retryCount).toEqual(3);
            });
    });

    it('retryOnFail returns value from callback', function() {
        var result = true;
        var cb = jasmine.createSpy('retry').and.callFake(function() {
            result = !result;
            return result;
        });

        var resource = new Resource({
            url: 'http://test.com/terrain',
            retryCallback: cb,
            retryAttempts: 4
        });

        var promises = [];
        for (var i=0;i<6;++i) {
            promises.push(resource.retryOnError());
        }

        when.all(promises)
            .then(function(result) {
                expect(result).toEqual([false, true, false, true, false, false]);
                expect(cb.calls.count()).toEqual(4);
                expect(resource._retryCount).toEqual(4);
            });
    });

    it('isDataUri returns correct values', function() {
        var dataResource = new Resource({
            url: 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3'
        });

        expect(dataResource.isDataUri).toBe(true);

        var resource = new Resource({
            url: 'http://invalid.uri/tileset'
        });

        expect(resource.isDataUri).toBe(false);
    });

    it('isBlobUri returns correct values', function() {
        var dataResource = new Resource({
            url: 'blob:d3958f5c-0777-0845-9dcf-2cb28783acaf'
        });

        expect(dataResource.isBlobUri).toBe(true);

        var resource = new Resource({
            url: 'http://invalid.uri/tileset'
        });

        expect(resource.isBlobUri).toBe(false);
    });

    it('post calls with correct method', function() {
        var expectedUrl = 'http://test.com/endpoint';
        var expectedResponseType = 'json';
        var expectedData = {
            stuff: 'myStuff'
        };
        var expectedHeaders = {
            'X-My-Header': 'My-Value'
        };
        var expectedResult = {
            status: 'success'
        };
        var expectedMimeType = 'application/test-data';
        var expectedResource = new Resource({
            url: expectedUrl,
            headers: expectedHeaders
        });

        spyOn(Resource._Implementations, 'loadWithXhr').and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType, resource) {
            expect(url).toEqual(expectedUrl);
            expect(responseType).toEqual(expectedResponseType);
            expect(method).toEqual('POST');
            expect(data).toEqual(expectedData);
            expect(headers['X-My-Header']).toEqual('My-Value');
            expect(headers['X-My-Other-Header']).toEqual('My-Other-Value');
            expect(overrideMimeType).toBe(expectedMimeType);
            expect(resource).toBe(expectedResource);
            deferred.resolve(expectedResult);
        });

        return expectedResource.post(expectedData, {
            responseType: expectedResponseType,
            headers: {
                'X-My-Other-Header': 'My-Other-Value'
            },
            overrideMimeType: expectedMimeType
        })
            .then(function(result) {
                expect(result).toEqual(expectedResult);
            });
    });

    it('static post calls with correct method', function() {
        var expectedUrl = 'http://test.com/endpoint';
        var expectedResponseType = 'json';
        var expectedData = {
            stuff: 'myStuff'
        };
        var expectedHeaders = {
            'X-My-Header': 'My-Value'
        };
        var expectedResult = {
            status: 'success'
        };
        var expectedMimeType = 'application/test-data';

        spyOn(Resource._Implementations, 'loadWithXhr').and.callFake(function(url, responseType, method, data, headers, deferred, overrideMimeType, resource) {
            expect(url).toEqual(expectedUrl);
            expect(responseType).toEqual(expectedResponseType);
            expect(method).toEqual('POST');
            expect(data).toEqual(expectedData);
            expect(headers).toEqual(expectedHeaders);
            expect(overrideMimeType).toBe(expectedMimeType);
            expect(resource).toBeDefined();
            deferred.resolve(expectedResult);
        });

        return Resource.post(expectedUrl, expectedData, {
            responseType: expectedResponseType,
            headers: expectedHeaders,
            overrideMimeType: expectedMimeType
        })
            .then(function(result) {
                expect(result).toEqual(expectedResult);
            });
    });
});
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const keys = require("../core/key");
const CustomXUL = require("../core/custom");

const { Windows } = require("../util/windows");
const { Overlays } = require("../core/overlay");

var _ = require("sdk/l10n").get;
const extensionPrefs = require("sdk/simple-prefs");

const GROUPS = {
		"Application": ["key_quitApplication", "key_openHelpMac", "key_openHelp", "key_preferencesCmdMac", "key_hideThisAppCmdMac", "key_hideOtherAppsCmdMac"],
        "Navigation": ["goBackKb", "goBackKb2", "goForwardKb", "goForwardKb2", "goHome", "openFileKb", "key_reload", "key_reload2", "key_forceReload", /*"Ctrl+F5", Ctrl+Shift+R,*/ "key_stop", "key_stop_mac", "focusURLBar", "focusURLBar2"],

        "CurrentPage": [ /*"End", "F6", "Shift+F6",*/ "goHome", "key_viewInfo", "key_viewSource", "printKb", "key_savePage", "key_fullZoomEnlarge", "key_fullZoomReduce", "key_fullZoomReset", "key_fullScreen", "key_fullScreen_old", "key_minimizeWindow", "key_toggleMute","key_switchTextDirection"],

        "Editing": ["key_copy", "key_cut", "key_delete", "key_paste", "key_redo", "key_selectAll", "key_undo"],

        "Search": ["key_find", "key_findAgain", "key_findPrevious", "key_search", "key_search2", "key_findSelection"],

        "WindowsTabs": ["key_close", "key_closeWindow", "key_closeOther", "key_newNavigatorTab", "key_newNavigator", "key_undoCloseTab", "key_undoCloseWindow", "key_selectTab1", "key_selectTab2", "key_selectTab3", "key_selectTab4", "key_selectTab5", "key_selectTab6", "key_selectTab7", "key_selectTab8", "key_selectLastTab", "key_tabview", "key_nextTabGroup", "key_previousTabGroup", "key_prevTab", "key_nextTab","key_showAllTabs"],

        "BookmarksHistory": ["addBookmarkAsKb", "viewBookmarksSidebarKb", "viewBookmarksSidebarWinKb", "manBookmarkKb", "bookmarkAllTabsKb", "key_gotoHistory", "showAllHistoryKb"],

        "Tools": ["key_openDownloads", "key_openAddons", "key_errorConsole", "key_webConsole", "key_privatebrowsing", "key_sanitize", "key_sanitize_mac", "key_webide"],

        "DeveloperTools": [
    "key_webconsole", "key_errorConsole", "key_jsdebugger", "key_inspector",
    "key_styleeditor", "key_jsprofiler", "key_devToolbar", "key_responsiveUI",
    "key_scratchpad"]
       };

const LABELS = {
        "focusURLBar": _("focusURLBar_label"),
        "focusURLBar2": _("focusURLBar2_label"),
        "key_search": _("key_search_label"),
        "key_search2": _("key_search2_label"),
        "key_stop": _("key_stop_label"),
        "key_stop_mac": _("key_stop_mac_label"),
        "key_reload": _("key_reload_label"),
        "key_reload2": _("key_reload2_label"),
        "key_forceReload": _("key_forceReload_label"),
        "key_forceReload2": _("key_forceReload2_label"),
        "goHome": _("goHome_label"),
        "goBackKb": _("goBackKb_label"),
        "goBackKb2": _("goBackKb2_label"),
        "goForwardKb": _("goForwardKb_label"),
        "goForwardKb2": _("goForwardKb2_label"),
        "key_close": _("key_close_label"),
        "key_undoCloseTab": _("key_undoCloseTab_label"),
        "key_undoCloseWindow": _("key_undoCloseWindow_label"),
        "key_toggleAddonBar": _("key_toggleAddonBar_label"),
        "key_findPrevious": _("key_findPrevious_label"),
        "key_selectLastTab": _("key_selectLastTab_label"),
        "key_closeOther": _("key_closeOther_label"),
        "key_prevTab": _("key_prevTab_label"),
        "key_nextTab": _("key_nextTab_label"),
        "key_selectTab1": _("key_selectTab1_label"),
        "key_selectTab2": _("key_selectTab2_label"),
        "key_selectTab3": _("key_selectTab3_label"),
        "key_selectTab4": _("key_selectTab4_label"),
        "key_selectTab5": _("key_selectTab5_label"),
        "key_selectTab6": _("key_selectTab6_label"),
        "key_selectTab7": _("key_selectTab7_label"),
        "key_selectTab8": _("key_selectTab8_label"),
        "key_tabview": _("key_tabview_label"),
        "key_nextTabGroup": _("key_nextTabGroup_label"),
        "key_previousTabGroup": _("key_previousTabGroup_label"),
        "key_toggleMute": _("key_toggleMute_label"),
        "key_sanitize_mac": _("key_sanitize_mac_label"),
        "key_devToolboxMenuItemF12": _("key_devToolboxMenuItemF12_label"),
        "key_devToolboxMenuItem": _("key_devToolboxMenuItem_label"),
        "key_fullScreen_old": _("key_fullScreen_old_label"),
        "key_minimizeWindow": _("key_minimizeWindow_label"),
		"key_switchTextDirection": _("key_switchTextDirection_label"),
		"key_toggleMute": _("key_toggleMute_label"),
		"key_findSelection": _("key_findSelection_label"),
		"key_webide": _("key_webide_label"),
		"focusChatBar": _("focusChatBar_label"),
        "key_firebug_toggleBreakOn": _("key_firebug_toggleBreakOn_label"),
        "key_firebug_detachFirebug": _("key_firebug_detachFirebug_label"),
        "key_firebug_closeFirebug": _("key_firebug_closeFirebug_label"),
        "key_firebug_focusCommandLine": _("key_firebug_focusCommandLine_label"),
        "key_firebug_toggleInspecting": _("key_firebug_toggleInspecting_label"),
        "key_foxyproxyquickadd": _("key_foxyproxyquickadd_label"),
        "key_changeproxy": _("key_changeproxy_label"),
        "secureLoginShortcut": _("secureLoginShortcut_label")
    };

function findKeyLabel(key) {
	let label = key.getLabel();

	if (label) {
		return label;
	}

    let id = key.id;
    if (id in LABELS) {
    return LABELS[id];
    }

        // try to find a menuitem
        let menuitem = Windows.querySelector(`menuitem[key="${id}"][label]`);
return menuitem ? menuitem.getAttribute("label") : id;
    }

let TreeView = exports.TreeView = function (term) {
	function filter(key) {

		return findKeyLabel(key).toLowerCase().includes(term.toLowerCase()) ||
		key.shortcut.toString().toLowerCase().includes(term.toLowerCase());
	}
	this._buildGroups(term ? keys.filter(filter) : keys.all());
	this._buildRows();
	};

TreeView.prototype = {
    _buildGroups: function(map) {
        this.groups = [];

        for (let [gname, gkeys] of keys.group(map, GROUPS, "Other")) {
           	let lname = String.concat(gname,"_group");
			let group = {type: "group", name: _(lname), parentIdx: -1, open: true, keys: gkeys};
            this.groups.push(group);
        }
    },

    _buildRows: function() {
        this.rows = [];

        for (let group of this.groups) {
            let parentIdx = this.rows.push(group) - 1;

            if (group.open) {
				for (let key of group.keys) {
                    this.rows.push({type: "key", key: key, parentIdx: parentIdx});
                }
            }
        }
    },

	get rowCount() { return this.rows.length },

    isContainer: function(idx) {
        return ("group" == this.rows[idx].type);
    },

    isEditable: function(idx, column) {
        return column.index && !this.isContainer(idx);
    },

    isContainerOpen: function(idx) {
        return this.rows[idx].open;
    },

    getLevel: function(idx) {
        return +!this.isContainer(idx);
    },

    getParentIndex: function(idx) {
        return this.rows[idx].parentIdx;
    },

    toggleOpenState: function(idx) {
        let row = this.rows[idx];

        let numRows = -row.keys.length;
        if (row.open = !row.open) { numRows *= -1; }

        this._buildRows();
        this.treebox.rowCountChanged(idx + 1, numRows);
        this.treebox.invalidateRow(idx);
    },

    hasNextSibling: function(idx, after) {
        let level = this.getLevel(idx);
        for (let t = after + 1; t < this.rowCount; t++) {
            let nextLevel = this.getLevel(t);
            if (nextLevel == level) { return true; }
            if (nextLevel < level) { return false; }
        }
    },

    getCellText: function(idx, column) {
        let row = this.rows[idx];
        if (this.isContainer(idx)) { return (column.index ? "" : row.name); }

        let key = row.key;
        if (!column.index) { return findKeyLabel(key); }

        let overlay = Overlays.findByKey(key);
        return (overlay ? overlay.shortcut : key.shortcut).toString();
    },

    getCellValue: function(idx, column) {
        if (!this.isContainer(idx)) { return this.rows[idx].key.toString(); }
    },

    getCellProperties: function(idx, column) {
        if (this.isContainer(idx)) { return; }

        if (!column.index) { return; }

        let props = [];
        let key = this.rows[idx].key;
        if (Overlays.findByKey(key)) {
            props.push("custom");
            let toStringCache = Overlays.findByKey(key).shortcut.toString();

            if (Overlays.findByConflictingShortcut(toStringCache)) {
                let groupColor = Overlays.getConflictingShortcutColor(toStringCache);
                props.push("maketext" + groupColor);
            }
        }
        if ((Overlays.findByCustomShortcut(key.shortcut)) && (!Overlays.findByOverriddenShortcut(key.shortcut)) && (!Overlays.findByDisabledKey(key))) // Display as overridden only if using default shortcut and not disabled.
        props.push("overridden");

        if (Overlays.findByDisabledKey(key)) { props.push("disabled"); }

        return props.join(" ");
    },

    setTree: function(treebox) {
        this.treebox = treebox;
    },

    isContainerEmpty: function() { return false },
    setCellText: function() { },
    isSeparator: function() { return false },
    isSorted: function() { return false },
    getImageSrc: function() {},
    getRowProperties: function() {},
    getColumnProperties: function() {}
};

let customXULTreeView = exports.customXULTreeView = function (term, find = false, tree = null, filtered = false, newXul = false) {

	function findNewRow(row) {
		return row.key == this;
	}

	function filter(key) {
		return key.getKey().toLowerCase().includes(term.toLowerCase()) || key.getLabel().toLowerCase().includes(term.toLowerCase()) ||
		key.getCommand().toLowerCase().includes(term.toLowerCase())
	}

	if (!find) { this._buildRows(term ? CustomXUL.filter(filter) : CustomXUL.allCustomKeys()); }

	else {
	this._buildRows(!!filtered ? CustomXUL.filter(filter) : CustomXUL.allCustomKeys());
	let toSelect = this.rows.find(findNewRow,term);
	toSelect = this.rows.indexOf(toSelect);
	Windows.getMostRecentWindow().setTimeout(function () {
	tree.view.selection.adjustSelection((toSelect -1),1);
	tree.view.selection.select(toSelect);
	if (!!newXul) { tree.startEditing(tree.view.selection.currentIndex,tree.columns.getNamedColumn("KeybinderCustomXUL_NameCol")); }
	},0);
	}
};

customXULTreeView.prototype = {
    _buildRows: function(map) {
        this.rows = [];
		let sortedKeys = new Map([...map.entries()].sort((a,b) => a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0));
	    for (let [mapKey, mapValue] of sortedKeys.entries()) {
	    this.rows.push({type:"customXULKey", key:mapValue.key, label:mapValue.label, command:mapValue.command});
	    }
    },

	get rowCount() { return this.rows.length },

    isContainer: function(idx) {
        return ("group" == this.rows[idx].type);
    },

    performActionOnRow: function(action, idx) {
    if ("select" == action) { this.treebox.view.selection.select(idx) }
    },

    isEditable: function(idx, column) {
        return column.index && !this.isContainer(idx);
    },

    isSelectable: function(idx, column) {
        return column.index && !this.isContainer(idx);
    },

    isContainerOpen: function(idx) {
        return this.rows[idx].open;
    },

    getLevel: function(idx) {
        return +!this.isContainer(idx);
    },

    getParentIndex: function(idx) {
        return this.rows[idx].parentIdx;
    },

    toggleOpenState: function(idx) {
		let row = this.rows[idx];

		let numRows = -row.keys.length;
		if (row.open = !row.open) { numRows *= -1; }

		this._buildRows();
		this.treebox.rowCountChanged(idx + 1, numRows);
		this.treebox.invalidateRow(idx);
    },

    hasNextSibling: function(idx, after) {},

    getCellText: function(idx, column) {
        let row = this.rows[idx];
		if ("KeybinderCustomXUL_NameCol" == column.id) { return CustomXUL.allCustomKeys().get(row.key).key }
		if ("KeybinderCustomXUL_LabelCol" == column.id) { return CustomXUL.allCustomKeys().get(row.key).label }
		if ("KeybinderCustomXUL_ActionCol" == column.id) { return CustomXUL.allCustomKeys().get(row.key).command }
    },

    getCellValue: function(idx, column) {
        if (!this.isContainer(idx)) { return this.rows[idx].key.toString(); }
    },

    getCellProperties: function(idx, column) {},

    setTree: function(treebox) {
        this.treebox = treebox;
    },

    isContainerEmpty: function() { return false },
    setCellText: function() { },
    isSeparator: function() { return false },
    isSorted: function() { return false },
    getImageSrc: function() {},
    getRowProperties: function() {},
    getColumnProperties: function() {}
};
<commit_msg>Catch error caused by empty or deleted rows.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const keys = require("../core/key");
const CustomXUL = require("../core/custom");

const { Windows } = require("../util/windows");
const { Overlays } = require("../core/overlay");

var _ = require("sdk/l10n").get;
const extensionPrefs = require("sdk/simple-prefs");

const GROUPS = {
		"Application": ["key_quitApplication", "key_openHelpMac", "key_openHelp", "key_preferencesCmdMac", "key_hideThisAppCmdMac", "key_hideOtherAppsCmdMac"],
        "Navigation": ["goBackKb", "goBackKb2", "goForwardKb", "goForwardKb2", "goHome", "openFileKb", "key_reload", "key_reload2", "key_forceReload", /*"Ctrl+F5", Ctrl+Shift+R,*/ "key_stop", "key_stop_mac", "focusURLBar", "focusURLBar2"],

        "CurrentPage": [ /*"End", "F6", "Shift+F6",*/ "goHome", "key_viewInfo", "key_viewSource", "printKb", "key_savePage", "key_fullZoomEnlarge", "key_fullZoomReduce", "key_fullZoomReset", "key_fullScreen", "key_fullScreen_old", "key_minimizeWindow", "key_toggleMute","key_switchTextDirection"],

        "Editing": ["key_copy", "key_cut", "key_delete", "key_paste", "key_redo", "key_selectAll", "key_undo"],

        "Search": ["key_find", "key_findAgain", "key_findPrevious", "key_search", "key_search2", "key_findSelection"],

        "WindowsTabs": ["key_close", "key_closeWindow", "key_closeOther", "key_newNavigatorTab", "key_newNavigator", "key_undoCloseTab", "key_undoCloseWindow", "key_selectTab1", "key_selectTab2", "key_selectTab3", "key_selectTab4", "key_selectTab5", "key_selectTab6", "key_selectTab7", "key_selectTab8", "key_selectLastTab", "key_tabview", "key_nextTabGroup", "key_previousTabGroup", "key_prevTab", "key_nextTab","key_showAllTabs"],

        "BookmarksHistory": ["addBookmarkAsKb", "viewBookmarksSidebarKb", "viewBookmarksSidebarWinKb", "manBookmarkKb", "bookmarkAllTabsKb", "key_gotoHistory", "showAllHistoryKb"],

        "Tools": ["key_openDownloads", "key_openAddons", "key_errorConsole", "key_webConsole", "key_privatebrowsing", "key_sanitize", "key_sanitize_mac", "key_webide"],

        "DeveloperTools": [
    "key_webconsole", "key_errorConsole", "key_jsdebugger", "key_inspector",
    "key_styleeditor", "key_jsprofiler", "key_devToolbar", "key_responsiveUI",
    "key_scratchpad"]
       };

const LABELS = {
        "focusURLBar": _("focusURLBar_label"),
        "focusURLBar2": _("focusURLBar2_label"),
        "key_search": _("key_search_label"),
        "key_search2": _("key_search2_label"),
        "key_stop": _("key_stop_label"),
        "key_stop_mac": _("key_stop_mac_label"),
        "key_reload": _("key_reload_label"),
        "key_reload2": _("key_reload2_label"),
        "key_forceReload": _("key_forceReload_label"),
        "key_forceReload2": _("key_forceReload2_label"),
        "goHome": _("goHome_label"),
        "goBackKb": _("goBackKb_label"),
        "goBackKb2": _("goBackKb2_label"),
        "goForwardKb": _("goForwardKb_label"),
        "goForwardKb2": _("goForwardKb2_label"),
        "key_close": _("key_close_label"),
        "key_undoCloseTab": _("key_undoCloseTab_label"),
        "key_undoCloseWindow": _("key_undoCloseWindow_label"),
        "key_toggleAddonBar": _("key_toggleAddonBar_label"),
        "key_findPrevious": _("key_findPrevious_label"),
        "key_selectLastTab": _("key_selectLastTab_label"),
        "key_closeOther": _("key_closeOther_label"),
        "key_prevTab": _("key_prevTab_label"),
        "key_nextTab": _("key_nextTab_label"),
        "key_selectTab1": _("key_selectTab1_label"),
        "key_selectTab2": _("key_selectTab2_label"),
        "key_selectTab3": _("key_selectTab3_label"),
        "key_selectTab4": _("key_selectTab4_label"),
        "key_selectTab5": _("key_selectTab5_label"),
        "key_selectTab6": _("key_selectTab6_label"),
        "key_selectTab7": _("key_selectTab7_label"),
        "key_selectTab8": _("key_selectTab8_label"),
        "key_tabview": _("key_tabview_label"),
        "key_nextTabGroup": _("key_nextTabGroup_label"),
        "key_previousTabGroup": _("key_previousTabGroup_label"),
        "key_toggleMute": _("key_toggleMute_label"),
        "key_sanitize_mac": _("key_sanitize_mac_label"),
        "key_devToolboxMenuItemF12": _("key_devToolboxMenuItemF12_label"),
        "key_devToolboxMenuItem": _("key_devToolboxMenuItem_label"),
        "key_fullScreen_old": _("key_fullScreen_old_label"),
        "key_minimizeWindow": _("key_minimizeWindow_label"),
		"key_switchTextDirection": _("key_switchTextDirection_label"),
		"key_toggleMute": _("key_toggleMute_label"),
		"key_findSelection": _("key_findSelection_label"),
		"key_webide": _("key_webide_label"),
		"focusChatBar": _("focusChatBar_label"),
        "key_firebug_toggleBreakOn": _("key_firebug_toggleBreakOn_label"),
        "key_firebug_detachFirebug": _("key_firebug_detachFirebug_label"),
        "key_firebug_closeFirebug": _("key_firebug_closeFirebug_label"),
        "key_firebug_focusCommandLine": _("key_firebug_focusCommandLine_label"),
        "key_firebug_toggleInspecting": _("key_firebug_toggleInspecting_label"),
        "key_foxyproxyquickadd": _("key_foxyproxyquickadd_label"),
        "key_changeproxy": _("key_changeproxy_label"),
        "secureLoginShortcut": _("secureLoginShortcut_label")
    };

function findKeyLabel(key) {
	let label = key.getLabel();

	if (label) {
		return label;
	}

    let id = key.id;
    if (id in LABELS) {
    return LABELS[id];
    }

        // try to find a menuitem
        let menuitem = Windows.querySelector(`menuitem[key="${id}"][label]`);
return menuitem ? menuitem.getAttribute("label") : id;
    }

let TreeView = exports.TreeView = function (term) {
	function filter(key) {

		return findKeyLabel(key).toLowerCase().includes(term.toLowerCase()) ||
		key.shortcut.toString().toLowerCase().includes(term.toLowerCase());
	}
	this._buildGroups(term ? keys.filter(filter) : keys.all());
	this._buildRows();
	};

TreeView.prototype = {
    _buildGroups: function(map) {
        this.groups = [];

        for (let [gname, gkeys] of keys.group(map, GROUPS, "Other")) {
           	let lname = String.concat(gname,"_group");
			let group = {type: "group", name: _(lname), parentIdx: -1, open: true, keys: gkeys};
            this.groups.push(group);
        }
    },

    _buildRows: function() {
        this.rows = [];

        for (let group of this.groups) {
            let parentIdx = this.rows.push(group) - 1;

            if (group.open) {
				for (let key of group.keys) {
                    this.rows.push({type: "key", key: key, parentIdx: parentIdx});
                }
            }
        }
    },

	get rowCount() { return this.rows.length },

    isContainer: function(idx) {
        return ("group" == this.rows[idx].type);
    },

    isEditable: function(idx, column) {
        return column.index && !this.isContainer(idx);
    },

    isContainerOpen: function(idx) {
        return this.rows[idx].open;
    },

    getLevel: function(idx) {
        return +!this.isContainer(idx);
    },

    getParentIndex: function(idx) {
        return this.rows[idx].parentIdx;
    },

    toggleOpenState: function(idx) {
        let row = this.rows[idx];

        let numRows = -row.keys.length;
        if (row.open = !row.open) { numRows *= -1; }

        this._buildRows();
        this.treebox.rowCountChanged(idx + 1, numRows);
        this.treebox.invalidateRow(idx);
    },

    hasNextSibling: function(idx, after) {
        let level = this.getLevel(idx);
        for (let t = after + 1; t < this.rowCount; t++) {
            let nextLevel = this.getLevel(t);
            if (nextLevel == level) { return true; }
            if (nextLevel < level) { return false; }
        }
    },

    getCellText: function(idx, column) {
        let row = this.rows[idx];
        if (this.isContainer(idx)) { return (column.index ? "" : row.name); }

        let key = row.key;
        if (!column.index) { return findKeyLabel(key); }

        let overlay = Overlays.findByKey(key);
        return (overlay ? overlay.shortcut : key.shortcut).toString();
    },

    getCellValue: function(idx, column) {
        if (!this.isContainer(idx)) { return this.rows[idx].key.toString(); }
    },

    getCellProperties: function(idx, column) {
        if (this.isContainer(idx)) { return; }

        if (!column.index) { return; }

        let props = [];
        let key = this.rows[idx].key;
        if (Overlays.findByKey(key)) {
            props.push("custom");
            let toStringCache = Overlays.findByKey(key).shortcut.toString();

            if (Overlays.findByConflictingShortcut(toStringCache)) {
                let groupColor = Overlays.getConflictingShortcutColor(toStringCache);
                props.push("maketext" + groupColor);
            }
        }
        if ((Overlays.findByCustomShortcut(key.shortcut)) && (!Overlays.findByOverriddenShortcut(key.shortcut)) && (!Overlays.findByDisabledKey(key))) // Display as overridden only if using default shortcut and not disabled.
        props.push("overridden");

        if (Overlays.findByDisabledKey(key)) { props.push("disabled"); }

        return props.join(" ");
    },

    setTree: function(treebox) {
        this.treebox = treebox;
    },

    isContainerEmpty: function() { return false },
    setCellText: function() { },
    isSeparator: function() { return false },
    isSorted: function() { return false },
    getImageSrc: function() {},
    getRowProperties: function() {},
    getColumnProperties: function() {}
};

let customXULTreeView = exports.customXULTreeView = function (term, find = false, tree = null, filtered = false, newXul = false) {

	function findNewRow(row) {
		return row.key == this;
	}

	function filter(key) {
		return key.getKey().toLowerCase().includes(term.toLowerCase()) || key.getLabel().toLowerCase().includes(term.toLowerCase()) ||
		key.getCommand().toLowerCase().includes(term.toLowerCase())
	}

	if (!find) { this._buildRows(term ? CustomXUL.filter(filter) : CustomXUL.allCustomKeys()); }

	else {
	this._buildRows(!!filtered ? CustomXUL.filter(filter) : CustomXUL.allCustomKeys());
	let toSelect = this.rows.find(findNewRow,term);
	toSelect = this.rows.indexOf(toSelect);
	Windows.getMostRecentWindow().setTimeout(function () {
	tree.view.selection.adjustSelection((toSelect -1),1);
	tree.view.selection.select(toSelect);
	if (!!newXul) { tree.startEditing(tree.view.selection.currentIndex,tree.columns.getNamedColumn("KeybinderCustomXUL_NameCol")); }
	},0);
	}
};

customXULTreeView.prototype = {
    _buildRows: function(map) {
        this.rows = [];
		let sortedKeys = new Map([...map.entries()].sort((a,b) => a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0));
	    for (let [mapKey, mapValue] of sortedKeys.entries()) {
	    this.rows.push({type:"customXULKey", key:mapValue.key, label:mapValue.label, command:mapValue.command});
	    }
    },

	get rowCount() { return this.rows.length },

    isContainer: function(idx) {
        return ("group" == this.rows[idx].type);
    },

    performActionOnRow: function(action, idx) {
    if ("select" == action) { this.treebox.view.selection.select(idx) }
    },

    isEditable: function(idx, column) {
        return column.index && !this.isContainer(idx);
    },

    isSelectable: function(idx, column) {
        return column.index && !this.isContainer(idx);
    },

    isContainerOpen: function(idx) {
        return this.rows[idx].open;
    },

    getLevel: function(idx) {
        return +!this.isContainer(idx);
    },

    getParentIndex: function(idx) {
        return this.rows[idx].parentIdx;
    },

    toggleOpenState: function(idx) {
		let row = this.rows[idx];

		let numRows = -row.keys.length;
		if (row.open = !row.open) { numRows *= -1; }

		this._buildRows();
		this.treebox.rowCountChanged(idx + 1, numRows);
		this.treebox.invalidateRow(idx);
    },

    hasNextSibling: function(idx, after) {},

    getCellText: function(idx, column) {
        let row = this.rows[idx];
        if (!row.key || !CustomXUL.find(row.key)) { return }
		if ("KeybinderCustomXUL_NameCol" == column.id) { return CustomXUL.allCustomKeys().get(row.key).key }
		if ("KeybinderCustomXUL_LabelCol" == column.id) { return CustomXUL.allCustomKeys().get(row.key).label }
		if ("KeybinderCustomXUL_ActionCol" == column.id) { return CustomXUL.allCustomKeys().get(row.key).command }
    },

    getCellValue: function(idx, column) {
        if (!this.isContainer(idx)) { return this.rows[idx].key.toString(); }
    },

    getCellProperties: function(idx, column) {},

    setTree: function(treebox) {
        this.treebox = treebox;
    },

    isContainerEmpty: function() { return false },
    setCellText: function() { },
    isSeparator: function() { return false },
    isSorted: function() { return false },
    getImageSrc: function() {},
    getRowProperties: function() {},
    getColumnProperties: function() {}
};
<|endoftext|>


<commit_before>import omit from 'lodash/omit';
import dotenv from 'dotenv';
import jwt from 'jsonwebtoken';
import db from '../models';

dotenv.load();
const secret = process.env.secretKey;

const { User } = db;
export default {
  create(req, res) {
    return User
      .create(req.userInput)
      .then((user) => {
        const token = jwt.sign(
          { user
          }, secret
        );
        return res.status(201).send({
          success: true,
          message: 'Signed up successfully',
          Token: token
        });
      })
      .catch(error => res.status(400).send(error));
  },
  login(req, res) {
    User
      .findOne({
        where: { username: req.body.username }
      })
      .then((user) => {
        user
          .update(
            {
              active: true,
            }).then((result) => {
            const token = jwt.sign(
              { result
              }, secret
            );
            res.status(200)
              .json({
                success: true,
                message: 'Logged In Successfully',
                Token: token
              });
          });
      });
  },
};
<commit_msg>Change JWT payload<commit_after>import dotenv from 'dotenv';
import jwt from 'jsonwebtoken';
import db from '../models';

dotenv.load();
const secret = process.env.secretKey;

const { User } = db;
export default {
  create(req, res) {
    return User
      .create(req.userInput)
      .then((user) => {
        const token = jwt.sign(
          { userId: user.id,
            username: user.username
          }, secret
        );
        return res.status(201).send({
          success: true,
          message: 'Signed up successfully',
          Token: token
        });
      })
      .catch(error => res.status(400).send(error));
  },
  login(req, res) {
    User
      .findOne({
        where: { username: req.body.username }
      })
      .then((user) => {
        user
          .update(
            {
              active: true,
            }).then((result) => {
            const token = jwt.sign(
              { result
              }, secret
            );
            res.status(200)
              .json({
                success: true,
                message: 'Logged In Successfully',
                Token: token
              });
          });
      });
  },
};
<|endoftext|>


<commit_before>if (!org.bustany.TrackerBird.TrackerSparql || !org.bustany.TrackerBird.TrackerSparql.__initialized)
org.bustany.TrackerBird.TrackerSparql = {
	__initialized: true,

	_trackerSparqlPath1: "libtracker-sparql-0.12.so.0",
	_trackerSparqlPath2: "libtracker-sparql-0.14.so.0",
	_lib: null,

	init: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		// Safeguard just in case a fool would call that twice
		if (tracker._lib) {
			return true;
		}

		Components.utils.import ("resource://gre/modules/ctypes.jsm");

		try {
			tracker._lib = ctypes.open (tracker._trackerSparqlPath1);
		} catch (e) {
			dump ("Could not load " + tracker._trackerSparqlPath1 + ": " + e + "\n");

		        try {
			        tracker._lib = ctypes.open (tracker._trackerSparqlPath2);
			} catch (e) {
			        dump ("Could not load " + tracker._trackerSparqlPath2 + ": " + e + "\n");
			        return false;
			}
		}

		// GLib types
		tracker.Object = new ctypes.StructType ("GObject");
		tracker.Cancellable = new ctypes.StructType ("GCancellable");
		tracker.Error = new ctypes.StructType ("GError", [
			{domain  : ctypes.uint32_t},
			{code    : ctypes.int32_t},
			{message : ctypes.char.ptr}
		]);
		tracker.AsyncResult = new ctypes.StructType ("GAsyncResult");
		tracker.AsyncReadyCallback = new ctypes.FunctionType(
			ctypes.default_abi,
			ctypes.void_t,
			[ tracker.Object.ptr, tracker.AsyncResult.ptr, ctypes.voidptr_t ]);

		// TrackerSparql types
		tracker.Connection = ctypes.StructType ("TrackerSparqlConnection");
		tracker.Cursor = ctypes.StructType ("TrackerSparqlCursor");

		// GLib methods
		tracker.free = tracker._lib.declare (
			"g_free",
			ctypes.default_abi,
			ctypes.void_t,
			ctypes.voidptr_t
		);

		tracker.object_unref = tracker._lib.declare (
			"g_object_unref",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Object.ptr
		);

		tracker.error_free = tracker._lib.declare (
			"g_error_free",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Error.ptr
		);

		// TrackerSparql methods (name, ABI, args with first arg = return type)
		tracker.connection_open = tracker._lib.declare (
			"tracker_sparql_connection_get",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_open_async = tracker._lib.declare (
			"tracker_sparql_connection_get_async",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Cancellable.ptr,
			tracker.AsyncReadyCallback.ptr,
			ctypes.voidptr_t);

		tracker.connection_open_finish = tracker._lib.declare (
			"tracker_sparql_connection_get_finish",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.AsyncResult.ptr,
			tracker.Error.ptr.ptr);

		tracker.connection_query = tracker._lib.declare (
			"tracker_sparql_connection_query",
			ctypes.default_abi,
			tracker.Cursor.ptr,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_update = tracker._lib.declare (
			"tracker_sparql_connection_update",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			ctypes.int32_t,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_next = tracker._lib.declare (
			"tracker_sparql_cursor_next",
			ctypes.default_abi,
			ctypes.bool,
			tracker.Cursor.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_get_string = tracker._lib.declare (
			"tracker_sparql_cursor_get_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			tracker.Cursor.ptr,
			ctypes.int,
			ctypes.long.ptr
		);

		tracker.escape_string = tracker._lib.declare (
			"tracker_sparql_escape_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			ctypes.char.ptr
		);

		return true;
	},

	shutdown: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		if (this._connection) {
			tracker.object_unref(this._connection);
		}

		if (this._lib) {
			this._lib.close ();
		}
	}
}
<commit_msg>thunderbird: Fix libraries we expect to find and connect to<commit_after>if (!org.bustany.TrackerBird.TrackerSparql || !org.bustany.TrackerBird.TrackerSparql.__initialized)
org.bustany.TrackerBird.TrackerSparql = {
	__initialized: true,

	_trackerSparqlPath1: "libtracker-sparql-0.14.so.0",
	_trackerSparqlPath2: "libtracker-sparql-0.16.so.0",
	_lib: null,

	init: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		// Safeguard just in case a fool would call that twice
		if (tracker._lib) {
			return true;
		}

		Components.utils.import ("resource://gre/modules/ctypes.jsm");

		try {
			tracker._lib = ctypes.open (tracker._trackerSparqlPath1);
		} catch (e) {
			dump ("Could not load " + tracker._trackerSparqlPath1 + ": " + e + "\n");

		        try {
			        tracker._lib = ctypes.open (tracker._trackerSparqlPath2);
			} catch (e) {
			        dump ("Could not load " + tracker._trackerSparqlPath2 + ": " + e + "\n");
			        return false;
			}
		}

		// GLib types
		tracker.Object = new ctypes.StructType ("GObject");
		tracker.Cancellable = new ctypes.StructType ("GCancellable");
		tracker.Error = new ctypes.StructType ("GError", [
			{domain  : ctypes.uint32_t},
			{code    : ctypes.int32_t},
			{message : ctypes.char.ptr}
		]);
		tracker.AsyncResult = new ctypes.StructType ("GAsyncResult");
		tracker.AsyncReadyCallback = new ctypes.FunctionType(
			ctypes.default_abi,
			ctypes.void_t,
			[ tracker.Object.ptr, tracker.AsyncResult.ptr, ctypes.voidptr_t ]);

		// TrackerSparql types
		tracker.Connection = ctypes.StructType ("TrackerSparqlConnection");
		tracker.Cursor = ctypes.StructType ("TrackerSparqlCursor");

		// GLib methods
		tracker.free = tracker._lib.declare (
			"g_free",
			ctypes.default_abi,
			ctypes.void_t,
			ctypes.voidptr_t
		);

		tracker.object_unref = tracker._lib.declare (
			"g_object_unref",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Object.ptr
		);

		tracker.error_free = tracker._lib.declare (
			"g_error_free",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Error.ptr
		);

		// TrackerSparql methods (name, ABI, args with first arg = return type)
		tracker.connection_open = tracker._lib.declare (
			"tracker_sparql_connection_get",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_open_async = tracker._lib.declare (
			"tracker_sparql_connection_get_async",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Cancellable.ptr,
			tracker.AsyncReadyCallback.ptr,
			ctypes.voidptr_t);

		tracker.connection_open_finish = tracker._lib.declare (
			"tracker_sparql_connection_get_finish",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.AsyncResult.ptr,
			tracker.Error.ptr.ptr);

		tracker.connection_query = tracker._lib.declare (
			"tracker_sparql_connection_query",
			ctypes.default_abi,
			tracker.Cursor.ptr,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_update = tracker._lib.declare (
			"tracker_sparql_connection_update",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			ctypes.int32_t,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_next = tracker._lib.declare (
			"tracker_sparql_cursor_next",
			ctypes.default_abi,
			ctypes.bool,
			tracker.Cursor.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_get_string = tracker._lib.declare (
			"tracker_sparql_cursor_get_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			tracker.Cursor.ptr,
			ctypes.int,
			ctypes.long.ptr
		);

		tracker.escape_string = tracker._lib.declare (
			"tracker_sparql_escape_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			ctypes.char.ptr
		);

		return true;
	},

	shutdown: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		if (this._connection) {
			tracker.object_unref(this._connection);
		}

		if (this._lib) {
			this._lib.close ();
		}
	}
}
<|endoftext|>