<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global define, module, require, exports */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery',
                'd3',
                'nf.ErrorHandler',
                'nf.Common',
                'nf.Dialog',
                'nf.Client',
                'nf.ProcessGroup',
                'nf.Shell',
                'nf.CanvasUtils'],
            function ($, d3, nfErrorHandler, nfCommon, nfDialog, nfClient, nfProcessGroup, nfShell, nfCanvasUtils) {
                return (nf.ProcessGroupConfiguration = factory($, d3, nfErrorHandler, nfCommon, nfDialog, nfClient, nfProcessGroup, nfShell, nfCanvasUtils));
            });
    } else if (typeof exports === 'object' && typeof module === 'object') {
        module.exports = (nf.ProcessGroupConfiguration =
            factory(require('jquery'),
                require('d3'),
                require('nf.ErrorHandler'),
                require('nf.Common'),
                require('nf.Dialog'),
                require('nf.Client'),
                require('nf.ProcessGroup'),
                require('nf.Shell'),
                require('nf.CanvasUtils')));
    } else {
        nf.ProcessGroupConfiguration = factory(root.$,
            root.d3,
            root.nf.ErrorHandler,
            root.nf.Common,
            root.nf.Dialog,
            root.nf.Client,
            root.nf.ProcessGroup,
            root.nf.Shell,
            root.nf.CanvasUtils);
    }
}(this, function ($, d3, nfErrorHandler, nfCommon, nfDialog, nfClient, nfProcessGroup, nfShell, nfCanvasUtils) {
    'use strict';

    var nfControllerServices;

    var config = {
        urls: {
            api: '../nifi-api'
        }
    };

    /**
     * Initializes the general tab.
     */
    var initGeneral = function () {
    };

    /**
     * Gets the controller services table.
     *
     * @returns {*|jQuery|HTMLElement}
     */
    var getControllerServicesTable = function () {
        return $('#process-group-controller-services-table');
    };

    /**
     * Saves the configuration for the specified group.
     *
     * @param version
     * @param groupId
     */
    var saveConfiguration = function (version, groupId) {
        // build the entity
        var entity = {
            'revision': nfClient.getRevision({
                'revision': {
                    'version': version
                }
            }),
            'component': {
                'id': groupId,
                'name': $('#process-group-name').val(),
                'comments': $('#process-group-comments').val()
            }
        };

        // update the selected component
        $.ajax({
            type: 'PUT',
            data: JSON.stringify(entity),
            url: config.urls.api + '/process-groups/' + encodeURIComponent(groupId),
            dataType: 'json',
            contentType: 'application/json'
        }).done(function (response) {
            // refresh the process group if necessary
            if (response.permissions.canRead && response.component.parentGroupId === nfCanvasUtils.getGroupId()) {
                nfProcessGroup.set(response);
            }

            // show the result dialog
            nfDialog.showOkDialog({
                headerText: 'Process Group Configuration',
                dialogContent: 'Process group configuration successfully saved.'
            });

            // update the click listener for the updated revision
            $('#process-group-configuration-save').off('click').on('click', function () {
                saveConfiguration(response.revision.version, groupId);
            });

            nfCanvasUtils.reload();
        }).fail(nfErrorHandler.handleAjaxError);
    };

    /**
     * Loads the configuration for the specified process group.
     *
     * @param {string} groupId
     */
    var loadConfiguration = function (groupId) {
        var setUnauthorizedText = function () {
            $('#read-only-process-group-name').addClass('unset').text('Unauthorized');
            $('#read-only-process-group-comments').addClass('unset').text('Unauthorized');
        };

        var setEditable = function (editable) {
            if (editable) {
                $('#process-group-configuration div.editable').show();
                $('#process-group-configuration div.read-only').hide();
                $('#process-group-configuration-save').show();
            } else {
                $('#process-group-configuration div.editable').hide();
                $('#process-group-configuration div.read-only').show();
                $('#process-group-configuration-save').hide();
            }
        };

        var processGroup = $.Deferred(function (deferred) {
            $.ajax({
                type: 'GET',
                url: config.urls.api + '/process-groups/' + encodeURIComponent(groupId),
                dataType: 'json'
            }).done(function (response) {
                // store the process group
                $('#process-group-configuration').data('process-group', response);

                if (response.permissions.canWrite) {
                    var processGroup = response.component;

                    // populate the process group settings
                    $('#process-group-id').text(processGroup.id);
                    $('#process-group-name').removeClass('unset').val(processGroup.name);
                    $('#process-group-comments').removeClass('unset').val(processGroup.comments);

                    setEditable(true);

                    // register the click listener for the save button
                    $('#process-group-configuration-save').off('click').on('click', function () {
                        saveConfiguration(response.revision.version, response.id);
                    });
                } else {
                    if (response.permissions.canRead) {
                        // populate the process group settings
                        $('#read-only-process-group-name').removeClass('unset').text(response.component.name);
                        $('#read-only-process-group-comments').removeClass('unset').text(response.component.comments);
                    } else {
                        setUnauthorizedText();
                    }

                    setEditable(false);
                }
                deferred.resolve();
            }).fail(function (xhr, status, error) {
                if (xhr.status === 403) {
                    if (groupId === nfCanvasUtils.getGroupId()) {
                        $('#process-group-configuration').data('process-group', {
                            'permissions': {
                                canRead: false,
                                canWrite: nfCanvasUtils.canWrite()
                            }
                        });
                    } else {
                        $('#process-group-configuration').data('process-group', nfProcessGroup.get(groupId));
                    }

                    setUnauthorizedText();
                    setEditable(false);
                    deferred.resolve();
                } else {
                    deferred.reject(xhr, status, error);
                }
            });
        }).promise();

        // load the controller services
        var controllerServicesUri = config.urls.api + '/flow/process-groups/' + encodeURIComponent(groupId) + '/controller-services';
        var controllerServices = nfControllerServices.loadControllerServices(controllerServicesUri, getControllerServicesTable());

        // wait for everything to complete
        return $.when(processGroup, controllerServices).done(function (processGroupResult, controllerServicesResult) {
            var controllerServicesResponse = controllerServicesResult[0];

            // update the current time
            $('#process-group-configuration-last-refreshed').text(controllerServicesResponse.currentTime);
        }).fail(nfErrorHandler.handleAjaxError);
    };

    /**
     * Shows the process group configuration.
     */
    var showConfiguration = function () {
        // show the configuration dialog
        nfShell.showContent('#process-group-configuration').done(function () {
            reset();
        });

        //reset content to account for possible policy changes
        $('#process-group-configuration-tabs').find('.selected-tab').click();

        // adjust the table size
        nfProcessGroupConfiguration.resetTableSize();
    };

    /**
     * Resets the process group configuration dialog.
     */
    var reset = function () {
        $('#process-group-configuration').removeData('process-group');

        // reset button state
        $('#process-group-configuration-save').mouseout();

        // reset the fields
        $('#process-group-name').val('');
        $('#process-group-comments').val('');
    };

    var nfProcessGroupConfiguration = {

        /**
         * Initialize the process group configuration.
         *
         * @param nfControllerServicesRef   The nfControllerServices module.
         */
        init: function (nfControllerServicesRef) {
            nfControllerServices = nfControllerServicesRef;

            // initialize the process group configuration tabs
            $('#process-group-configuration-tabs').tabbs({
                tabStyle: 'tab',
                selectedTabStyle: 'selected-tab',
                scrollableTabContentStyle: 'scrollable',
                tabs: [{
                    name: 'General',
                    tabContentId: 'general-process-group-configuration-tab-content'
                }, {
                    name: 'Controller Services',
                    tabContentId: 'process-group-controller-services-tab-content'
                }],
                select: function () {
                    var processGroup = $('#process-group-configuration').data('process-group');
                    var canWrite = nfCommon.isDefinedAndNotNull(processGroup) ? processGroup.permissions.canWrite : false;

                    var tab = $(this).text();
                    if (tab === 'General') {
                        $('#add-process-group-configuration-controller-service').hide();

                        if (canWrite) {
                            $('#process-group-configuration-save').show();
                        } else {
                            $('#process-group-configuration-save').hide();
                        }
                    } else {
                        $('#process-group-configuration-save').hide();

                        if (canWrite) {
                            $('#add-process-group-configuration-controller-service').show();
                            $('#process-group-controller-services-tab-content').css('top', '32px');
                        } else {
                            $('#add-process-group-configuration-controller-service').hide();
                            $('#process-group-controller-services-tab-content').css('top', '0');
                        }

                        // resize the table
                        nfProcessGroupConfiguration.resetTableSize();
                    }
                }
            });

            // initialize each tab
            initGeneral();
            nfControllerServices.init(getControllerServicesTable());
        },

        /**
         * Update the size of the grid based on its container's current size.
         */
        resetTableSize: function () {
            nfControllerServices.resetTableSize(getControllerServicesTable());
        },

        /**
         * Shows the settings dialog.
         */
        showConfiguration: function (groupId) {
            // update the click listener
            $('#process-group-configuration-refresh-button').off('click').on('click', function () {
                loadConfiguration(groupId);
            });

            // update the new controller service click listener
            $('#add-process-group-configuration-controller-service').off('click').on('click', function () {
                var selectedTab = $('#process-group-configuration-tabs li.selected-tab').text();
                if (selectedTab === 'Controller Services') {
                    var controllerServicesUri = config.urls.api + '/process-groups/' + encodeURIComponent(groupId) + '/controller-services';
                    nfControllerServices.promptNewControllerService(controllerServicesUri, getControllerServicesTable());
                }
            });

            // load the configuration
            return loadConfiguration(groupId).done(showConfiguration);
        },

        /**
         * Loads the configuration for the specified process group.
         *
         * @param groupId
         */
        loadConfiguration: function (groupId) {
            return loadConfiguration(groupId);
        },

        /**
         * Selects the specified controller service.
         *
         * @param {string} controllerServiceId
         */
        selectControllerService: function (controllerServiceId) {
            var controllerServiceGrid = getControllerServicesTable().data('gridInstance');
            var controllerServiceData = controllerServiceGrid.getData();

            // select the desired service
            var row = controllerServiceData.getRowById(controllerServiceId);
            controllerServiceGrid.setSelectedRows([row]);
            controllerServiceGrid.scrollRowIntoView(row);

            // select the controller services tab
            $('#process-group-configuration-tabs').find('li:eq(1)').click();
        }
    };

    return nfProcessGroupConfiguration;
}));<commit_msg>NIFI-3243: - Rendering the selected Process Group in the header if possible.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global define, module, require, exports */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery',
                'd3',
                'nf.ErrorHandler',
                'nf.Common',
                'nf.Dialog',
                'nf.Client',
                'nf.ProcessGroup',
                'nf.Shell',
                'nf.CanvasUtils'],
            function ($, d3, nfErrorHandler, nfCommon, nfDialog, nfClient, nfProcessGroup, nfShell, nfCanvasUtils) {
                return (nf.ProcessGroupConfiguration = factory($, d3, nfErrorHandler, nfCommon, nfDialog, nfClient, nfProcessGroup, nfShell, nfCanvasUtils));
            });
    } else if (typeof exports === 'object' && typeof module === 'object') {
        module.exports = (nf.ProcessGroupConfiguration =
            factory(require('jquery'),
                require('d3'),
                require('nf.ErrorHandler'),
                require('nf.Common'),
                require('nf.Dialog'),
                require('nf.Client'),
                require('nf.ProcessGroup'),
                require('nf.Shell'),
                require('nf.CanvasUtils')));
    } else {
        nf.ProcessGroupConfiguration = factory(root.$,
            root.d3,
            root.nf.ErrorHandler,
            root.nf.Common,
            root.nf.Dialog,
            root.nf.Client,
            root.nf.ProcessGroup,
            root.nf.Shell,
            root.nf.CanvasUtils);
    }
}(this, function ($, d3, nfErrorHandler, nfCommon, nfDialog, nfClient, nfProcessGroup, nfShell, nfCanvasUtils) {
    'use strict';

    var nfControllerServices;

    var config = {
        urls: {
            api: '../nifi-api'
        }
    };

    /**
     * Initializes the general tab.
     */
    var initGeneral = function () {
    };

    /**
     * Gets the controller services table.
     *
     * @returns {*|jQuery|HTMLElement}
     */
    var getControllerServicesTable = function () {
        return $('#process-group-controller-services-table');
    };

    /**
     * Saves the configuration for the specified group.
     *
     * @param version
     * @param groupId
     */
    var saveConfiguration = function (version, groupId) {
        // build the entity
        var entity = {
            'revision': nfClient.getRevision({
                'revision': {
                    'version': version
                }
            }),
            'component': {
                'id': groupId,
                'name': $('#process-group-name').val(),
                'comments': $('#process-group-comments').val()
            }
        };

        // update the selected component
        $.ajax({
            type: 'PUT',
            data: JSON.stringify(entity),
            url: config.urls.api + '/process-groups/' + encodeURIComponent(groupId),
            dataType: 'json',
            contentType: 'application/json'
        }).done(function (response) {
            // refresh the process group if necessary
            if (response.permissions.canRead && response.component.parentGroupId === nfCanvasUtils.getGroupId()) {
                nfProcessGroup.set(response);
            }

            // show the result dialog
            nfDialog.showOkDialog({
                headerText: 'Process Group Configuration',
                dialogContent: 'Process group configuration successfully saved.'
            });

            // update the click listener for the updated revision
            $('#process-group-configuration-save').off('click').on('click', function () {
                saveConfiguration(response.revision.version, groupId);
            });

            nfCanvasUtils.reload();
        }).fail(nfErrorHandler.handleAjaxError);
    };

    /**
     * Loads the configuration for the specified process group.
     *
     * @param {string} groupId
     */
    var loadConfiguration = function (groupId) {
        var setUnauthorizedText = function () {
            $('#read-only-process-group-name').addClass('unset').text('Unauthorized');
            $('#read-only-process-group-comments').addClass('unset').text('Unauthorized');
        };

        var setEditable = function (editable) {
            if (editable) {
                $('#process-group-configuration div.editable').show();
                $('#process-group-configuration div.read-only').hide();
                $('#process-group-configuration-save').show();
            } else {
                $('#process-group-configuration div.editable').hide();
                $('#process-group-configuration div.read-only').show();
                $('#process-group-configuration-save').hide();
            }
        };

        var processGroup = $.Deferred(function (deferred) {
            $.ajax({
                type: 'GET',
                url: config.urls.api + '/process-groups/' + encodeURIComponent(groupId),
                dataType: 'json'
            }).done(function (response) {
                // store the process group
                $('#process-group-configuration').data('process-group', response);

                if (response.permissions.canWrite) {
                    var processGroup = response.component;

                    // populate the process group settings
                    $('#process-group-id').text(processGroup.id);
                    $('#process-group-name').removeClass('unset').val(processGroup.name);
                    $('#process-group-comments').removeClass('unset').val(processGroup.comments);

                    // populate the header
                    $('#process-group-configuration-header-text').text(processGroup.name + ' Configuration');

                    setEditable(true);

                    // register the click listener for the save button
                    $('#process-group-configuration-save').off('click').on('click', function () {
                        saveConfiguration(response.revision.version, response.id);
                    });
                } else {
                    if (response.permissions.canRead) {
                        // populate the process group settings
                        $('#read-only-process-group-name').removeClass('unset').text(response.component.name);
                        $('#read-only-process-group-comments').removeClass('unset').text(response.component.comments);

                        // populate the header
                        $('#process-group-configuration-header-text').text(processGroup.name + ' Configuration');
                    } else {
                        setUnauthorizedText();
                    }

                    setEditable(false);
                }
                deferred.resolve();
            }).fail(function (xhr, status, error) {
                if (xhr.status === 403) {
                    if (groupId === nfCanvasUtils.getGroupId()) {
                        $('#process-group-configuration').data('process-group', {
                            'permissions': {
                                canRead: false,
                                canWrite: nfCanvasUtils.canWrite()
                            }
                        });
                    } else {
                        $('#process-group-configuration').data('process-group', nfProcessGroup.get(groupId));
                    }

                    setUnauthorizedText();
                    setEditable(false);
                    deferred.resolve();
                } else {
                    deferred.reject(xhr, status, error);
                }
            });
        }).promise();

        // load the controller services
        var controllerServicesUri = config.urls.api + '/flow/process-groups/' + encodeURIComponent(groupId) + '/controller-services';
        var controllerServices = nfControllerServices.loadControllerServices(controllerServicesUri, getControllerServicesTable());

        // wait for everything to complete
        return $.when(processGroup, controllerServices).done(function (processGroupResult, controllerServicesResult) {
            var controllerServicesResponse = controllerServicesResult[0];

            // update the current time
            $('#process-group-configuration-last-refreshed').text(controllerServicesResponse.currentTime);
        }).fail(nfErrorHandler.handleAjaxError);
    };

    /**
     * Shows the process group configuration.
     */
    var showConfiguration = function () {
        // show the configuration dialog
        nfShell.showContent('#process-group-configuration').done(function () {
            reset();
        });

        //reset content to account for possible policy changes
        $('#process-group-configuration-tabs').find('.selected-tab').click();

        // adjust the table size
        nfProcessGroupConfiguration.resetTableSize();
    };

    /**
     * Resets the process group configuration dialog.
     */
    var reset = function () {
        $('#process-group-configuration').removeData('process-group');

        // reset button state
        $('#process-group-configuration-save').mouseout();

        // reset the fields
        $('#process-group-name').val('');
        $('#process-group-comments').val('');

        // reset the header
        $('#process-group-configuration-header-text').text('Process Group Configuration');
    };

    var nfProcessGroupConfiguration = {

        /**
         * Initialize the process group configuration.
         *
         * @param nfControllerServicesRef   The nfControllerServices module.
         */
        init: function (nfControllerServicesRef) {
            nfControllerServices = nfControllerServicesRef;

            // initialize the process group configuration tabs
            $('#process-group-configuration-tabs').tabbs({
                tabStyle: 'tab',
                selectedTabStyle: 'selected-tab',
                scrollableTabContentStyle: 'scrollable',
                tabs: [{
                    name: 'General',
                    tabContentId: 'general-process-group-configuration-tab-content'
                }, {
                    name: 'Controller Services',
                    tabContentId: 'process-group-controller-services-tab-content'
                }],
                select: function () {
                    var processGroup = $('#process-group-configuration').data('process-group');
                    var canWrite = nfCommon.isDefinedAndNotNull(processGroup) ? processGroup.permissions.canWrite : false;

                    var tab = $(this).text();
                    if (tab === 'General') {
                        $('#add-process-group-configuration-controller-service').hide();

                        if (canWrite) {
                            $('#process-group-configuration-save').show();
                        } else {
                            $('#process-group-configuration-save').hide();
                        }
                    } else {
                        $('#process-group-configuration-save').hide();

                        if (canWrite) {
                            $('#add-process-group-configuration-controller-service').show();
                            $('#process-group-controller-services-tab-content').css('top', '32px');
                        } else {
                            $('#add-process-group-configuration-controller-service').hide();
                            $('#process-group-controller-services-tab-content').css('top', '0');
                        }

                        // resize the table
                        nfProcessGroupConfiguration.resetTableSize();
                    }
                }
            });

            // initialize each tab
            initGeneral();
            nfControllerServices.init(getControllerServicesTable());
        },

        /**
         * Update the size of the grid based on its container's current size.
         */
        resetTableSize: function () {
            nfControllerServices.resetTableSize(getControllerServicesTable());
        },

        /**
         * Shows the settings dialog.
         */
        showConfiguration: function (groupId) {
            // update the click listener
            $('#process-group-configuration-refresh-button').off('click').on('click', function () {
                loadConfiguration(groupId);
            });

            // update the new controller service click listener
            $('#add-process-group-configuration-controller-service').off('click').on('click', function () {
                var selectedTab = $('#process-group-configuration-tabs li.selected-tab').text();
                if (selectedTab === 'Controller Services') {
                    var controllerServicesUri = config.urls.api + '/process-groups/' + encodeURIComponent(groupId) + '/controller-services';
                    nfControllerServices.promptNewControllerService(controllerServicesUri, getControllerServicesTable());
                }
            });

            // load the configuration
            return loadConfiguration(groupId).done(showConfiguration);
        },

        /**
         * Loads the configuration for the specified process group.
         *
         * @param groupId
         */
        loadConfiguration: function (groupId) {
            return loadConfiguration(groupId);
        },

        /**
         * Selects the specified controller service.
         *
         * @param {string} controllerServiceId
         */
        selectControllerService: function (controllerServiceId) {
            var controllerServiceGrid = getControllerServicesTable().data('gridInstance');
            var controllerServiceData = controllerServiceGrid.getData();

            // select the desired service
            var row = controllerServiceData.getRowById(controllerServiceId);
            controllerServiceGrid.setSelectedRows([row]);
            controllerServiceGrid.scrollRowIntoView(row);

            // select the controller services tab
            $('#process-group-configuration-tabs').find('li:eq(1)').click();
        }
    };

    return nfProcessGroupConfiguration;
}));<|endoftext|>


<commit_before>const config = require('config');
const bcoin = require('bcoin').set(config.get('network'));
const path = require('path');
const co = require('co');
const fs = require('fs');

class Wallet {

  /**
   * Wallet
   * @constructor
   * @param {String} id - The wallet id
   * @param {String} location - The path in which wallet will be stored
   */

  constructor (id=config.get('wallet_id'), location = Wallet._getWalletLocation()) {
    this.id = id;
    this.location = location;
  }

  /**
   * Initializes the Wallet of Diavgeia.
   * If the wallet already exists, initialization is skipped
   */

  initialize() {
    var _wallet = this;
    if (! fs.existsSync(_wallet.location))
      fs.mkdirSync(_wallet.location);
    return co(function* () {
      let walletdb = yield _wallet.getWalletDB();
      let existingWallet = yield walletdb.get(_wallet.id);
      if (existingWallet === undefined) {
        yield walletdb.create({id:_wallet.id});
      }
      yield walletdb.close();
    });
  }

  /**
   * Creates and returns an instance of walletdb
   * @returns {Promise}
   */

  async getWalletDB() {
    var walletDB = new bcoin.walletdb({
      db : 'leveldb',
      location : this.location + '/diavgeia-wallet'
    })
    await walletDB.open();
    await walletDB.connect();
    return walletDB;
  }

  /**
   * Path Normalization of the wallet_location, based on the user preference
   * of having enabled the home path option or not.
   * @private
   * @returns {string}
   */

  static _getWalletLocation() {
    let configWalletLocation = config.get('wallet_location');
    if (config.get('wallet_location_from_home'))
      return process.env.HOME + '/' + path.normalize(configWalletLocation);
    return path.normalize(configWalletLocation);
  }

}

module.exports = Wallet;<commit_msg>Modify getWalletDB by adding co()<commit_after>const config = require('config');
const bcoin = require('bcoin').set(config.get('network'));
const path = require('path');
const co = require('co');
const fs = require('fs');

class Wallet {

  /**
   * Wallet
   * @constructor
   * @param {String} id - The wallet id
   * @param {String} location - The path in which wallet will be stored
   */

  constructor (id=config.get('wallet_id'), location = Wallet.getWalletLocation()) {
    this.id = id;
    this.location = location;
  }

  /**
   * Initializes the Wallet of Diavgeia.
   * If the wallet already exists, initialization is skipped
   */

  initialize() {
    var _wallet = this;
    if (! fs.existsSync(_wallet.location))
      fs.mkdirSync(_wallet.location);
    return co(function* () {
      let walletdb = yield _wallet.getWalletDB();
      let existingWallet = yield walletdb.get(_wallet.id);
      if (existingWallet === undefined) {
        yield walletdb.create({
          id:_wallet.id
        });
      }
      yield walletdb.close();
    });
  }

  /**
   * Creates and returns an instance of walletdb
   * @returns {Promise}
   */

  getWalletDB() {
    var walletDB = new bcoin.walletdb({
      db : 'leveldb',
      location : this.location + '/diavgeia-wallet',
      spv : true
    })
    return co(function* () {
      yield walletDB.open();
      yield walletDB.connect();
      return walletDB;
    });
  }

  /**
   * Path Normalization of the wallet_location, based on the user preference
   * of having enabled the home path option or not.
   * @returns {string}
   */

  static getWalletLocation() {
    let configWalletLocation = config.get('wallet_location');
    if (config.get('wallet_location_from_home'))
      return process.env.HOME + '/' + path.normalize(configWalletLocation);
    return path.normalize(configWalletLocation);
  }

}

module.exports = Wallet;<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

module.exports = Em.Route.extend({
  route: '/services/add',

  enter: function (router) {
    console.log('in /service/add:enter');
    if (App.get('isAdmin')) {
      Em.run.next(function () {
        var addServiceController = router.get('addServiceController');
        App.router.get('updateController').set('isWorking', false);
        var popup = App.ModalPopup.show({
          classNames: ['full-width-modal'],
          header:Em.I18n.t('services.add.header'),
          bodyClass:  App.AddServiceView.extend({
            controllerBinding: 'App.router.addServiceController'
          }),
          primary:Em.I18n.t('form.cancel'),
          showFooter: false,
          secondary: null,

          onPrimary:function () {
            this.hide();
            App.router.transitionTo('main.services.index');
          },
          onClose: function() {
            this.set('showCloseButton', false); // prevent user to click "Close" many times
            App.router.get('updateController').set('isWorking', true);
            var self = this;
            App.clusterStatus.setClusterStatus({
              clusterName: App.router.get('content.cluster.name'),
              clusterState: 'DEFAULT',
              wizardControllerName: App.router.get('addServiceController.name'),
              localdb: App.db.data
            });
            App.router.get('updateController').updateServiceMetric(function(){
              self.hide();
            });
            App.router.transitionTo('main.services.index');
          },
          didInsertElement: function(){
            this.fitHeight();
          }
        });
        addServiceController.set('popup',popup);
        var currentClusterStatus = App.clusterStatus.get('value');
        if (currentClusterStatus) {
          switch (currentClusterStatus.clusterState) {
            case 'ADD_SERVICES_DEPLOY_PREP_2' :
              addServiceController.setCurrentStep('5');
              break;
            case 'ADD_SERVICES_INSTALLING_3' :
            case 'SERVICE_STARTING_3' :
              addServiceController.setCurrentStep('6');
              break;
            case 'ADD_SERVICES_INSTALLED_4' :
              addServiceController.setCurrentStep('7');
              break;
            default:
              break;
          }
        }

        router.transitionTo('step' + addServiceController.get('currentStep'));
      });
    } else {
      Em.run.next(function () {
        App.router.transitionTo('main.services');
      });
    }

  },

  /*connectOutlets: function (router) {
    console.log('in /service/add:connectOutlets');
    router.get('mainController').connectOutlet('addService');
  },*/

  step1: Em.Route.extend({
    route: '/step1',
    connectOutlets: function (router) {
      console.log('in addService.step1:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('1');
      controller.set('hideBackButton', true);
      controller.dataLoading().done(function () {
        controller.loadServicesFromServer();
        controller.loadAllPriorSteps();
        controller.connectOutlet('wizardStep4', controller.get('content.services'));
      })
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep4Controller = router.get('wizardStep4Controller');
      addServiceController.saveServices(wizardStep4Controller);
      addServiceController.saveClients(wizardStep4Controller);
      addServiceController.setDBProperty('masterComponentHosts', undefined);
      router.transitionTo('step2');
    }
  }),

  step2: Em.Route.extend({
    route: '/step2',
    connectOutlets: function (router) {
      console.log('in addService.step2:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('2');
      controller.set('hideBackButton', false);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('wizardStep5', controller.get('content'));
      })

    },
    back: Em.Router.transitionTo('step1'),
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep5Controller = router.get('wizardStep5Controller');
      addServiceController.saveMasterComponentHosts(wizardStep5Controller);
      addServiceController.setDBProperty('slaveComponentHosts', undefined);
      router.transitionTo('step3');
    }
  }),

  step3: Em.Route.extend({
    route: '/step3',
    connectOutlets: function (router) {
      console.log('in addService.step3:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('3');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        var wizardStep6Controller = router.get('wizardStep6Controller');
        wizardStep6Controller.set('wizardController', controller);
        controller.connectOutlet('wizardStep6', controller.get('content'));
        wizardStep6Controller.set('isMasters', false);
      })
    },
    back: function(router){
      var controller = router.get('addServiceController');
      if(!controller.get('content.skipMasterStep')){
        router.transitionTo('step2');
      } else {
        router.transitionTo('step1');
      }
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep6Controller = router.get('wizardStep6Controller');

      if (wizardStep6Controller.validate()) {
        addServiceController.saveSlaveComponentHosts(wizardStep6Controller);
        addServiceController.get('content').set('serviceConfigProperties', null);
        addServiceController.setDBProperty('serviceConfigProperties', null);
        router.transitionTo('step4');
      }
    }
  }),

  step4: Em.Route.extend({
    route: '/step4',
    connectOutlets: function (router) {
      console.log('in addService.step4:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('4');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.loadAdvancedConfigs();
        var wizardStep7Controller = router.get('wizardStep7Controller');
        wizardStep7Controller.set('wizardController', controller);
        controller.connectOutlet('wizardStep7', controller.get('content'));
      })
    },
    back: function(router){
      var controller = router.get('addServiceController');
      if(!controller.get('content.skipSlavesStep')){
        router.transitionTo('step3');
      } else if(!controller.get('content.skipMasterStep')) {
        router.transitionTo('step2');
      } else {
        router.transitionTo('step1');
      }
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep7Controller = router.get('wizardStep7Controller');
      addServiceController.saveServiceConfigProperties(wizardStep7Controller);
      router.transitionTo('step5');
    }
  }),

  step5: Em.Route.extend({
    route: '/step5',
    connectOutlets: function (router, context) {
      console.log('in addService.step5:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('5');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        var wizardStep8Controller = router.get('wizardStep8Controller');
        wizardStep8Controller.set('wizardController', controller);
        controller.connectOutlet('wizardStep8', controller.get('content'));
      })
    },
    back: function(router){
      var controller = router.get('addServiceController');
      if(!controller.get('content.skipConfigStep')) {
        router.transitionTo('step4');
      }
      else {
        if(!controller.get('content.skipSlavesStep')) {
          router.transitionTo('step3');
        }
        else {
          if(!controller.get('content.skipMasterStep')) {
            router.transitionTo('step2');
          }
          else {
            router.transitionTo('step1');
          }
        }
      }
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep8Controller = router.get('wizardStep8Controller');
      addServiceController.installServices();
      addServiceController.setInfoForStep9();

      addServiceController.saveClusterState('ADD_SERVICES_INSTALLING_3');
      wizardStep8Controller.set('servicesInstalled', true);
      router.transitionTo('step6');
    }
  }),

  step6: Em.Route.extend({
    route: '/step6',
    connectOutlets: function (router, context) {
      console.log('in addService.step6:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('6');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        var wizardStep9Controller = router.get('wizardStep9Controller');
        wizardStep9Controller.set('wizardController', controller);
        if (!App.testMode) {              //if test mode is ON don't disable prior steps link.
          controller.setLowerStepsDisable(6);
        }
        controller.connectOutlet('wizardStep9', controller.get('content'));
      })
    },
    back: Em.Router.transitionTo('step5'),
    retry: function(router,context) {
      var addServiceController = router.get('addServiceController');
      var wizardStep9Controller = router.get('wizardStep9Controller');
      if (wizardStep9Controller.get('showRetry')) {
        if (wizardStep9Controller.get('content.cluster.status') === 'INSTALL FAILED') {
          var isRetry = true;
          addServiceController.installServices(isRetry);
          addServiceController.setInfoForStep9();
          wizardStep9Controller.resetHostsForRetry();
          // We need to do recovery based on whether we are in Add Host or Installer wizard
          addServiceController.saveClusterState('ADD_SERVICES_INSTALLING_3');
        }
        wizardStep9Controller.navigateStep();
      }
    },
    unroutePath: function() {
      return false;
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep9Controller = router.get('wizardStep9Controller');
      addServiceController.saveInstalledHosts(wizardStep9Controller);

      // We need to do recovery based on whether we are in Add Host or Installer wizard
      addServiceController.saveClusterState('ADD_SERVICES_INSTALLED_4');

      router.transitionTo('step7');
    }
  }),

  step7: Em.Route.extend({
    route: '/step7',
    connectOutlets: function (router, context) {
      console.log('in addService.step7:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('7');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.setLowerStepsDisable(7);
        controller.connectOutlet('wizardStep10', controller.get('content'));
      })
    },
    back: Em.Router.transitionTo('step6'),
    complete: function (router, context) {
      var addServiceController = router.get('addServiceController');
      addServiceController.get('popup').onClose();
      addServiceController.finish();
      // We need to do recovery based on whether we are in Add Host or Installer wizard
      addServiceController.saveClusterState('DEFAULT');
    }
  }),

  gotoStep1: Em.Router.transitionTo('step1'),

  gotoStep2: Em.Router.transitionTo('step2'),

  gotoStep3: Em.Router.transitionTo('step3'),

  gotoStep4: Em.Router.transitionTo('step4'),

  gotoStep5: Em.Router.transitionTo('step5'),

  gotoStep6: Em.Router.transitionTo('step6'),

  gotoStep7: Em.Router.transitionTo('step7'),

  backToServices: function (router) {
    App.router.get('updateController').set('isWorking', true);
    router.transitionTo('services');
  }

});
<commit_msg>AMBARI-4165. Add Service wizard: after last step you are back on first step. (Denys Buzhor via onechiporenko)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

module.exports = Em.Route.extend({
  route: '/services/add',

  enter: function (router) {
    console.log('in /service/add:enter');
    if (App.get('isAdmin')) {
      Em.run.next(function () {
        var addServiceController = router.get('addServiceController');
        App.router.get('updateController').set('isWorking', false);
        var popup = App.ModalPopup.show({
          classNames: ['full-width-modal'],
          header:Em.I18n.t('services.add.header'),
          bodyClass:  App.AddServiceView.extend({
            controllerBinding: 'App.router.addServiceController'
          }),
          primary:Em.I18n.t('form.cancel'),
          showFooter: false,
          secondary: null,

          onPrimary:function () {
            this.hide();
            App.router.transitionTo('main.services.index');
          },
          onClose: function() {
            this.set('showCloseButton', false); // prevent user to click "Close" many times
            App.router.get('updateController').set('isWorking', true);
            var self = this;
            App.clusterStatus.setClusterStatus({
              clusterName: App.router.get('content.cluster.name'),
              clusterState: 'DEFAULT',
              wizardControllerName: App.router.get('addServiceController.name'),
              localdb: App.db.data
            });
            App.router.get('updateController').updateServices(function(){
              App.router.get('updateController').updateServiceMetric(function(){
                self.hide();
              });
            });
            App.router.transitionTo('main.services.index');
          },
          didInsertElement: function(){
            this.fitHeight();
          }
        });
        addServiceController.set('popup',popup);
        var currentClusterStatus = App.clusterStatus.get('value');
        if (currentClusterStatus) {
          switch (currentClusterStatus.clusterState) {
            case 'ADD_SERVICES_DEPLOY_PREP_2' :
              addServiceController.setCurrentStep('5');
              break;
            case 'ADD_SERVICES_INSTALLING_3' :
            case 'SERVICE_STARTING_3' :
              addServiceController.setCurrentStep('6');
              break;
            case 'ADD_SERVICES_INSTALLED_4' :
              addServiceController.setCurrentStep('7');
              break;
            default:
              break;
          }
        }

        router.transitionTo('step' + addServiceController.get('currentStep'));
      });
    } else {
      Em.run.next(function () {
        App.router.transitionTo('main.services');
      });
    }

  },

  /*connectOutlets: function (router) {
    console.log('in /service/add:connectOutlets');
    router.get('mainController').connectOutlet('addService');
  },*/

  step1: Em.Route.extend({
    route: '/step1',
    connectOutlets: function (router) {
      console.log('in addService.step1:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('1');
      controller.set('hideBackButton', true);
      controller.dataLoading().done(function () {
        controller.loadServicesFromServer();
        controller.loadAllPriorSteps();
        controller.connectOutlet('wizardStep4', controller.get('content.services'));
      })
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep4Controller = router.get('wizardStep4Controller');
      addServiceController.saveServices(wizardStep4Controller);
      addServiceController.saveClients(wizardStep4Controller);
      addServiceController.setDBProperty('masterComponentHosts', undefined);
      router.transitionTo('step2');
    }
  }),

  step2: Em.Route.extend({
    route: '/step2',
    connectOutlets: function (router) {
      console.log('in addService.step2:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('2');
      controller.set('hideBackButton', false);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('wizardStep5', controller.get('content'));
      })

    },
    back: Em.Router.transitionTo('step1'),
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep5Controller = router.get('wizardStep5Controller');
      addServiceController.saveMasterComponentHosts(wizardStep5Controller);
      addServiceController.setDBProperty('slaveComponentHosts', undefined);
      router.transitionTo('step3');
    }
  }),

  step3: Em.Route.extend({
    route: '/step3',
    connectOutlets: function (router) {
      console.log('in addService.step3:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('3');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        var wizardStep6Controller = router.get('wizardStep6Controller');
        wizardStep6Controller.set('wizardController', controller);
        controller.connectOutlet('wizardStep6', controller.get('content'));
        wizardStep6Controller.set('isMasters', false);
      })
    },
    back: function(router){
      var controller = router.get('addServiceController');
      if(!controller.get('content.skipMasterStep')){
        router.transitionTo('step2');
      } else {
        router.transitionTo('step1');
      }
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep6Controller = router.get('wizardStep6Controller');

      if (wizardStep6Controller.validate()) {
        addServiceController.saveSlaveComponentHosts(wizardStep6Controller);
        addServiceController.get('content').set('serviceConfigProperties', null);
        addServiceController.setDBProperty('serviceConfigProperties', null);
        router.transitionTo('step4');
      }
    }
  }),

  step4: Em.Route.extend({
    route: '/step4',
    connectOutlets: function (router) {
      console.log('in addService.step4:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('4');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.loadAdvancedConfigs();
        var wizardStep7Controller = router.get('wizardStep7Controller');
        wizardStep7Controller.set('wizardController', controller);
        controller.connectOutlet('wizardStep7', controller.get('content'));
      })
    },
    back: function(router){
      var controller = router.get('addServiceController');
      if(!controller.get('content.skipSlavesStep')){
        router.transitionTo('step3');
      } else if(!controller.get('content.skipMasterStep')) {
        router.transitionTo('step2');
      } else {
        router.transitionTo('step1');
      }
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep7Controller = router.get('wizardStep7Controller');
      addServiceController.saveServiceConfigProperties(wizardStep7Controller);
      router.transitionTo('step5');
    }
  }),

  step5: Em.Route.extend({
    route: '/step5',
    connectOutlets: function (router, context) {
      console.log('in addService.step5:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('5');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        var wizardStep8Controller = router.get('wizardStep8Controller');
        wizardStep8Controller.set('wizardController', controller);
        controller.connectOutlet('wizardStep8', controller.get('content'));
      })
    },
    back: function(router){
      var controller = router.get('addServiceController');
      if(!controller.get('content.skipConfigStep')) {
        router.transitionTo('step4');
      }
      else {
        if(!controller.get('content.skipSlavesStep')) {
          router.transitionTo('step3');
        }
        else {
          if(!controller.get('content.skipMasterStep')) {
            router.transitionTo('step2');
          }
          else {
            router.transitionTo('step1');
          }
        }
      }
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep8Controller = router.get('wizardStep8Controller');
      addServiceController.installServices();
      addServiceController.setInfoForStep9();

      addServiceController.saveClusterState('ADD_SERVICES_INSTALLING_3');
      wizardStep8Controller.set('servicesInstalled', true);
      router.transitionTo('step6');
    }
  }),

  step6: Em.Route.extend({
    route: '/step6',
    connectOutlets: function (router, context) {
      console.log('in addService.step6:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('6');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        var wizardStep9Controller = router.get('wizardStep9Controller');
        wizardStep9Controller.set('wizardController', controller);
        if (!App.testMode) {              //if test mode is ON don't disable prior steps link.
          controller.setLowerStepsDisable(6);
        }
        controller.connectOutlet('wizardStep9', controller.get('content'));
      })
    },
    back: Em.Router.transitionTo('step5'),
    retry: function(router,context) {
      var addServiceController = router.get('addServiceController');
      var wizardStep9Controller = router.get('wizardStep9Controller');
      if (wizardStep9Controller.get('showRetry')) {
        if (wizardStep9Controller.get('content.cluster.status') === 'INSTALL FAILED') {
          var isRetry = true;
          addServiceController.installServices(isRetry);
          addServiceController.setInfoForStep9();
          wizardStep9Controller.resetHostsForRetry();
          // We need to do recovery based on whether we are in Add Host or Installer wizard
          addServiceController.saveClusterState('ADD_SERVICES_INSTALLING_3');
        }
        wizardStep9Controller.navigateStep();
      }
    },
    unroutePath: function() {
      return false;
    },
    next: function (router) {
      var addServiceController = router.get('addServiceController');
      var wizardStep9Controller = router.get('wizardStep9Controller');
      addServiceController.saveInstalledHosts(wizardStep9Controller);

      // We need to do recovery based on whether we are in Add Host or Installer wizard
      addServiceController.saveClusterState('ADD_SERVICES_INSTALLED_4');

      router.transitionTo('step7');
    }
  }),

  step7: Em.Route.extend({
    route: '/step7',
    connectOutlets: function (router, context) {
      console.log('in addService.step7:connectOutlets');
      var controller = router.get('addServiceController');
      controller.setCurrentStep('7');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.setLowerStepsDisable(7);
        controller.connectOutlet('wizardStep10', controller.get('content'));
      })
    },
    back: Em.Router.transitionTo('step6'),
    complete: function (router, context) {
      var addServiceController = router.get('addServiceController');
      addServiceController.get('popup').onClose();
      addServiceController.finish();
      // We need to do recovery based on whether we are in Add Host or Installer wizard
      addServiceController.saveClusterState('DEFAULT');
    }
  }),

  gotoStep1: Em.Router.transitionTo('step1'),

  gotoStep2: Em.Router.transitionTo('step2'),

  gotoStep3: Em.Router.transitionTo('step3'),

  gotoStep4: Em.Router.transitionTo('step4'),

  gotoStep5: Em.Router.transitionTo('step5'),

  gotoStep6: Em.Router.transitionTo('step6'),

  gotoStep7: Em.Router.transitionTo('step7'),

  backToServices: function (router) {
    App.router.get('updateController').set('isWorking', true);
    router.transitionTo('services');
  }

});
<|endoftext|>


<commit_before>var iconv = require('iconv-lite');
var zlib = require('zlib');
var MAX_REQ_SIZE = 128 * 1024;
var MAX_RES_SIZE = 256 * 1024;
var TIMEOUT = 20000;
var CACHE_TIME = 6000;
var CLEAR_INTERVAL = 3000;
var MAX_LENGTH = 512;
var MIN_LENGTH = 412;
var COUNT = 100;
var count = 0;
var ids = [];
var data = {};
var proxy, binded, timeout, interval, util;

function disable() {
	proxy.removeListener('request', handleRequest);
	ids = [];
	data = {};
	interval && clearInterval(interval);
	interval = null;
	binded = false;
}

function enable() {
	!binded && proxy.on('request', handleRequest);
	binded = true;
	clearTimeout(timeout);
	timeout = setTimeout(disable, TIMEOUT);
	if (!interval) {
		interval = setInterval(clearCache, CLEAR_INTERVAL);
	}
}

/**
 * 如果超过最大缓存数，清理如下请求数据：
 * 1. 已经请求结束且结束时间超过10秒
 * 2. 请求#1前面的未结束且未被ui读取过的请求
 */
function clearCache() {
	var len = ids.length;
	if (len <= MAX_LENGTH) {
		return;
	}

	var index = -1; //已经完成，且缓存超过10s的最后一个请求
	var now = Date.now();
	for (var i = len - 1; i >= 0; i--) {
		var curData = data[ids[i]];
		if (curData.endTime && now - curData.endTime > TIMEOUT) {
			index = i;
			break;
		}
	}

	if (index < 0) {
		return;
	}

	var _ids = [];
	var end;
	++index;
	for (var i = 0; i < index; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData.read && (!curData.endTime || now - curData.endTime < CACHE_TIME)) {
			_ids.push(id);
		} else {
			delete data[id];
			if (--len <= MIN_LENGTH) {
				_ids.push.apply(_ids, ids.slice(i + 1, index));
				break;
			}
		}
	}
	ids = _ids.concat(ids.slice(index));
}

function passThrough(chunk, encoding, callback) {
	callback(null, chunk);
}

function decode(body) {
	if (body) {
		var _body = body + '';
		if (_body.indexOf('�') != -1) {
			_body = iconv.decode(body, 'gbk');
		}
		body = _body;
	}

	return body;
}

function get(options) {
	enable();
	options = options || {};
	var data = {};
	var newIds = options.startTime == -1 ? [] : getIds(options.startTime, options.count);
	var list = getList(newIds).concat(getList(options.ids));
	for (var i = 0, len = list.length; i < len; i++) {
		var item = list[i];
		if (item) {
			data[item.id] = item;
		}
	}

	return {
		ids: options.ids || [],
		newIds: newIds,
		data: data
	};
}

function getIds(startTime, count) {
	var len = ids.length;
	if (!len) {
		return [];
	}

	startTime = (startTime || Date.now() - 6000) + '';
	count = Math.min(count || COUNT, len);
	if (ids[0] > startTime) {

		return ids.slice(0, count);
	}

	if (len === 1 || ids[len - 1] <= startTime) {

		return  [];
	}

	var index = getIndex(startTime, 0, len - 1);
	return ids.slice(index, index + count);
}

function getIndex(startTime, start, end) {
	if (end - start <= 1) {
		return ids[start] > startTime ? start : end;
	}

	var mid = Math.floor((start + end) / 2);
	var id = ids[mid];
	return id == startTime ? mid + 1 : (id < startTime ? getIndex(startTime, mid + 1, end)
			: getIndex(startTime, start, mid));
}

function getList(ids) {
	var result = [];
	for (var i = 0, len = ids && ids.length; i < len; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData) {
			curData.read = true;
			result[i] = curData;
		}
	}

	return result;
}

function handleRequest(req) {
	var dnsTime = req.dnsTime || 0;
	req.dnsTime = Date.now();
	var startTime = req.dnsTime - dnsTime;
	var id = startTime + '-' + ++count;
	var reqData = {
			method: req.method || 'GET',
			httpVersion: req.httpVersion || '1.1',
            ip: req.ip || '::ffff:127.0.0.1',
            headers: req.headers
		};
	var resData = {
			ip: req.host
	};

	var curData = data[id] = {
			id: id,
			url: req.url,
			startTime: startTime,
			dnsTime: req.dnsTime,
			req: reqData,
			res: resData,
			rules: req.rules
	};

	ids.push(id);
	req.on('response', handleResponse);
	req.on('error', function(err) {
		reqData.body = err && err.stack;
		curData.endTime = reqData.requestTime = Date.now();
		curData.reqError = true;
		req.removeListener('response', handleResponse);
		req._transform = passThrough;
	});

	var reqBody;
	var reqSize = 0;

	if (util.hasRequestBody(req)) {
		reqBody = false;
	}
	req._transform = function(chunk, encoding, callback) {

		if (chunk) {
			if (reqBody || reqBody === false) {
				reqBody = reqBody ? Buffer.concat([reqBody, chunk]) : chunk;
			}
			reqSize += chunk.length;
		}

		if (reqBody && reqBody.length > MAX_REQ_SIZE) {
			reqBody = null;
		}

		if (!chunk) {
			curData.requestTime = Date.now();
			curData.reqEnd = true;
			reqData.size = reqSize;
			reqData.body = decode(reqBody);
		}

		callback(null, chunk);
	};

	function handleResponse(res) {
		curData.responseTime = Date.now();
		resData.headers = res.headers;
		resData.statusCode = res.statusCode;
		resData.ip = res.ip;
		res.on('error', function(err) {
			resData.body = err && err.stack;
			curData.endTime = Date.now();
			curData.resError = true;
			res._transform = passThrough;
		});

		var resBody;
		var resSize = 0;
		var contentType = util.getContentType(res.headers);
		if (contentType && contentType != 'IMG' && util.hasBody(res)) {
			resBody = false;
		}

		res._transform = function(chunk, encoding, callback) {
			if (chunk) {
				if (resBody || resBody === false) {
					resBody = resBody ? Buffer.concat([resBody, chunk]) : chunk;
				}

				resSize += chunk.length;
			}

			if (resBody && resBody.length > MAX_RES_SIZE) {
				resBody = null;
			}

			if (!chunk) {
				curData.endTime = Date.now();
				curData.resEnd = true;
				resData.size = resSize;
				if (resBody) {
					var unzip;
					switch (util.toLowerCase(res.headers['content-encoding'])) {
					    case 'gzip':
					    	unzip = zlib.gunzip.bind(zlib);
					      break;
					    case 'deflate':
					    	unzip = zlib.inflate.bind(zlib);
					      break;
					}

					if (unzip) {
						unzip(resBody, function(err, body) {
							if (err) {
								callback(err, chunk);
								return;
							}
							resData.body = decode(body);
							callback(null, chunk);
						});
						return;
					}
				}
				resData.body = decode(resBody);
			}

			callback(null, chunk);
		};
	}

}

module.exports = function init(_proxy) {
	proxy = _proxy;
	util = proxy.util;
	enable();
	module.exports = get;
};<commit_msg>cache time<commit_after>var iconv = require('iconv-lite');
var zlib = require('zlib');
var MAX_REQ_SIZE = 128 * 1024;
var MAX_RES_SIZE = 256 * 1024;
var TIMEOUT = 20000;
var CLEAR_INTERVAL = 3000;
var CACHE_TIME = CLEAR_INTERVAL * 2;
var WAITING_TIME = CLEAR_INTERVAL * 10;
var MAX_LENGTH = 512;
var MIN_LENGTH = 412;
var COUNT = 100;
var count = 0;
var ids = [];
var data = {};
var proxy, binded, timeout, interval, util;

function disable() {
	proxy.removeListener('request', handleRequest);
	ids = [];
	data = {};
	interval && clearInterval(interval);
	interval = null;
	binded = false;
}

function enable() {
	!binded && proxy.on('request', handleRequest);
	binded = true;
	clearTimeout(timeout);
	timeout = setTimeout(disable, TIMEOUT);
	if (!interval) {
		interval = setInterval(clearCache, CLEAR_INTERVAL);
	}
}

/**
 * 如果超过最大缓存数，清理如下请求数据：
 * 1. 已经请求结束且结束时间超过10秒
 * 2. 请求#1前面的未结束且未被ui读取过的请求
 */
function clearCache() {
	var len = ids.length;
	if (len <= MAX_LENGTH) {
		return;
	}

	var index = -1; //已经完成，且缓存超过10s的最后一个请求
	var now = Date.now();
	for (var i = len - 1; i >= 0; i--) {
		var curData = data[ids[i]];
		if (curData.endTime && now - curData.endTime > TIMEOUT) {
			index = i;
			break;
		}
	}

	if (index < 0) {
		return;
	}

	var _ids = [];
	var end;
	++index;
	for (var i = 0; i < index; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData.read && (!curData.endTime || now - curData.endTime < CACHE_TIME
				|| now - curData.startTime < WAITING_TIME)) {
			_ids.push(id);
		} else {
			delete data[id];
			if (--len <= MIN_LENGTH) {
				_ids.push.apply(_ids, ids.slice(i + 1, index));
				break;
			}
		}
	}
	ids = _ids.concat(ids.slice(index));
}

function passThrough(chunk, encoding, callback) {
	callback(null, chunk);
}

function decode(body) {
	if (body) {
		var _body = body + '';
		if (_body.indexOf('�') != -1) {
			_body = iconv.decode(body, 'gbk');
		}
		body = _body;
	}

	return body;
}

function get(options) {
	enable();
	options = options || {};
	var data = {};
	var newIds = options.startTime == -1 ? [] : getIds(options.startTime, options.count);
	var list = getList(newIds).concat(getList(options.ids));
	for (var i = 0, len = list.length; i < len; i++) {
		var item = list[i];
		if (item) {
			data[item.id] = item;
		}
	}

	return {
		ids: options.ids || [],
		newIds: newIds,
		data: data
	};
}

function getIds(startTime, count) {
	var len = ids.length;
	if (!len) {
		return [];
	}

	startTime = (startTime || Date.now() - 6000) + '';
	count = Math.min(count || COUNT, len);
	if (ids[0] > startTime) {

		return ids.slice(0, count);
	}

	if (len === 1 || ids[len - 1] <= startTime) {

		return  [];
	}

	var index = getIndex(startTime, 0, len - 1);
	return ids.slice(index, index + count);
}

function getIndex(startTime, start, end) {
	if (end - start <= 1) {
		return ids[start] > startTime ? start : end;
	}

	var mid = Math.floor((start + end) / 2);
	var id = ids[mid];
	return id == startTime ? mid + 1 : (id < startTime ? getIndex(startTime, mid + 1, end)
			: getIndex(startTime, start, mid));
}

function getList(ids) {
	var result = [];
	for (var i = 0, len = ids && ids.length; i < len; i++) {
		var id = ids[i];
		var curData = data[id];
		if (curData) {
			curData.read = true;
			result[i] = curData;
		}
	}

	return result;
}

function handleRequest(req) {
	var dnsTime = req.dnsTime || 0;
	req.dnsTime = Date.now();
	var startTime = req.dnsTime - dnsTime;
	var id = startTime + '-' + ++count;
	var reqData = {
			method: req.method || 'GET',
			httpVersion: req.httpVersion || '1.1',
            ip: req.ip || '::ffff:127.0.0.1',
            headers: req.headers
		};
	var resData = {
			ip: req.host
	};

	var curData = data[id] = {
			id: id,
			url: req.url,
			startTime: startTime,
			dnsTime: req.dnsTime,
			req: reqData,
			res: resData,
			rules: req.rules
	};

	ids.push(id);
	req.on('response', handleResponse);
	req.on('error', function(err) {
		reqData.body = err && err.stack;
		curData.endTime = reqData.requestTime = Date.now();
		curData.reqError = true;
		req.removeListener('response', handleResponse);
		req._transform = passThrough;
	});

	var reqBody;
	var reqSize = 0;

	if (util.hasRequestBody(req)) {
		reqBody = false;
	}
	req._transform = function(chunk, encoding, callback) {

		if (chunk) {
			if (reqBody || reqBody === false) {
				reqBody = reqBody ? Buffer.concat([reqBody, chunk]) : chunk;
			}
			reqSize += chunk.length;
		}

		if (reqBody && reqBody.length > MAX_REQ_SIZE) {
			reqBody = null;
		}

		if (!chunk) {
			curData.requestTime = Date.now();
			curData.reqEnd = true;
			reqData.size = reqSize;
			reqData.body = decode(reqBody);
		}

		callback(null, chunk);
	};

	function handleResponse(res) {
		curData.responseTime = Date.now();
		resData.headers = res.headers;
		resData.statusCode = res.statusCode;
		resData.ip = res.ip;
		res.on('error', function(err) {
			resData.body = err && err.stack;
			curData.endTime = Date.now();
			curData.resError = true;
			res._transform = passThrough;
		});

		var resBody;
		var resSize = 0;
		var contentType = util.getContentType(res.headers);
		if (contentType && contentType != 'IMG' && util.hasBody(res)) {
			resBody = false;
		}

		res._transform = function(chunk, encoding, callback) {
			if (chunk) {
				if (resBody || resBody === false) {
					resBody = resBody ? Buffer.concat([resBody, chunk]) : chunk;
				}

				resSize += chunk.length;
			}

			if (resBody && resBody.length > MAX_RES_SIZE) {
				resBody = null;
			}

			if (!chunk) {
				curData.endTime = Date.now();
				curData.resEnd = true;
				resData.size = resSize;
				if (resBody) {
					var unzip;
					switch (util.toLowerCase(res.headers['content-encoding'])) {
					    case 'gzip':
					    	unzip = zlib.gunzip.bind(zlib);
					      break;
					    case 'deflate':
					    	unzip = zlib.inflate.bind(zlib);
					      break;
					}

					if (unzip) {
						unzip(resBody, function(err, body) {
							if (err) {
								callback(err, chunk);
								return;
							}
							resData.body = decode(body);
							callback(null, chunk);
						});
						return;
					}
				}
				resData.body = decode(resBody);
			}

			callback(null, chunk);
		};
	}

}

module.exports = function init(_proxy) {
	proxy = _proxy;
	util = proxy.util;
	enable();
	module.exports = get;
};<|endoftext|>


<commit_before>/**
 * `syncer` is a collection of instance methods that are mixed into the prototypes
 * of `BaseModel` and `BaseCollection`. The purpose is to encapsulate shared logic
 * for fetching data from the API.
 */

var _ = require('underscore'),
    Backbone = require('backbone'),

    // Pull out params in path, like '/users/:id'.
    extractParamNamesRe = /:([a-z_-]+)/ig,

    methodMap = {
      'create': 'POST',
      'update': 'PUT',
      'delete': 'DELETE',
      'read': 'GET'
    },

    isServer = (typeof window === 'undefined');

if (isServer) {
  // hide it from requirejs since it's server only
  var serverOnly_qs = 'qs2';
  var qs = require(serverOnly_qs);
} else {
  var $ = window.$ || require('jquery');
  Backbone.$ = $;
}

var syncer = module.exports;

function clientSync(method, model, options) {
  var error;
  options = _.clone(options);
  if (!_.isUndefined(options.data)) options.data = _.clone(options.data);
  options.url = this.getUrl(options.url, true, options.data);
  error = options.error;
  if (error) {
    options.error = function(xhr) {
      var body = xhr.responseText,
          contentType = xhr.getResponseHeader('content-type'),
          resp;
      if (contentType && contentType.indexOf('application/json') !== -1) {
        try {
          body = JSON.parse(body);
        } catch (e) {}
      }
      resp = {
        body: body,
        status: xhr.status
      };
      error(resp);
    }
  }
  return Backbone.sync(method, model, options);
}

function serverSync(method, model, options) {
  var api, urlParts, verb, req, queryStr;

  options = _.clone(options);
  if (!_.isUndefined(options.data)) options.data = _.clone(options.data);
  options.url = this.getUrl(options.url, false, options.data);
  verb = methodMap[method];
  urlParts = options.url.split('?');
  req = this.app.req;
  queryStr = urlParts[1] || '';
  if (!_.isEmpty(options.data)) queryStr += '&' + qs.stringify(options.data);
  /**
   * if queryStr is initially an empty string, leading '&' will still get parsed correctly by qs.parse below.
   * e.g.  qs.parse('&baz=quux') => { baz: 'quux' }
   */

  api = {
    method: verb,
    path: urlParts[0],
    query: qs.parse(queryStr),
    headers: options.headers || {},
    api: _.result(this, 'api'),
    body: {}
  };

  if (verb === 'POST' || verb === 'PUT') {
    api.body = model.toJSON();
  }

  req.dataAdapter.request(req, api, function(err, response, body) {
    var resp;
    if (err) {
      resp = {
        body: body,
        // Pass through the statusCode, so lower-level code can handle i.e. 401 properly.
        status: err.status
      };

      if (options.error) {
        // This `error` has signature of $.ajax, not Backbone.sync.
        options.error(resp);
      } else {
        throw err;
      }
    } else {
      // This `success` has signature of $.ajax, not Backbone.sync.
      options.success(body);
    }
  });
}

syncer.clientSync = clientSync;
syncer.serverSync = serverSync;
syncer.sync = function sync() {
  var syncMethod = isServer ? serverSync : clientSync;
  return syncMethod.apply(this, arguments);
};

/**
 * 'model' is either a model or collection that
 * has a 'url' property, which can be a string or function.
 */
syncer.getUrl = function getUrl(url, clientPrefix, params) {
  if (clientPrefix == null) {
    clientPrefix = false;
  }
  params = params || {};
  url = url || _.result(this, 'url');
  if (clientPrefix && !~url.indexOf('://')) {
    url = this.formatClientUrl(url, _.result(this, 'api'));
  }
  return this.interpolateParams(this, url, params);
};

syncer.formatClientUrl = function(url, api) {
  var prefix = this.app.get('apiPath') || '/api';
  if (api) {
    prefix += '/' + api;
  }
  prefix += '/-';
  return prefix + url;
};

/**
 * Deeply-compare two objects to see if they differ.
 */
syncer.objectsDiffer = function objectsDiffer(data1, data2) {
  var changed = false,
      keys,
      key,
      value1,
      value2;

  keys = _.unique(_.keys(data1).concat(_.keys(data2)));
  for (var i = 0, len = keys.length; i < len; i++) {
    key = keys[i];
    value1 = data1[key];
    value2 = data2[key];

    // If attribute is an object recurse
    if (_.isObject(value1) && _.isObject(value2)) {
      changed = this.objectsDiffer(value1, value2);
    // Test for equality
    } else if (!_.isEqual(value1, value2)) {
      changed = true;
    }
  }
  return changed;
};

/**
 * This maps i.e. '/listings/:id' to '/listings/3' if
 * the model you supply has model.get('id') == 3.
 */
syncer.interpolateParams = function interpolateParams(model, url, params) {
  var matches = url.match(extractParamNamesRe);

  params = params || {};

  if (matches) {
    matches.forEach(function(param) {
      var property = param.slice(1),
          value;

      // Is collection? Then use options.
      if (model.length != null) {
        value = model.options[property];

      // Otherwise it's a model; use attrs.
      } else {
        value = model.get(property);
      }
      url = url.replace(param, value);

      /**
       * Delete the param from params hash, so we don't get urls like:
       * /v1/threads/1234?id=1234...
       */
      delete params[property];
    });
  }
  /**
   * Separate deletion of idAttribute from params hash necessary if using urlRoot in the model
   * so we don't get urls like: /v1/threads/1234?id=1234
   */
  delete params[model.idAttribute]
  return url;
};
<commit_msg>URI encode interpolated parameter value<commit_after>/**
 * `syncer` is a collection of instance methods that are mixed into the prototypes
 * of `BaseModel` and `BaseCollection`. The purpose is to encapsulate shared logic
 * for fetching data from the API.
 */

var _ = require('underscore'),
    Backbone = require('backbone'),

    // Pull out params in path, like '/users/:id'.
    extractParamNamesRe = /:([a-z_-]+)/ig,

    methodMap = {
      'create': 'POST',
      'update': 'PUT',
      'delete': 'DELETE',
      'read': 'GET'
    },

    isServer = (typeof window === 'undefined');

if (isServer) {
  // hide it from requirejs since it's server only
  var serverOnly_qs = 'qs2';
  var qs = require(serverOnly_qs);
} else {
  var $ = window.$ || require('jquery');
  Backbone.$ = $;
}

var syncer = module.exports;

function clientSync(method, model, options) {
  var error;
  options = _.clone(options);
  if (!_.isUndefined(options.data)) options.data = _.clone(options.data);
  options.url = this.getUrl(options.url, true, options.data);
  error = options.error;
  if (error) {
    options.error = function(xhr) {
      var body = xhr.responseText,
          contentType = xhr.getResponseHeader('content-type'),
          resp;
      if (contentType && contentType.indexOf('application/json') !== -1) {
        try {
          body = JSON.parse(body);
        } catch (e) {}
      }
      resp = {
        body: body,
        status: xhr.status
      };
      error(resp);
    }
  }
  return Backbone.sync(method, model, options);
}

function serverSync(method, model, options) {
  var api, urlParts, verb, req, queryStr;

  options = _.clone(options);
  if (!_.isUndefined(options.data)) options.data = _.clone(options.data);
  options.url = this.getUrl(options.url, false, options.data);
  verb = methodMap[method];
  urlParts = options.url.split('?');
  req = this.app.req;
  queryStr = urlParts[1] || '';
  if (!_.isEmpty(options.data)) queryStr += '&' + qs.stringify(options.data);
  /**
   * if queryStr is initially an empty string, leading '&' will still get parsed correctly by qs.parse below.
   * e.g.  qs.parse('&baz=quux') => { baz: 'quux' }
   */

  api = {
    method: verb,
    path: urlParts[0],
    query: qs.parse(queryStr),
    headers: options.headers || {},
    api: _.result(this, 'api'),
    body: {}
  };

  if (verb === 'POST' || verb === 'PUT') {
    api.body = model.toJSON();
  }

  req.dataAdapter.request(req, api, function(err, response, body) {
    var resp;
    if (err) {
      resp = {
        body: body,
        // Pass through the statusCode, so lower-level code can handle i.e. 401 properly.
        status: err.status
      };

      if (options.error) {
        // This `error` has signature of $.ajax, not Backbone.sync.
        options.error(resp);
      } else {
        throw err;
      }
    } else {
      // This `success` has signature of $.ajax, not Backbone.sync.
      options.success(body);
    }
  });
}

syncer.clientSync = clientSync;
syncer.serverSync = serverSync;
syncer.sync = function sync() {
  var syncMethod = isServer ? serverSync : clientSync;
  return syncMethod.apply(this, arguments);
};

/**
 * 'model' is either a model or collection that
 * has a 'url' property, which can be a string or function.
 */
syncer.getUrl = function getUrl(url, clientPrefix, params) {
  if (clientPrefix == null) {
    clientPrefix = false;
  }
  params = params || {};
  url = url || _.result(this, 'url');
  if (clientPrefix && !~url.indexOf('://')) {
    url = this.formatClientUrl(url, _.result(this, 'api'));
  }
  return this.interpolateParams(this, url, params);
};

syncer.formatClientUrl = function(url, api) {
  var prefix = this.app.get('apiPath') || '/api';
  if (api) {
    prefix += '/' + api;
  }
  prefix += '/-';
  return prefix + url;
};

/**
 * Deeply-compare two objects to see if they differ.
 */
syncer.objectsDiffer = function objectsDiffer(data1, data2) {
  var changed = false,
      keys,
      key,
      value1,
      value2;

  keys = _.unique(_.keys(data1).concat(_.keys(data2)));
  for (var i = 0, len = keys.length; i < len; i++) {
    key = keys[i];
    value1 = data1[key];
    value2 = data2[key];

    // If attribute is an object recurse
    if (_.isObject(value1) && _.isObject(value2)) {
      changed = this.objectsDiffer(value1, value2);
    // Test for equality
    } else if (!_.isEqual(value1, value2)) {
      changed = true;
    }
  }
  return changed;
};

/**
 * This maps i.e. '/listings/:id' to '/listings/3' if
 * the model you supply has model.get('id') == 3.
 */
syncer.interpolateParams = function interpolateParams(model, url, params) {
  var matches = url.match(extractParamNamesRe);

  params = params || {};

  if (matches) {
    matches.forEach(function(param) {
      var property = param.slice(1),
          value;

      // Is collection? Then use options.
      if (model.length != null) {
        value = model.options[property];

      // Otherwise it's a model; use attrs.
      } else {
        value = model.get(property);
      }
      url = url.replace(param, encodeURIComponent(value));

      /**
       * Delete the param from params hash, so we don't get urls like:
       * /v1/threads/1234?id=1234...
       */
      delete params[property];
    });
  }
  /**
   * Separate deletion of idAttribute from params hash necessary if using urlRoot in the model
   * so we don't get urls like: /v1/threads/1234?id=1234
   */
  delete params[model.idAttribute]
  return url;
};
<|endoftext|>


<commit_before>import messages from 'shared/messages';
import actions from '../actions';
import * as tabs from '../shared/tabs';
import * as bookmarks from '../shared/bookmarks';
import * as parsers from 'shared/commands/parsers';
import * as properties from 'shared/settings/properties';

const openCommand = (url) => {
  return browser.tabs.query({
    active: true, currentWindow: true
  }).then((gotTabs) => {
    if (gotTabs.length > 0) {
      return browser.tabs.update(gotTabs[0].id, { url: url });
    }
  });
};

const tabopenCommand = (url) => {
  return browser.tabs.create({ url: url });
};

const tabcloseCommand = () => {
  return browser.tabs.query({ active: true }).then((tabList) => {
    return browser.tabs.remove(tabList.map(tab => tab.id));
  });
};

const winopenCommand = (url) => {
  return browser.windows.create({ url });
};

const bufferCommand = (keywords) => {
  if (keywords.length === 0) {
    return Promise.resolve([]);
  }
  let keywordsStr = keywords.join(' ');
  return browser.tabs.query({
    active: true, currentWindow: true
  }).then((gotTabs) => {
    if (gotTabs.length > 0) {
      if (isNaN(keywordsStr)) {
        return tabs.selectByKeyword(gotTabs[0], keywordsStr);
      }
      let index = parseInt(keywordsStr, 10) - 1;
      return tabs.selectAt(index);
    }
  });
};

const addBookmarkCommand = (tab, args) => {
  if (!args[0]) {
    return Promise.resolve();
  }

  return bookmarks.create(args.join(' '), tab.url);
};

const setCommand = (args) => {
  if (!args[0]) {
    return Promise.resolve();
  }

  let [name, value] = parsers.parseSetOption(args[0], properties.types);
  return {
    type: actions.SETTING_SET_PROPERTY,
    name,
    value
  };
};

// eslint-disable-next-line complexity
const exec = (tab, line, settings) => {
  let [name, args] = parsers.parseCommandLine(line);

  switch (name) {
  case 'o':
  case 'open':
    return openCommand(parsers.normalizeUrl(args, settings.search));
  case 't':
  case 'tabopen':
    return tabopenCommand(parsers.normalizeUrl(args, settings.search));
  case 'w':
  case 'winopen':
    return winopenCommand(parsers.normalizeUrl(args, settings.search));
  case 'b':
  case 'buffer':
    return bufferCommand(args);
  case 'bd':
  case 'bdel':
  case 'bdelete':
    return tabs.closeTabByKeywords(args.join(' '));
  case 'bd!':
  case 'bdel!':
  case 'bdelete!':
    return tabs.closeTabByKeywordsForce(args.join(' '));
  case 'bdeletes':
    return tabs.closeTabsByKeywords(args.join(' '));
  case 'bdeletes!':
    return tabs.closeTabsByKeywordsForce(args.join(' '));
  case 'addbookmark':
    return addBookmarkCommand(tab, args).then((item) => {
      if (!item) {
        return browser.tabs.sendMessage(tab.id, {
          type: messages.CONSOLE_SHOW_ERROR,
          text: 'Could not create a bookmark',
        });
      }
      return browser.tabs.sendMessage(tab.id, {
        type: messages.CONSOLE_SHOW_INFO,
        text: 'Saved current page: ' + item.url,
      });
    });
  case 'set':
    return setCommand(args);
  case 'q':
  case 'quit':
    return tabcloseCommand();
  case '':
    return Promise.resolve();
  }
  throw new Error(name + ' command is not defined');
};

export { exec };
<commit_msg>Fix quit command<commit_after>import messages from 'shared/messages';
import actions from '../actions';
import * as tabs from '../shared/tabs';
import * as bookmarks from '../shared/bookmarks';
import * as parsers from 'shared/commands/parsers';
import * as properties from 'shared/settings/properties';

const openCommand = (url) => {
  return browser.tabs.query({
    active: true, currentWindow: true
  }).then((gotTabs) => {
    if (gotTabs.length > 0) {
      return browser.tabs.update(gotTabs[0].id, { url: url });
    }
  });
};

const tabopenCommand = (url) => {
  return browser.tabs.create({ url: url });
};

const tabcloseCommand = () => {
  return browser.tabs.query({
    active: true, currentWindow: true
  }).then((tabList) => {
    return browser.tabs.remove(tabList.map(tab => tab.id));
  });
};

const winopenCommand = (url) => {
  return browser.windows.create({ url });
};

const bufferCommand = (keywords) => {
  if (keywords.length === 0) {
    return Promise.resolve([]);
  }
  let keywordsStr = keywords.join(' ');
  return browser.tabs.query({
    active: true, currentWindow: true
  }).then((gotTabs) => {
    if (gotTabs.length > 0) {
      if (isNaN(keywordsStr)) {
        return tabs.selectByKeyword(gotTabs[0], keywordsStr);
      }
      let index = parseInt(keywordsStr, 10) - 1;
      return tabs.selectAt(index);
    }
  });
};

const addBookmarkCommand = (tab, args) => {
  if (!args[0]) {
    return Promise.resolve();
  }

  return bookmarks.create(args.join(' '), tab.url);
};

const setCommand = (args) => {
  if (!args[0]) {
    return Promise.resolve();
  }

  let [name, value] = parsers.parseSetOption(args[0], properties.types);
  return {
    type: actions.SETTING_SET_PROPERTY,
    name,
    value
  };
};

// eslint-disable-next-line complexity
const exec = (tab, line, settings) => {
  let [name, args] = parsers.parseCommandLine(line);

  switch (name) {
  case 'o':
  case 'open':
    return openCommand(parsers.normalizeUrl(args, settings.search));
  case 't':
  case 'tabopen':
    return tabopenCommand(parsers.normalizeUrl(args, settings.search));
  case 'w':
  case 'winopen':
    return winopenCommand(parsers.normalizeUrl(args, settings.search));
  case 'b':
  case 'buffer':
    return bufferCommand(args);
  case 'bd':
  case 'bdel':
  case 'bdelete':
    return tabs.closeTabByKeywords(args.join(' '));
  case 'bd!':
  case 'bdel!':
  case 'bdelete!':
    return tabs.closeTabByKeywordsForce(args.join(' '));
  case 'bdeletes':
    return tabs.closeTabsByKeywords(args.join(' '));
  case 'bdeletes!':
    return tabs.closeTabsByKeywordsForce(args.join(' '));
  case 'addbookmark':
    return addBookmarkCommand(tab, args).then((item) => {
      if (!item) {
        return browser.tabs.sendMessage(tab.id, {
          type: messages.CONSOLE_SHOW_ERROR,
          text: 'Could not create a bookmark',
        });
      }
      return browser.tabs.sendMessage(tab.id, {
        type: messages.CONSOLE_SHOW_INFO,
        text: 'Saved current page: ' + item.url,
      });
    });
  case 'set':
    return setCommand(args);
  case 'q':
  case 'quit':
    return tabcloseCommand();
  case '':
    return Promise.resolve();
  }
  throw new Error(name + ' command is not defined');
};

export { exec };
<|endoftext|>


<commit_before>#!/usr/bin/env node
/* icecapd */

var init = require('init'),
    fs = require('fs'),
    path = require('path'),
    config = {};

/* Read (optional) configuration file */
(function() {
	var home = process.env.HOME || __dirname,
	    dir = path.resolve(home, '.icecapd-js'),
	    file = path.resolve(dir, 'config.json');
	try {
		if(!path.existsSync(dir)) fs.mkdirSync(dir, 0700);
		if(path.existsSync(file)) {
			config = JSON.parse(fs.readFileSync(file, 'utf-8'));
		}
	} catch(e) {
		// Do nothing
	}

	if(!config.dir) config.dir = dir;
})();

/* Setup configurations */
(function() {
	var arg = process.argv[2],
	    value = process.argv[3];
	if((arg === 'config') && value) {

	}
})();

/* Setup standard init CLI */
init.simple({
	pidfile : config.pidfile || path.resolve(config.dir, 'run.pid'),
	logfile : config.logfile,
	command : process.argv[2],
	run     : function () {

		var io = require('socket.io-client'),
		    sys = require('sys'),
		    util = require('util'),
		    website_socket = io.connect(config.iotarget || 'http://localhost:3000/shell'),
		    icecap = require('icecap').create();

		// Lets handle errors
		website_socket.on('error', function (msg) {
			console.error('Error: ' + msg);
		});

		// Let's log every icecap event
		icecap.on('event', function(name, tokens) {
			util.log("DEBUG: icecap.on(event): " + sys.inspect(name) + ": " + sys.inspect(tokens) );
		});

		// Lets handle succesful connection
		website_socket.on('connect', function () {
			util.log('Connected to website and sending our apikey');

			// Let's handle successful join
			website_socket.on('joined', function() {
				util.log('Joined to website');

				// Let's send each icecap event to the website
				icecap.on('event', function(name, tokens) {
					util.log('Sending icecap-event to website...');
					website_socket.emit('icecap-event', name, tokens);
				});

				// Let's receive icecap.commands and send them to the icecap
				website_socket.on('icecap.command', function(name, tokens) {
					util.log("DEBUG: website_socket.on(client-event): " + sys.inspect(name) + ": " + sys.inspect(tokens) );
					icecap.command(name, tokens);
				});
			});

			// Send join request with our apikey
			website_socket.emit('join', config.apikey);

		});
	}
});

/* EOF */
<commit_msg>Updated<commit_after>#!/usr/bin/env node
/* icecapd */

var init = require('init'),
    fs = require('fs'),
    path = require('path'),
    sys = require('sys'),
    config = {};

/* Read (optional) configuration file */
(function() {
	var home = process.env.HOME || __dirname,
	    dir = path.resolve(home, '.icecapd-js'),
	    file = path.resolve(dir, 'config.json');
	try {
		if(!path.existsSync(dir)) fs.mkdirSync(dir, 0700);
		if(path.existsSync(file)) {
			config = JSON.parse(fs.readFileSync(file, 'utf-8'));
		}
	} catch(e) {
		// Do nothing
	}

	if(!config.dir) config.dir = dir;

	/* Setup configurations */
	(function() {
		var arg = process.argv[2],
		    key = process.argv[3],
		    value = process.argv[4],
			changed,
			exit;
		if((arg === 'config-set') && key) {
			config[key] = value;
			changed = true;
			exit = true;
		}
		if(arg === 'config') {
			console.log('Config from file `' + file + "`:" );
			console.log(sys.inspect(config));
			exit = true;
		}

		if(changed) {
			fs.writeFileSync(file, JSON.stringify(config));
			console.log('Saved.');
		}

		if(exit) process.exit(0);
	})();

})();

/* Setup standard init CLI */
init.simple({
	pidfile : config.pidfile || path.resolve(config.dir, 'run.pid'),
	logfile : config.logfile,
	command : process.argv[2],
	run     : function () {

		var io = require('socket.io-client'),
		    util = require('util'),
		    website_socket = io.connect(config.iotarget || 'http://localhost:3000/shell'),
		    icecap = require('icecap').create();

		// Lets handle errors
		website_socket.on('error', function (msg) {
			console.error('Error: ' + msg);
		});

		// Let's log every icecap event
		icecap.on('event', function(name, tokens) {
			util.log("DEBUG: icecap.on(event): " + sys.inspect(name) + ": " + sys.inspect(tokens) );
		});

		// Lets handle succesful connection
		website_socket.on('connect', function () {
			util.log('Connected to website and sending our apikey');

			// Let's handle successful join
			website_socket.on('joined', function() {
				util.log('Joined to website');

				// Let's send each icecap event to the website
				icecap.on('event', function(name, tokens) {
					util.log('Sending icecap-event to website...');
					website_socket.emit('icecap-event', name, tokens);
				});

				// Let's receive icecap.commands and send them to the icecap
				website_socket.on('icecap.command', function(name, tokens) {
					util.log("DEBUG: website_socket.on(client-event): " + sys.inspect(name) + ": " + sys.inspect(tokens) );
					icecap.command(name, tokens);
				});
			});

			// Send join request with our apikey
			website_socket.emit('join', config.apikey);

		});
	}
});

/* EOF */
<|endoftext|>


<commit_before>window.onload = function() {
    socket = new WebSocket("ws://192.168.12.50:10080");
    socket.onmessage = function(event) {
	document.getElementById('news').innerHTML = event.data;
    }
}
<commit_msg>client-server system server side finished<commit_after>var topic_data,type_data;
var topics = [], type =[], topics_len, type_len;

window.onload = function() {
    socket_topic = new WebSocket("ws://localhost:10080");
    socket_type = new WebSocket("ws://localhost:10081");
    socket_topic.onmessage = function(event) {
	topic_data= event.data.split("\n");
	topic_len = topic_data.length;
	for(var i = 0; i < topic_len; i++){
	    topics = topic_data[i];
	}
    }
    socket_type.onmessage=function(event){
	type_data = event.data.split("\n");
	type_len = event.data.split("\n");
	for(var i = 0; i< type_len; i++){
	    type = type_data[i];
	}
    }
    var ros = new ROSLIB.Ros({
	url:"ws://localhost:9090"
    });

    ros.on("connection",function(){
	console.log("Connected to websocket server.");
    });
    ros.on('error', function(error) {
	console.log('Error connecting to websocket server: ', error);
    });

    ros.on('close', function() {
    console.log('Connection to websocket server closed.');
  });
}
<|endoftext|>


<commit_before>// import Buttons from './Buttons.react';
import Component from 'react-pure-render/component';
import Helmet from 'react-helmet';
// import NewTodo from './NewTodo.react';
import React, { PropTypes } from 'react';
import Debtors from './Debtors.react';
import { fetchDebtors } from '../../common/debtors/actions';
import { defineMessages, injectIntl, intlShape } from 'react-intl';
import fetch from '../../common/components/fetch';

const messages = defineMessages({
  title: {
    id: 'debtors.page.title',
    defaultMessage: '借款人管理'
  }
});

class Page extends Component {
  static propTypes = {
    intl: intlShape.isRequired,
    children: PropTypes.object
  };

  render() {
    const { children, intl } = this.props;
    const title = intl.formatMessage(messages.title);
    return (

        <Helmet title={title} />
        {children || <Debtors />}

    );
  }

}

Page = fetch(fetchDebtors)(Page);

export default injectIntl(Page);
<commit_msg>removed auto fetchDebtors<commit_after>// import Buttons from './Buttons.react';
import Component from 'react-pure-render/component';
import Helmet from 'react-helmet';
// import NewTodo from './NewTodo.react';
import React, { PropTypes } from 'react';
import Debtors from './Debtors.react';
// import { fetchDebtors } from '../../common/debtors/actions';
import { defineMessages, injectIntl, intlShape } from 'react-intl';
// import fetch from '../../common/components/fetch';

const messages = defineMessages({
  title: {
    id: 'debtors.page.title',
    defaultMessage: '借款人管理'
  }
});

class Page extends Component {
  static propTypes = {
    intl: intlShape.isRequired,
    children: PropTypes.object
  };

  render() {
    const { children, intl } = this.props;
    const title = intl.formatMessage(messages.title);
    return (

        <Helmet title={title} />
        {children || <Debtors />}

    );
  }

}

// Page = fetch(fetchDebtors)(Page);

export default injectIntl(Page);
<|endoftext|>


<commit_before><commit_msg>Update LMexpress.js<commit_after><|endoftext|>